Documentation ¶
Index ¶
- Constants
- Variables
- func AllowWhitespace(s string) string
- func AsBool(v string) bool
- func AssembleAppFQDN(localClusterName string, localProxyDNSName string, appClusterName string, ...) string
- func BcryptFromPassword(password []byte, cost int) ([]byte, error)
- func ByteCount(b int64) string
- func CalculateSPKI(cert *x509.Certificate) string
- func CanUserWriteTo(path string) (bool, error)
- func ChainHTTPMiddlewares(handler http.Handler, middlewares ...HTTPMiddleware) http.Handler
- func CheckCertificateFormatFlag(s string) (string, error)
- func CheckSPKI(pins []string, certs []*x509.Certificate) error
- func CheckVersion(currentVersion, minVersion string) error
- func ChooseRandomString(slice []string) string
- func CipherSuiteMapping(cipherSuites []string) ([]uint16, error)
- func ClickableURL(in string) string
- func ClientIPFromConn(conn net.Conn) (string, error)
- func Color(color int, v interface{}) string
- func CompileExpression(expression string) (*regexp.Regexp, error)
- func CompressTarGzArchive(files []string, fileReader ReadStatFS) (*bytes.Buffer, error)
- func ContainsExpansion(val string) bool
- func CopyFile(src, dest string, perm os.FileMode) error
- func CopyStringsMap(in map[string]string) map[string]string
- func CryptoRandomHex(length int) (string, error)
- func DNSName(hostport string) (string, error)
- func DefaultCipherSuites() []uint16
- func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (net.Conn, net.Conn, error)
- func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)
- func EscapeControl(s string) string
- func Extract(r io.Reader, dir string) error
- func FSTryReadLock(filePath string) (unlock func() error, err error)
- func FSTryReadLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
- func FSTryWriteLock(filePath string) (unlock func() error, err error)
- func FSTryWriteLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
- func FastMarshal(v interface{}) ([]byte, error)
- func FastMarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
- func FastUnmarshal(data []byte, v interface{}) error
- func FatalError(err error)
- func FileExists(fp string) bool
- func FnCacheGet[T any](ctx context.Context, cache *FnCache, key any, ...) (T, error)
- func FnCacheGetWithTTL[T any](ctx context.Context, cache *FnCache, key any, ttl time.Duration, ...) (T, error)
- func FormatAlert(alert types.ClusterAlert) string
- func FormatErrorWithNewline(err error) string
- func FromSlice[T any](r []T, key func(T) string) map[string]T
- func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
- func GetAndReplaceRequestBody(req *http.Request) ([]byte, error)
- func GetAndReplaceResponseBody(response *http.Response) ([]byte, error)
- func GetAnyHeader(header http.Header, keys ...string) string
- func GetEC2InstanceIdentityDocument(ctx context.Context) (*imds.InstanceIdentityDocument, error)
- func GetEC2NodeID(ctx context.Context) (string, error)
- func GetHostUUIDPath(dataDir string) string
- func GetIterations() int
- func GetListenerFile(listener net.Listener) (*os.File, error)
- func GetRawEC2IdentityDocument(ctx context.Context) ([]byte, error)
- func GetSingleHeader(headers http.Header, key string) (string, error)
- func GlobToRegexp(in string) string
- func GuessHostIP() (ip net.IP, err error)
- func HasBTF() error
- func HasPrefixAny(prefix string, values []string) bool
- func Host(hostname string) (string, error)
- func HostUUIDExistsLocally(dataDir string) bool
- func InitCLIParser(appName, appHelp string) (app *kingpin.Application)
- func InitCertLeaves(certs []tls.Certificate) error
- func InitLogger(purpose LoggingPurpose, level slog.Level, opts ...LoggerOption)
- func InitLoggerForTests()
- func IsCertExpiredError(err error) bool
- func IsConnectionRefused(err error) bool
- func IsDir(path string) bool
- func IsFailedToSendCloseNotifyError(err error) bool
- func IsGroupMember(gid int) (bool, error)
- func IsHandshakeFailedError(err error) bool
- func IsLocalhost(host string) bool
- func IsOKNetworkError(err error) bool
- func IsPredicateError(err error) bool
- func IsRedirect(code int) bool
- func IsSelfSigned(certificateChain []*x509.Certificate) bool
- func IsUntrustedCertErr(err error) bool
- func IsUseOfClosedNetworkError(err error) bool
- func IsValidHostname(hostname string) bool
- func IsValidUnixUser(u string) bool
- func KernelVersion() (*semver.Version, error)
- func KubeResourceMatchesRegex(input types.KubernetesResource, resources []types.KubernetesResource) (bool, error)
- func KubeResourceMatchesRegexWithVerbsCollector(input types.KubernetesResource, resources []types.KubernetesResource) (bool, []string, error)
- func MajorSemver(version string) (string, error)
- func MarshalPrivateKey(key crypto.Signer) ([]byte, []byte, error)
- func MarshalPublicKey(signer crypto.Signer) ([]byte, error)
- func MatchString(input, expression string) (bool, error)
- func MeetsVersion(gotVer, minVer string) bool
- func MinTTL(a, b time.Duration) time.Duration
- func MinVerWithoutPreRelease(currentVersion, minVersion string) (bool, error)
- func MultiCloser(closers ...io.Closer) io.Closer
- func NetAddrsToStrings(netAddrs []NetAddr) []string
- func NewCertPoolFromPath(path string) (*x509.CertPool, error)
- func NewDefaultLinear() *retryutils.Linear
- func NewLogger() *logrus.Logger
- func NewLoggerForTests() *logrus.Logger
- func NewSlogLoggerForTests() *slog.Logger
- func NewStdlogger(logger LeveledOutputFunc, component string) *stdlog.Logger
- func NewSyslogHook(w io.Writer) (logrus.Hook, error)
- func NewSyslogWriter() (io.Writer, error)
- func NilCloser(r io.Closer) io.Closer
- func NodeIDFromIID(iid *imds.InstanceIdentityDocument) string
- func NoopHTTPMiddleware(next http.Handler) http.Handler
- func NopWriteCloser(r io.Writer) io.WriteCloser
- func NormalizePath(path string, evaluateSymlinks bool) (string, error)
- func ObeyIdleTimeout(conn net.Conn, timeout time.Duration) net.Conn
- func OpaqueAccessDenied(err error) error
- func OpenFileAllowingUnsafeLinks(path string) (*os.File, error)
- func OpenFileNoUnsafeLinks(path string) (*os.File, error)
- func ParseAdvertiseAddr(advertiseIP string) (string, string, error)
- func ParsePrivateKey(bytes []byte) (crypto.Signer, error)
- func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)
- func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)
- func ParsePublicKey(bytes []byte) (crypto.PublicKey, error)
- func PercentUsed(path string) (float64, error)
- func ProxyConn(ctx context.Context, client, server io.ReadWriteCloser) error
- func RandomDuration(max time.Duration) time.Duration
- func ReadAtMost(r io.Reader, limit int64) ([]byte, error)
- func ReadCertificates(certificateChainBytes []byte) ([]*x509.Certificate, error)
- func ReadCertificatesFromPath(path string) ([]*x509.Certificate, error)
- func ReadHostUUID(dataDir string) (string, error)
- func ReadOrMakeHostUUID(dataDir string) (string, error)
- func ReadPath(path string) ([]byte, error)
- func ReadYAML(reader io.Reader) (interface{}, error)
- func RecursiveChown(dir string, uid, gid int) error
- func RecursiveCopy(src, dest string, skip func(src, dest string) (bool, error)) error
- func RegexMatchesAny(inputs []string, expression string) (bool, error)
- func RegexpWithConfig(expression string, config RegexpConfig) (*regexp.Regexp, error)
- func RemoveAllSecure(path string) error
- func RemoveFileIfExist(filePath string) error
- func RemoveFromSlice(slice []string, values ...string) []string
- func RemoveSecure(filePath string) error
- func RenameHeader(header http.Header, oldKey, newKey string)
- func ReplaceInSlice(s []string, old string, new string) []string
- func ReplaceLocalhost(addr, replaceWith string) string
- func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)
- func ReplaceRegexpWith(expr *regexp.Regexp, replaceWith string, input string) (string, error)
- func ReplaceRequestBody(req *http.Request, newBody io.ReadCloser) error
- func ReplaceUnspecifiedHost(addr *NetAddr, defaultPort int) string
- func Round(x float64) float64
- func Roundtrip(addr string) (string, error)
- func RoundtripWithConn(conn net.Conn) (string, error)
- func SetupTLSConfig(config *tls.Config, cipherSuites []uint16)
- func SliceMatchesRegex(input string, expressions []string) (bool, error)
- func SplitHostPort(hostname string) (string, string, error)
- func SplitIdentifiers(s string) []string
- func StatDir(path string) (os.FileInfo, error)
- func StatFile(path string) (os.FileInfo, error)
- func StoreErrorOf(f func() error, err *error)
- func StreamJSONArray[T any](items stream.Stream[T], out io.Writer, indent bool) error
- func StringMapsEqual(a, b map[string]string) bool
- func StringSliceSubset(a []string, b []string) error
- func StringsSet(in []string) map[string]struct{}
- func StringsSliceFromSet(in map[string]struct{}) []string
- func SwitchLoggingToSyslog() error
- func TLSCertLeaf(cert tls.Certificate) (*x509.Certificate, error)
- func TLSConfig(cipherSuites []uint16) *tls.Config
- func ThisFunction() string
- func ToJSON(data []byte) ([]byte, error)
- func ToLowerCaseASCII(in string) string
- func ToTTL(c clockwork.Clock, tm time.Time) time.Duration
- func TryReadValueAsFile(value string) (string, error)
- func UintSliceSubset(a []uint16, b []uint16) error
- func UnsafeSliceData[T any](slice []T) (*T, error)
- func UpdateAppUsageTemplate(app *kingpin.Application, args []string)
- func UserMessageFromError(err error) string
- func VerifyCertificateChain(certificateChain []*x509.Certificate) error
- func VerifyCertificateExpiry(c *x509.Certificate, clock clockwork.Clock) error
- func VersionBeforeAlpha(version string) string
- func WriteCloserWithContext(ctx context.Context, closer WriteContextCloser) io.WriteCloser
- func WriteHostUUID(dataDir string, id string) error
- func WriteJSON(w io.Writer, values interface{}) error
- func WriteJSONArray[T any](w io.Writer, values []T) error
- func WriteJSONObject[M ~map[K]V, K comparable, V any](w io.Writer, m M) error
- func WriteYAML(w io.Writer, values interface{}) error
- type Anonymizer
- type BufferSyncPool
- type CaptureNBytesWriter
- type CircularBuffer
- type CloseBroadcaster
- type CloseFunc
- type CloserConn
- type CombinedReadWriteCloser
- type ConnWithAddr
- type Fields
- type FieldsCondition
- type FnCache
- type FnCacheConfig
- type HMACAnonymizer
- type HTTPDoClient
- type HTTPMiddleware
- type InMemoryFile
- type JumpHost
- type KeyStore
- type LeveledOutputFunc
- type LoadBalancer
- type Logger
- type LoggerOption
- type LoggingFormat
- type LoggingPurpose
- type NetAddr
- func AddrsFromStrings(s apiutils.Strings, defaultPort int) ([]NetAddr, error)
- func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr
- func FromAddr(a net.Addr) NetAddr
- func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr
- func MustParseAddr(a string) *NetAddr
- func MustParseAddrList(aList ...string) []NetAddr
- func ParseAddr(a string) (*NetAddr, error)
- func ParseAddrs(addrs []string) (result []NetAddr, err error)
- func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error)
- func (a *NetAddr) FullAddress() string
- func (a *NetAddr) Host() string
- func (a *NetAddr) IsEmpty() bool
- func (a *NetAddr) IsHostUnspecified() bool
- func (a *NetAddr) IsLocal() bool
- func (a *NetAddr) IsLoopback() bool
- func (a *NetAddr) MarshalYAML() (interface{}, error)
- func (a *NetAddr) Network() string
- func (a *NetAddr) Port(defaultPort int) int
- func (a *NetAddr) Set(s string) error
- func (a *NetAddr) String() string
- func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error
- type OpenFileWithFlagsFunc
- type PipeNetConn
- func (nc *PipeNetConn) Close() error
- func (nc *PipeNetConn) LocalAddr() net.Addr
- func (nc *PipeNetConn) Read(buf []byte) (n int, e error)
- func (nc *PipeNetConn) RemoteAddr() net.Addr
- func (nc *PipeNetConn) SetDeadline(t time.Time) error
- func (nc *PipeNetConn) SetReadDeadline(t time.Time) error
- func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error
- func (nc *PipeNetConn) Write(buf []byte) (n int, e error)
- type PortList
- type PredicateError
- type ReadStatFS
- type RegexpConfig
- type RepeatReader
- type RoundRobin
- type SlicePool
- type SliceSyncPool
- type Stater
- type SyncBuffer
- type SyncMap
- type SyncString
- type SyncWriter
- type TLSConn
- type Tracer
- type TrackingConn
- type TrackingReader
- type TrackingWriter
- type UID
- type WebLinks
- type WriteContextCloser
Constants ¶
const ( // Bold is an escape code to format as bold or increased intensity Bold = 1 // Red is an escape code for red terminal color Red = 31 // Yellow is an escape code for yellow terminal color Yellow = 33 // Blue is an escape code for blue terminal color Blue = 36 // Gray is an escape code for gray terminal color Gray = 37 )
const ( // DefaultLRUCapacity is a capacity for LRU session cache DefaultLRUCapacity = 1024 // DefaultCertTTL sets the TTL of the self-signed certificate (1 year) DefaultCertTTL = (24 * time.Hour) * 365 )
const ( // CertTeleportUser specifies teleport user CertTeleportUser = "x-teleport-user" // CertTeleportUserCA specifies teleport certificate authority CertTeleportUserCA = "x-teleport-user-ca" // CertExtensionRole specifies teleport role CertExtensionRole = "x-teleport-role" // CertExtensionAuthority specifies teleport authority's name // that signed this domain CertExtensionAuthority = "x-teleport-authority" // HostUUIDFile is the file name where the host UUID file is stored HostUUIDFile = "host_uuid" // CertTeleportClusterName is a name of the teleport cluster CertTeleportClusterName = "x-teleport-cluster-name" // CertTeleportUserCertificate is the certificate of the authenticated in user. CertTeleportUserCertificate = "x-teleport-certificate" // ExtIntCertType is an internal extension used to propagate cert type. ExtIntCertType = "certtype@teleport" // ExtIntCertTypeHost indicates a host-type certificate. ExtIntCertTypeHost = "host" // ExtIntCertTypeUser indicates a user-type certificate. ExtIntCertTypeUser = "user" )
const ( // FSLockRetryDelay is a delay between attempts to acquire lock. FSLockRetryDelay = 10 * time.Millisecond )
const ( // KubeCustomResource is the type that represents a Kubernetes // CustomResource object. These objects are special in that they do not exist // in the user's resources list, but their access is determined by the // access level of their namespace resource. KubeCustomResource = "CustomResource" )
const PortStartingNumber = 20000
PortStartingNumber is a starting port number for tests
const (
// SelfSignedCertsMsg is a helper message to point users towards helpful documentation.
SelfSignedCertsMsg = "Your proxy certificate is not trusted or expired. " +
"Please update the certificate or follow this guide for self-signed certs: https://goteleport.com/docs/management/admin/self-signed-certs/"
)
Variables ¶
var ErrFnCacheClosed = errors.New("fncache permanently closed")
ErrFnCacheClosed is returned from Get when the FnCache context is closed
var ErrLimitReached = &trace.LimitExceededError{Message: "the read limit is reached"}
ErrLimitReached means that the read limit is reached.
var ErrUnsuccessfulLockTry = errors.New("could not acquire lock on the file at this time")
ErrUnsuccessfulLockTry designates an error when we temporarily couldn't acquire lock (most probably it was already locked by someone else), another try might succeed.
var FullJitter = retryutils.NewFullJitter()
FullJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls, and use a dedicated sharded jitter instance for any usecases that might scale with cluster size or request count.
var HalfJitter = retryutils.NewHalfJitter()
HalfJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls, and use a dedicated sharded jitter instance for any usecases that might scale with cluster size or request count.
var SafeConfig = jsoniter.Config{ EscapeHTML: false, MarshalFloatWith6Digits: true, ObjectFieldMustBeSimpleString: true, SortMapKeys: true, }.Froze()
SafeConfig uses jsoniter's ConfigFastest settings but enables map key sorting to ensure CompareAndSwap checks consistently succeed.
var SafeConfigWithIndent = jsoniter.Config{ IndentionStep: 2, EscapeHTML: false, MarshalFloatWith6Digits: true, ObjectFieldMustBeSimpleString: true, SortMapKeys: true, }.Froze()
SafeConfigWithIndent is equivalent to SafeConfig except with indentation enabled.
var SeventhJitter = retryutils.NewSeventhJitter()
SeventhJitter is a global jitter instance used for one-off jitters. Prefer instantiating a new jitter instance for operations that require repeated calls, and use a dedicated sharded jitter instance for any usecases that might scale with cluster size or request count.
Functions ¶
func AllowWhitespace ¶
AllowWhitespace escapes all ANSI escape sequences except some whitespace characters (\n \t \v) from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:
func AsBool ¶
AsBool converts string to bool, in case of the value is empty or unknown, defaults to false
func AssembleAppFQDN ¶
func AssembleAppFQDN(localClusterName string, localProxyDNSName string, appClusterName string, app types.Application) string
AssembleAppFQDN returns the application's FQDN.
If the application is running within the local cluster and it has a public address specified, the application's public address is used.
In all other cases, i.e. if the public address is not set or the application is running in a remote cluster, the FQDN is formatted as <appName>.<localProxyDNSName>
func BcryptFromPassword ¶
BcryptFromPassword delegates to bcrypt.GenerateFromPassword, but maintains the prior behavior of only hashing the first 72 bytes. BCrypt as an algorithm can not hash inputs > 72 bytes.
func CalculateSPKI ¶
func CalculateSPKI(cert *x509.Certificate) string
CalculateSPKI the hash value of the SPKI header in a certificate.
func CanUserWriteTo ¶
CanUserWriteTo attempts to check if a user has write access to certain path. It also works around the program being run as root and tries to check the permissions of the user who executed the program as root. This should only be used for string formatting or inconsequential use cases as it's not bullet proof and can report wrong results.
func ChainHTTPMiddlewares ¶
func ChainHTTPMiddlewares(handler http.Handler, middlewares ...HTTPMiddleware) http.Handler
ChainHTTPMiddlewares wraps an http.Handler with a list of middlewares. Inner middlewares should be provided before outer middlewares.
func CheckCertificateFormatFlag ¶
CheckCertificateFormatFlag checks if the certificate format is valid.
func CheckSPKI ¶
func CheckSPKI(pins []string, certs []*x509.Certificate) error
CheckSPKI the passed in pin against the calculated value from a certificate.
func CheckVersion ¶
CheckVersion compares a version with a minimum version supported.
func ChooseRandomString ¶
ChooseRandomString returns a random string from the given slice.
func CipherSuiteMapping ¶
CipherSuiteMapping transforms Teleport formatted cipher suites strings into uint16 IDs.
func ClickableURL ¶
ClickableURL fixes address in url to make sure it's clickable, e.g. it replaces "undefined" address like 0.0.0.0 used in network listeners format with loopback 127.0.0.1
func ClientIPFromConn ¶
ClientIPFromConn extracts host from provided remote address.
func CompileExpression ¶
CompileExpression compiles the given regex expression with Teleport's custom globbing and quoting logic.
func CompressTarGzArchive ¶
func CompressTarGzArchive(files []string, fileReader ReadStatFS) (*bytes.Buffer, error)
CompressTarGzArchive creates a Tar Gzip archive in memory, reading the files using the provided file reader
func ContainsExpansion ¶
ContainsExpansion returns true if value contains expansion syntax, e.g. $1 or ${10}
func CopyStringsMap ¶
CopyStringsMap returns a copy of the strings map
func CryptoRandomHex ¶
CryptoRandomHex returns a hex-encoded random string generated with a crypto-strong pseudo-random generator. The length parameter controls how many random bytes are generated, and the returned hex string will be twice the length. An error is returned when fewer bytes were generated than length.
func DefaultCipherSuites ¶
func DefaultCipherSuites() []uint16
DefaultCipherSuites returns the default list of cipher suites that Teleport supports. By default Teleport only support modern ciphers (Chacha20 and AES GCM) and key exchanges which support perfect forward secrecy (ECDHE).
Note that TLS_RSA_WITH_AES_128_GCM_SHA{256,384} have been dropped due to being banned by HTTP2 which breaks gRPC clients. For more information see: https://tools.ietf.org/html/rfc7540#appendix-A. These two can still be manually added if needed.
func DualPipeNetConn ¶
DualPipeNetConn creates a pipe to connect a client and a server. The two net.Conn instances are wrapped in an PipeNetConn which holds the source and destination addresses.
The pipe is constructed from a syscall.Socketpair instead of a net.Pipe because the synchronous nature of net.Pipe causes it to deadlock when attempting to perform TLS or SSH handshakes.
func EnsureLocalPath ¶
EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in default gravity config directory, e.g.
EnsureLocalPath("/custom/myconfig", ".gravity", "config") -> /custom/myconfig EnsureLocalPath("", ".gravity", "config") -> ${HOME}/.gravity/config
It also makes sure that base dir exists
func EscapeControl ¶
EscapeControl escapes all ANSI escape sequences from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:
func Extract ¶
Extract extracts the contents of the specified tarball under dir. The resulting files and directories are created using the current user context. Extract will only unarchive files into dir, and will fail if the tarball tries to write files outside of dir.
func FSTryReadLock ¶
FSTryReadLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else
func FSTryReadLockTimeout ¶
func FSTryReadLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
FSTryReadLockTimeout tries to grab read lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.
func FSTryWriteLock ¶
FSTryWriteLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else
func FSTryWriteLockTimeout ¶
func FSTryWriteLockTimeout(ctx context.Context, filePath string, timeout time.Duration) (unlock func() error, err error)
FSTryWriteLockTimeout tries to grab write lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.
func FastMarshal ¶
FastMarshal uses the json-iterator library for fast JSON marshaling. Note, this function unmarshals floats with 6 digits precision.
func FastMarshalIndent ¶
FastMarshal uses the json-iterator library for fast JSON marshaling with indentation. Note, this function unmarshals floats with 6 digits precision.
func FastUnmarshal ¶
FastUnmarshal uses the json-iterator library for fast JSON unmarshalling. Note, this function marshals floats with 6 digits precision.
func FatalError ¶
func FatalError(err error)
FatalError is for CLI front-ends: it detects gravitational/trace debugging information, sends it to the logger, strips it off and prints a clean message to stderr
func FileExists ¶
FileExists checks whether a file exists at a given path
func FnCacheGet ¶
func FnCacheGet[T any](ctx context.Context, cache *FnCache, key any, loadfn func(ctx context.Context) (T, error)) (T, error)
FnCacheGet loads the result associated with the supplied key. If no result is currently stored, or the stored result was acquired >TTL ago, then loadfn is used to reload it. Subsequent calls while the value is being loaded/reloaded block until the first call updates the entry. Note that the supplied context can cancel the call to Get, but will not cancel loading. The supplied loadfn should not be canceled just because the specific request happens to have been canceled.
func FnCacheGetWithTTL ¶
func FnCacheGetWithTTL[T any](ctx context.Context, cache *FnCache, key any, ttl time.Duration, loadfn func(ctx context.Context) (T, error)) (T, error)
FnCacheGetWithTTL is identical to FnCacheGet except that it allows individual keys to specify a TTL that is used instead of the configured TTL for the FnCache.
func FormatAlert ¶
func FormatAlert(alert types.ClusterAlert) string
FormatAlert formats and colors the alert message if possible.
func FormatErrorWithNewline ¶
FormatErrorWithNewline returns user friendly error message from error. The error message is escaped if necessary. A newline is added if the error text does not end with a newline.
func FromSlice ¶
FromSlice converts the provided slice to a map using the key function to determine the appropriate key per entry. If any duplicates exist in the slice, then the entry with the lowest index is used.
func GenerateSelfSignedSigningCert ¶
func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
GenerateSelfSignedSigningCert generates self-signed certificate used for digital signatures
func GetAndReplaceRequestBody ¶
GetAndReplaceRequestBody returns the request body and replaces the drained body reader with io.NopCloser allowing for further body processing by http transport.
func GetAndReplaceResponseBody ¶
GetAndReplaceResponseBody returns the response body and replaces the drained body reader with io.NopCloser allowing for further body processing.
func GetAnyHeader ¶
GetAnyHeader returns the first non-empty value by the provided keys.
func GetEC2InstanceIdentityDocument ¶
func GetEC2InstanceIdentityDocument(ctx context.Context) (*imds.InstanceIdentityDocument, error)
func GetEC2NodeID ¶
GetEC2NodeID returns the node ID to use for this EC2 instance when using Simplified Node Joining.
func GetHostUUIDPath ¶
GetHostUUIDPath returns the path to the host UUID file given the data directory.
func GetIterations ¶
func GetIterations() int
GetIterations provides a simple way to add iterations to the test by setting environment variable "ITERATIONS", by default it returns 1
func GetListenerFile ¶
GetListenerFile returns file associated with listener
func GetRawEC2IdentityDocument ¶
GetRawEC2IdentityDocument fetches the PKCS7 RSA2048 InstanceIdentityDocument from the IMDS for this EC2 instance.
func GetSingleHeader ¶
GetSingleHeader will return the header value for the key if there is exactly one value present. If the header is missing or specified multiple times, an error will be returned.
func GlobToRegexp ¶
GlobToRegexp replaces glob-style standalone wildcard values with real .* regexp-friendly values, does not modify regexp-compatible values, quotes non-wildcard values
func GuessHostIP ¶
GuessIP tries to guess an IP address this machine is reachable at on the internal network, always picking IPv4 from the internal address space
If no internal IPs are found, it returns 127.0.0.1 but it never returns an address from the public IP space
func HasBTF ¶
func HasBTF() error
HasBTF checks that the kernel has been compiled with BTF support and that the type information can be opened. Returns nil if BTF is there and accessible, otherwise an error describing the problem.
func HasPrefixAny ¶
HasPrefixAny determines if any of the string values have the given prefix.
func HostUUIDExistsLocally ¶
HostUUIDExistsLocally checks if dataDir/host_uuid file exists in local storage.
func InitCLIParser ¶
func InitCLIParser(appName, appHelp string) (app *kingpin.Application)
InitCLIParser configures kingpin command line args parser with some defaults common for all Teleport CLI tools
func InitCertLeaves ¶
func InitCertLeaves(certs []tls.Certificate) error
InitCertLeaves initializes the Leaf field for each cert in a slice of certs, to reduce per-handshake processing. Typically, servers should avoid doing this since it will consume more memory.
func InitLogger ¶
func InitLogger(purpose LoggingPurpose, level slog.Level, opts ...LoggerOption)
InitLogger configures the global logger for a given purpose / verbosity level
func InitLoggerForTests ¶
func InitLoggerForTests()
InitLoggerForTests initializes the standard logger for tests.
func IsCertExpiredError ¶
IsCertExpiredError specifies whether this error indicates expired SSH certificate
func IsConnectionRefused ¶
IsConnectionRefused returns true if the given err is "connection refused" error.
func IsFailedToSendCloseNotifyError ¶
IsFailedToSendCloseNotifyError returns true if the provided error is the "tls: failed to send closeNotify".
func IsGroupMember ¶
IsGroupMember returns whether currently logged user is a member of a group
func IsHandshakeFailedError ¶
IsHandshakeFailedError specifies whether this error indicates failed handshake
func IsLocalhost ¶
IsLocalhost returns true if this is a local hostname or ip
func IsOKNetworkError ¶
IsOKNetworkError returns true if the provided error received from a network operation is one of those that usually indicate normal connection close. If the error is a trace.Aggregate, all the errors must be OK network errors.
func IsPredicateError ¶
IsPredicateError determines if the error is from failing to parse predicate expression by checking if the error as a string contains predicate keywords.
func IsRedirect ¶
IsRedirect returns true if the status code is a 3xx code.
func IsSelfSigned ¶
func IsSelfSigned(certificateChain []*x509.Certificate) bool
IsSelfSigned checks if the certificate is a self-signed certificate. To check if a certificate is self-signed, we make sure that only one certificate is in the chain and that the SubjectKeyId and AuthorityKeyId match.
From RFC5280: https://tools.ietf.org/html/rfc5280#section-4.2.1.1
The signature on a self-signed certificate is generated with the private key associated with the certificate's subject public key. (This proves that the issuer possesses both the public and private keys.) In this case, the subject and authority key identifiers would be identical, but only the subject key identifier is needed for certification path building.
func IsUntrustedCertErr ¶
IsUntrustedCertErr checks if an error is an untrusted cert error.
func IsUseOfClosedNetworkError ¶
IsUseOfClosedNetworkError returns true if the specified error indicates the use of a closed network connection.
func IsValidHostname ¶
IsValidHostname checks if a string represents a valid hostname.
func IsValidUnixUser ¶
IsValidUnixUser checks if a string represents a valid UNIX username.
func KernelVersion ¶
KernelVersion parses /proc/sys/kernel/osrelease and returns the kernel version of the host. This only returns something meaningful on Linux.
func KubeResourceMatchesRegex ¶
func KubeResourceMatchesRegex(input types.KubernetesResource, resources []types.KubernetesResource) (bool, error)
KubeResourceMatchesRegex checks whether the input matches any of the given expressions. This function returns as soon as it finds the first match or when matchString returns an error. This function supports regex expressions in the Name and Namespace fields, but not for the Kind field. The wildcard (*) expansion is also supported. input is the resource we are checking for access. resources is a list of resources that the user has access to - collected from their roles that match the Kubernetes cluster where the resource is defined.
func KubeResourceMatchesRegexWithVerbsCollector ¶
func KubeResourceMatchesRegexWithVerbsCollector(input types.KubernetesResource, resources []types.KubernetesResource) (bool, []string, error)
KubeResourceMatchesRegex checks whether the input matches any of the given expressions. This function returns as soon as it finds the first match or when MatchString returns an error. This function supports regex expressions in the Name and Namespace fields, but not for the Kind field. The wildcard (*) expansion is also supported.
func MajorSemver ¶
MajorSemver returns the major version as a semver string. Ex: 13.4.3 -> 13.0.0
func MarshalPrivateKey ¶
MarshalPrivateKey will return a PEM encoded crypto.Signer. Only supports RSA private keys.
func MarshalPublicKey ¶
MarshalPublicKey returns a PEM encoded public key for a given crypto.Signer
func MatchString ¶
MatchString will match an input against the given expression. The expression is cached for later use.
func MeetsVersion ¶
MeetsVersion returns true if gotVer is empty or at least minVer.
func MinVerWithoutPreRelease ¶
MinVerWithoutPreRelease compares semver strings, but skips prerelease. This allows to compare two versions and ignore dev,alpha,beta, etc. strings.
func MultiCloser ¶
MultiCloser implements io.Close, it sequentially calls Close() on each object
func NetAddrsToStrings ¶
NetAddrsToStrings takes a list of netAddrs and returns a list of address strings.
func NewCertPoolFromPath ¶
NewCertPoolFromPath creates a new x509.CertPool from provided path.
func NewDefaultLinear ¶
func NewDefaultLinear() *retryutils.Linear
NewDefaultLinear creates a linear retry with reasonable default parameters for attempting to restart "critical but potentially load-inducing" operations, such as watcher or control stream resume. Exact parameters are subject to change, but this retry will always be configured for automatic reset.
func NewLoggerForTests ¶
NewLoggerForTests creates a new logrus logger for test environments.
func NewSlogLoggerForTests ¶
NewSlogLoggerForTests creates a new slog logger for test environments.
func NewStdlogger ¶
func NewStdlogger(logger LeveledOutputFunc, component string) *stdlog.Logger
NewStdlogger creates a new stdlib logger that uses the specified leveled logger for output and the given component as a logging prefix.
func NewSyslogHook ¶
NewSyslogHook provides a logrus.Hook that sends output to syslog.
func NewSyslogWriter ¶
NewSyslogWriter creates a writer that outputs to the local machine syslog.
func NodeIDFromIID ¶
func NodeIDFromIID(iid *imds.InstanceIdentityDocument) string
NodeIDFromIID returns the node ID that must be used for nodes joining with the given Instance Identity Document.
func NoopHTTPMiddleware ¶
NoopHTTPMiddleware is a no-operation HTTPMiddleware that returns the original handler.
func NopWriteCloser ¶
func NopWriteCloser(r io.Writer) io.WriteCloser
NopWriteCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w
func NormalizePath ¶
NormalizePath normalises path, evaluating symlinks and converting local paths to absolute
func ObeyIdleTimeout ¶
ObeyIdleTimeout wraps an existing network connection, closing it if data isn't read often enough. The connection will be closed even if Read is never called, or if it's called on the underlying connection instead of the returned one.
func OpaqueAccessDenied ¶
OpaqueAccessDenied returns a generic NotFound instead of AccessDenied so as to avoid leaking the existence of secret resources.
func OpenFileAllowingUnsafeLinks ¶
OpenFileAllowingUnsafeLinks opens a file, if the path includes a symlink, the returned os.File will be resolved to the actual file. This will return an error if the file is not found or is a directory.
func OpenFileNoUnsafeLinks ¶
OpenFileNoUnsafeLinks opens a file, ensuring it's an actual file and not a directory or symlink. Depending on the os, it may also prevent hardlinks. This is important because MacOS allows hardlinks without validating write permissions (similar to a symlink in that regard).
func ParseAdvertiseAddr ¶
ParseAdvertiseAddr validates advertise address, makes sure it's not an unreachable or multicast address returns address split into host and port, port could be empty if not specified
func ParsePrivateKey ¶
ParsePrivateKey parses a PEM encoded private key and returns a crypto.Signer. Only supports RSA private keys.
func ParsePrivateKeyDER ¶
ParsePrivateKeyDER parses unencrypted DER-encoded private key
func ParsePrivateKeyPEM ¶
ParsePrivateKeyPEM parses PEM-encoded private key
func ParsePublicKey ¶
ParsePublicKey parses a PEM encoded public key and returns a crypto.PublicKey. Only support RSA public keys.
func PercentUsed ¶
PercentUsed returns percentage of disk space used. The percentage of disk space used is calculated from (total blocks - free blocks)/total blocks. The value is rounded to the nearest whole integer.
func ProxyConn ¶
func ProxyConn(ctx context.Context, client, server io.ReadWriteCloser) error
ProxyConn launches a double-copy loop that proxies traffic between the provided client and server connections.
Exits when one or both copies stop, or when the context is canceled, and closes both connections.
func RandomDuration ¶
RandomDuration returns a duration in a range [0, max)
func ReadAtMost ¶
ReadAtMost reads up to limit bytes from r, and reports an error when limit bytes are read.
func ReadCertificates ¶
func ReadCertificates(certificateChainBytes []byte) ([]*x509.Certificate, error)
ReadCertificates parses PEM encoded bytes that can contain one or multiple certificates and returns a slice of x509.Certificate.
func ReadCertificatesFromPath ¶
func ReadCertificatesFromPath(path string) ([]*x509.Certificate, error)
ReadCertificatesFromPath parses PEM encoded certificates from provided path.
func ReadHostUUID ¶
ReadHostUUID reads host UUID from the file in the data dir
func ReadOrMakeHostUUID ¶
ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, returns the UUID from it, otherwise generates one
func RecursiveChown ¶
func RecursiveCopy ¶
RecursivelyCopy will copy a directory from src to dest, if the directory exists, files will be overwritten. The skip paramater, if provided, will be passed the source and destination paths, and will skip files upon returning true
func RegexMatchesAny ¶
RegexMatchesAny returns true if [expression] matches any element of [inputs]. [expression] support globbing ("env-*") or normal regexp syntax if surrounded with ^$ ("^env-.*$").
func RegexpWithConfig ¶
func RegexpWithConfig(expression string, config RegexpConfig) (*regexp.Regexp, error)
RegexpWithConfig compiles a regular expression given some configuration. There are several important differences with standard lib (see ReplaceRegexp).
func RemoveAllSecure ¶
RemoveAllSecure is similar to os.RemoveAll but leverages RemoveSecure to delete files so that they are overwritten. This helps guard against hardware attacks on magnetic disks.
func RemoveFileIfExist ¶
RemoveFileIfExist removes file if exits.
func RemoveFromSlice ¶
RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.
func RemoveSecure ¶
RemoveSecure attempts to securely delete the file by first overwriting the file with random data three times followed by calling os.Remove(filePath).
func RenameHeader ¶
RenameHeader moves all values from the old header key to the new header key.
func ReplaceInSlice ¶
ReplaceInSlice replaces element old with new and returns a new slice.
func ReplaceLocalhost ¶
ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1) and replaces it with the IP taken from replaceWith, preserving the original port
Both addresses are in "host:port" format The function returns the original value if it encounters any problems with parsing
func ReplaceRegexp ¶
ReplaceRegexp replaces value in string, accepts regular expression and simplified wildcard syntax, it has several important differences with standard lib regexp replacer: * Wildcard globs '*' are treated as regular expression .* expression * Expression is treated as regular expression if it starts with ^ and ends with $ * Full match is expected, partial replacements ignored * If there is no match, returns a NotFound error
func ReplaceRegexpWith ¶
ReplaceRegexp replaces string in a given regexp.
func ReplaceRequestBody ¶
func ReplaceRequestBody(req *http.Request, newBody io.ReadCloser) error
ReplaceRequestBody drains the old request body and replaces it with a new one.
func ReplaceUnspecifiedHost ¶
ReplaceUnspecifiedHost replaces unspecified "0.0.0.0" with localhost since "0.0.0.0" is never a valid principal (auth server explicitly removes it when issuing host certs) and when a reverse tunnel client used establishes SSH reverse tunnel connection the host is validated against the valid principal list.
func Round ¶
Round returns the nearest integer, rounding half away from zero.
Special cases are:
Round(±0) = ±0 Round(±Inf) = ±Inf Round(NaN) = NaN
Note: Copied from Go standard library to support Go 1.9.7 releases. This function was added in the standard library in Go 1.10.
func Roundtrip ¶
Roundtrip is a single connection simplistic HTTP client that allows us to bypass a connection pool to test load balancing used in tests, as it only supports GET request on /
func RoundtripWithConn ¶
RoundtripWithConn uses HTTP GET on the existing connection, used in tests as it only performs GET request on /
func SetupTLSConfig ¶
SetupTLSConfig sets up cipher suites in existing TLS config
func SliceMatchesRegex ¶
SliceMatchesRegex checks if input matches any of the expressions. The match is always evaluated as a regex either an exact match or regexp.
func SplitHostPort ¶
SplitHostPort splits host and port and checks that host is not empty
func SplitIdentifiers ¶
SplitIdentifiers splits list of identifiers by commas/spaces/newlines. Helpful when accepting lists of identifiers in CLI (role names, request IDs, etc).
func StoreErrorOf ¶
StoreErrorOf stores the error returned by f within *err.
func StreamJSONArray ¶
StremJSONArray streams the elements of a stream.Stream as a json array with optional indentation (used to stream to CLI).
func StringMapsEqual ¶
StringMapsEqual returns true if two strings maps are equal
func StringSliceSubset ¶
StringSliceSubset returns true if b is a subset of a.
func StringsSet ¶
StringsSet creates set of string (map[string]struct{}) from a list of strings
func StringsSliceFromSet ¶
StringsSliceFromSet returns a sorted strings slice from set
func SwitchLoggingToSyslog ¶
func SwitchLoggingToSyslog() error
SwitchLoggingToSyslog configures the default logger to send output to syslog.
func TLSCertLeaf ¶
func TLSCertLeaf(cert tls.Certificate) (*x509.Certificate, error)
TLSCertLeaf is a helper function that extracts the parsed leaf *x509.Certificate from a tls.Certificate. If the leaf certificate is not parsed already, then this function parses it.
func ToJSON ¶
ToJSON converts a single YAML document into a JSON document or returns an error. If the document appears to be JSON the YAML decoding path is not used (so that error messages are JSON specific). Creds to: k8s.io for the code
func ToLowerCaseASCII ¶
ToLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use an explicitly ASCII function to avoid any sharp corners resulting from performing Unicode operations on DNS labels.
NOTE: copied verbatim from crypto/x509 source, including the above comments. Teleport uses this function to approximate a form of opt-in case-insensitivity for ssh hostnames
func ToTTL ¶
ToTTL converts expiration time to TTL duration relative to current time as provided by clock
func TryReadValueAsFile ¶
TryReadValueAsFile is a utility function to read a value from the disk if it looks like an absolute path, otherwise, treat it as a value. It only support absolute paths to avoid ambiguity in interpretation of the value
func UintSliceSubset ¶
UintSliceSubset returns true if b is a subset of a.
func UnsafeSliceData ¶
UnsafeSliceData is a wrapper around unsafe.SliceData which ensures that instead of ever returning "a non-nil pointer to an unspecified memory address" (see unsafe.SliceData documentation), an error is returned instead.
func UpdateAppUsageTemplate ¶
func UpdateAppUsageTemplate(app *kingpin.Application, args []string)
UpdateAppUsageTemplate updates usage template for kingpin applications by pre-parsing the arguments then applying any changes to the usage template if necessary.
func UserMessageFromError ¶
UserMessageFromError returns user-friendly error message from error. The error message will be formatted for output depending on the debug flag
func VerifyCertificateChain ¶
func VerifyCertificateChain(certificateChain []*x509.Certificate) error
VerifyCertificateChain reads in chain of certificates and makes sure the chain from leaf to root is valid. This ensures that clients (web browsers and CLI) won't have problem validating the chain.
func VerifyCertificateExpiry ¶
func VerifyCertificateExpiry(c *x509.Certificate, clock clockwork.Clock) error
VerifyCertificateExpiry checks the certificate's expiration status.
func VersionBeforeAlpha ¶
VersionBeforeAlpha appends "-aa" to the version so that it comes before <version>-alpha. This ban be used to make version checks work during development.
func WriteCloserWithContext ¶
func WriteCloserWithContext(ctx context.Context, closer WriteContextCloser) io.WriteCloser
WriteCloserWithContext converts ContextCloser to io.Closer, whenever new Close method will be called, the ctx will be passed to it
func WriteHostUUID ¶
WriteHostUUID writes host UUID into a file
func WriteJSONArray ¶
WriteJSONArray marshals values as a JSON array.
func WriteJSONObject ¶
func WriteJSONObject[M ~map[K]V, K comparable, V any](w io.Writer, m M) error
WriteJSONObject marshals m as a JSON object.
Types ¶
type Anonymizer ¶
type Anonymizer interface { // Anonymize returns anonymized string from the provided data Anonymize(data []byte) string // AnonymizeString anonymizes the given string data using HMAC AnonymizeString(s string) string // AnonymizeNonEmpty anonymizes the given string into bytes if the string is // nonempty, otherwise returns an empty slice. AnonymizeNonEmpty(s string) []byte }
Anonymizer defines an interface for anonymizing data
type BufferSyncPool ¶
BufferSyncPool is a sync pool of bytes.Buffer
func NewBufferSyncPool ¶
func NewBufferSyncPool(size int64) *BufferSyncPool
NewBufferSyncPool returns a new instance of sync pool of bytes.Buffers that creates new buffers with preallocated underlying buffer of size
func (*BufferSyncPool) Get ¶
func (b *BufferSyncPool) Get() *bytes.Buffer
Get returns a new or already allocated buffer
func (*BufferSyncPool) Put ¶
func (b *BufferSyncPool) Put(buf *bytes.Buffer)
Put resets the buffer (does not free the memory) and returns it back to the pool. Users should be careful not to use the buffer (e.g. via Bytes) after it was returned
func (*BufferSyncPool) Size ¶
func (b *BufferSyncPool) Size() int64
Size returns default allocated buffer size
type CaptureNBytesWriter ¶
type CaptureNBytesWriter struct {
// contains filtered or unexported fields
}
CaptureNBytesWriter is an io.Writer thats captures up to first n bytes of the incoming data in memory, and then it ignores the rest of the incoming data.
func NewCaptureNBytesWriter ¶
func NewCaptureNBytesWriter(max int) *CaptureNBytesWriter
NewCaptureNBytesWriter creates a new CaptureNBytesWriter.
func (CaptureNBytesWriter) Bytes ¶
func (w CaptureNBytesWriter) Bytes() []byte
Bytes returns all captured bytes.
type CircularBuffer ¶
CircularBuffer implements an in-memory circular buffer of predefined size
func NewCircularBuffer ¶
func NewCircularBuffer(size int) (*CircularBuffer, error)
NewCircularBuffer returns a new instance of a circular buffer that will hold size elements before it rotates
func (*CircularBuffer) Add ¶
func (t *CircularBuffer) Add(d float64)
Add pushes a new item onto the buffer
func (*CircularBuffer) Data ¶
func (t *CircularBuffer) Data(n int) []float64
Data returns the most recent n elements in the correct order
type CloseBroadcaster ¶
CloseBroadcaster is a helper struct that implements io.Closer and uses channel to broadcast it's closed state once called
func NewCloseBroadcaster ¶
func NewCloseBroadcaster() *CloseBroadcaster
NewCloseBroadcaster returns new instance of close broadcaster
func (*CloseBroadcaster) Close ¶
func (b *CloseBroadcaster) Close() error
Close closes channel (once) to start broadcasting it's closed state
type CloseFunc ¶
type CloseFunc func() error
CloseFunc is a helper used to implement io.Closer on a closure.
type CloserConn ¶
CloserConn wraps connection and attaches additional closers to it
func NewCloserConn ¶
func NewCloserConn(conn net.Conn, closers ...io.Closer) *CloserConn
NewCloserConn returns new connection wrapper that when closed will also close passed closers
func (*CloserConn) AddCloser ¶
func (c *CloserConn) AddCloser(closer io.Closer)
AddCloser adds any closer in ctx that will be called whenever server closes session channel
func (*CloserConn) Close ¶
func (c *CloserConn) Close() error
Close connection, all closers, and cancel context.
func (*CloserConn) Context ¶
func (c *CloserConn) Context() context.Context
Context returns a context that is canceled once the connection is closed.
type CombinedReadWriteCloser ¶
type CombinedReadWriteCloser struct {
// contains filtered or unexported fields
}
CombinedReadWriteCloser wraps an io.ReadCloser and an io.WriteCloser to implement io.ReadWriteCloser. Reads are performed on the io.ReadCloser and writes are performed on the io.WriteCloser. Closing will return the aggregated errors of both.
func CombineReadWriteCloser ¶
func CombineReadWriteCloser(r io.ReadCloser, w io.WriteCloser) CombinedReadWriteCloser
CombineReadWriteCloser creates a CombinedReadWriteCloser from the provided io.ReadCloser and io.WriteCloser that implements io.ReadWriteCloser
func (CombinedReadWriteCloser) Close ¶
func (o CombinedReadWriteCloser) Close() error
type ConnWithAddr ¶
ConnWithAddr is a net.Conn wrapper that allows the local and remote address to be overridden.
func NewConnWithAddr ¶
func NewConnWithAddr(conn net.Conn, localAddr, remoteAddr net.Addr) *ConnWithAddr
NewConnWithAddr wraps a net.Conn optionally overriding the local and remote addresses with the provided ones, if non-nil.
func NewConnWithSrcAddr ¶
func NewConnWithSrcAddr(conn net.Conn, clientSrcAddr net.Addr) *ConnWithAddr
NewConnWithSrcAddr wraps provided connection and overrides client remote address.
func (*ConnWithAddr) LocalAddr ¶
func (c *ConnWithAddr) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*ConnWithAddr) NetConn ¶
func (c *ConnWithAddr) NetConn() net.Conn
NetConn returns the underlying net.Conn.
func (*ConnWithAddr) RemoteAddr ¶
func (c *ConnWithAddr) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
type Fields ¶
type Fields map[string]interface{}
Fields represents a generic string-keyed map.
func (Fields) GetStrings ¶
GetStrings returns a slice-of-strings representation of a field.
type FieldsCondition ¶
FieldsCondition is a boolean function on Fields.
func ToFieldsCondition ¶
func ToFieldsCondition(expr *types.WhereExpr) (FieldsCondition, error)
ToFieldsCondition converts a WhereExpr into a FieldsCondition.
type FnCache ¶
type FnCache struct {
// contains filtered or unexported fields
}
FnCache is a helper for temporarily storing the results of regularly called functions. This helper is used to limit the amount of backend reads that occur while the primary cache is unhealthy. Most resources do not require this treatment, however, certain resources (cas, nodes, etc.) can be loaded on a per-request basis and can cause a significant number of backend reads if the cache is unhealthy or taking a while to initialize.
func NewFnCache ¶
func NewFnCache(cfg FnCacheConfig) (*FnCache, error)
NewFnCache creates a FnCache from the provided FnCacheConfig.
func (*FnCache) RemoveExpired ¶
func (c *FnCache) RemoveExpired()
RemoveExpired purges any items from the cache which have exceeded their TTL.
type FnCacheConfig ¶
type FnCacheConfig struct { // TTL is the time to live for cache entries. TTL time.Duration // Clock is the clock used to determine the current time. Clock clockwork.Clock // Context is the context used to cancel the cache. All loadfns // will be provided with this context. Context context.Context // ReloadOnErr causes entries to be reloaded immediately if // the currently loaded value is an error. Note that all concurrent // requests registered before load completes still observe the // same error. This option is only really useful for longer TTLs. ReloadOnErr bool // CleanupInterval is the interval at which cleanups occur (defaults to // 16x the supplied TTL). Longer cleanup intervals are appropriate for // caches where keys are unlikely to become orphaned. Shorter cleanup // intervals should be used when keys regularly become orphaned. CleanupInterval time.Duration // OnExpiry is an optional callback that will be executed any time // an item is expired and removed from the cache. OnExpiry func(ctx context.Context, key any, value any) }
FnCacheConfig contains dependencies for a FnCache.
func (*FnCacheConfig) CheckAndSetDefaults ¶
func (c *FnCacheConfig) CheckAndSetDefaults() error
CheckAndSetDefaults validates the FnCacheConfig is populated with required fields and sets any omitted fields to default values.
type HMACAnonymizer ¶
type HMACAnonymizer struct {
// contains filtered or unexported fields
}
hmacAnonymizer implements anonymization using HMAC
func NewHMACAnonymizer ¶
func NewHMACAnonymizer(key string) (*HMACAnonymizer, error)
NewHMACAnonymizer returns a new HMAC-based anonymizer
func (*HMACAnonymizer) Anonymize ¶
func (a *HMACAnonymizer) Anonymize(data []byte) string
Anonymize anonymizes the provided data using HMAC
func (*HMACAnonymizer) AnonymizeNonEmpty ¶
func (a *HMACAnonymizer) AnonymizeNonEmpty(s string) []byte
AnonymizeNonEmpty implements Anonymizer.
func (*HMACAnonymizer) AnonymizeString ¶
func (a *HMACAnonymizer) AnonymizeString(s string) string
AnonymizeString anonymizes the given string data using HMAC
type HTTPDoClient ¶
HTTPDoClient is an interface that defines the Do function of http.Client.
type HTTPMiddleware ¶
HTTPMiddleware defines a HTTP middleware.
type InMemoryFile ¶
type InMemoryFile struct {
// contains filtered or unexported fields
}
InMemoryFile stores the required properties to emulate a File in memory It contains the File properties like name, size, mode It also contains the File contents It does not support folders
func NewInMemoryFile ¶
func (*InMemoryFile) Content ¶
func (fi *InMemoryFile) Content() []byte
Content returns the file bytes
func (*InMemoryFile) IsDir ¶
func (fi *InMemoryFile) IsDir() bool
IsDir checks whether the file is a directory
func (*InMemoryFile) ModTime ¶
func (fi *InMemoryFile) ModTime() time.Time
ModTime returns the last modification time
func (*InMemoryFile) Size ¶
func (fi *InMemoryFile) Size() int64
Size returns the file size (calculated when writing the file)
func (*InMemoryFile) Sys ¶
func (fi *InMemoryFile) Sys() interface{}
Sys is platform independent InMemoryFile's implementation is no-op
type JumpHost ¶
type JumpHost struct { // Username to login as Username string // Addr is a target addr Addr NetAddr }
JumpHost is a target jump host
func ParseProxyJump ¶
ParseProxyJump parses strings like user@host:port,bob@host:port
type KeyStore ¶
type KeyStore struct {
// contains filtered or unexported fields
}
KeyStore is used to sign and decrypt data using X509 digital signatures.
func ParseKeyStorePEM ¶
ParseKeyStorePEM parses signing key store from PEM encoded key pair
func (*KeyStore) GetKeyPair ¶
func (ks *KeyStore) GetKeyPair() (*rsa.PrivateKey, []byte, error)
type LeveledOutputFunc ¶
type LeveledOutputFunc func(args ...interface{})
LeveledOutputFunc describes a function that emits given arguments at a specific level to an underlying logger
type LoadBalancer ¶
type LoadBalancer struct { sync.RWMutex *log.Entry PROXYHeader []byte // optional PROXY header that load balancer will send to the backend on every new connection. // contains filtered or unexported fields }
LoadBalancer implements naive round robin TCP load balancer used in tests.
func NewLoadBalancer ¶
func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
NewLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends using round robin algo
func NewRandomLoadBalancer ¶
func NewRandomLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
NewRandomLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends randomly.
func (*LoadBalancer) AddBackend ¶
func (l *LoadBalancer) AddBackend(b NetAddr)
AddBackend adds backend
func (*LoadBalancer) Addr ¶
func (l *LoadBalancer) Addr() net.Addr
Addr returns the frontend listener address. Call this after Listen, otherwise Addr returns nil.
func (*LoadBalancer) Close ¶
func (l *LoadBalancer) Close() error
func (*LoadBalancer) Listen ¶
func (l *LoadBalancer) Listen() error
Listen creates a listener on the frontend addr
func (*LoadBalancer) RemoveBackend ¶
func (l *LoadBalancer) RemoveBackend(b NetAddr) error
RemoveBackend removes backend
func (*LoadBalancer) Serve ¶
func (l *LoadBalancer) Serve() error
Serve starts accepting connections
func (*LoadBalancer) Wait ¶
func (l *LoadBalancer) Wait()
Wait is here to workaround issue https://github.com/golang/go/issues/10527 in tests
type Logger ¶
type Logger interface { logrus.FieldLogger // GetLevel specifies the level at which this logger // value is logging GetLevel() logrus.Level // SetLevel sets the logger's level to the specified value SetLevel(level logrus.Level) }
Logger describes a logger value
func WrapLogger ¶
WrapLogger wraps an existing logger entry and returns a value satisfying the Logger interface
type LoggerOption ¶
type LoggerOption func(opts *logOpts)
LoggerOption enables customizing the global logger.
func WithLogFormat ¶
func WithLogFormat(format LoggingFormat) LoggerOption
WithLogFormat initializes the default logger with the provided format.
type LoggingFormat ¶
type LoggingFormat = string
LoggingFormat defines the possible logging output formats.
const ( // LogFormatJSON configures logs to be emitted in json. LogFormatJSON LoggingFormat = "json" // LogFormatText configures logs to be emitted in a human readable text format. LogFormatText LoggingFormat = "text" )
type LoggingPurpose ¶
type LoggingPurpose int
LoggingPurpose specifies which kind of application logging is to be configured for.
const ( // LoggingForDaemon configures logging for non-user interactive applications (teleport, tbot, tsh deamon). LoggingForDaemon LoggingPurpose = iota // LoggingForCLI configures logging for user face utilities (tctl, tsh). LoggingForCLI )
type NetAddr ¶
type NetAddr struct { // Addr is the host:port address, like "localhost:22" Addr string `json:"addr"` // AddrNetwork is the type of a network socket, like "tcp" or "unix" AddrNetwork string `json:"network,omitempty"` // Path is a socket file path, like '/var/path/to/socket' in "unix:///var/path/to/socket" Path string `json:"path,omitempty"` }
NetAddr is network address that includes network, optional path and host port
func AddrsFromStrings ¶
AddrsFromStrings returns strings list converted to address list
func DialAddrFromListenAddr ¶
DialAddrFromListenAddr returns dial address from listen address
func JoinAddrSlices ¶
JoinAddrSlices joins two addr slices and returns a resulting slice
func MustParseAddr ¶
MustParseAddr parses the provided string into NetAddr or panics on an error
func MustParseAddrList ¶
MustParseAddrList parses the provided list of strings into a NetAddr list or panics on error
func ParseAddr ¶
ParseAddr takes strings like "tcp://host:port/path" and returns *NetAddr or an error
func ParseAddrs ¶
ParseAddrs parses the provided slice of strings as a slice of NetAddr's.
func ParseHostPortAddr ¶
ParseHostPortAddr takes strings like "host:port" and returns *NetAddr or an error
If defaultPort == -1 it expects 'hostport' string to have it
func (*NetAddr) FullAddress ¶
FullAddress returns full address including network and address (tcp://0.0.0.0:1243)
func (*NetAddr) IsHostUnspecified ¶
IsHostUnspecified returns true if this address' host is unspecified.
func (*NetAddr) IsLoopback ¶
IsLoopback returns true if this is a loopback address
func (*NetAddr) MarshalYAML ¶
MarshalYAML defines how a network address should be marshaled to a string
func (*NetAddr) Port ¶
Port returns defaultPort if no port is set or is invalid, the real port otherwise
func (*NetAddr) UnmarshalYAML ¶
UnmarshalYAML defines how a string can be unmarshalled into a network address
type OpenFileWithFlagsFunc ¶
OpenFileWithFlagsFunc defines a function used to open files providing options.
type PipeNetConn ¶
type PipeNetConn struct {
// contains filtered or unexported fields
}
PipeNetConn implements net.Conn from a provided io.Reader,io.Writer and io.Closer
func NewPipeNetConn ¶
func NewPipeNetConn(reader io.Reader, writer io.Writer, closer io.Closer, fakelocalAddr net.Addr, fakeRemoteAddr net.Addr) *PipeNetConn
NewPipeNetConn constructs a new PipeNetConn, providing a net.Conn implementation synthesized from the supplied io.Reader, io.Writer & io.Closer.
func (*PipeNetConn) Close ¶
func (nc *PipeNetConn) Close() error
func (*PipeNetConn) LocalAddr ¶
func (nc *PipeNetConn) LocalAddr() net.Addr
func (*PipeNetConn) RemoteAddr ¶
func (nc *PipeNetConn) RemoteAddr() net.Addr
func (*PipeNetConn) SetDeadline ¶
func (nc *PipeNetConn) SetDeadline(t time.Time) error
func (*PipeNetConn) SetReadDeadline ¶
func (nc *PipeNetConn) SetReadDeadline(t time.Time) error
func (*PipeNetConn) SetWriteDeadline ¶
func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error
type PortList ¶
PortList is a list of TCP ports.
func GetFreeTCPPorts ¶
GetFreeTCPPorts returns n ports starting from port 20000.
type PredicateError ¶
type PredicateError struct {
Err error
}
func (PredicateError) Error ¶
func (p PredicateError) Error() string
type ReadStatFS ¶
type ReadStatFS interface { fs.ReadFileFS fs.StatFS }
ReadStatFS combines two interfaces: fs.ReadFileFS and fs.StatFS We need both when creating the archive to be able to: - read file contents - `ReadFile` provided by fs.ReadFileFS - set the correct file permissions - `Stat() ... Mode()` provided by fs.StatFS
type RegexpConfig ¶
type RegexpConfig struct { // IgnoreCase specifies whether matching is case-insensitive IgnoreCase bool }
RegexpConfig defines the configuration of the regular expression matcher
type RepeatReader ¶
type RepeatReader struct {
// contains filtered or unexported fields
}
RepeatReader repeats the same byte count times without allocating any data, the single instance of the repeat reader is not goroutine safe
func NewRepeatReader ¶
func NewRepeatReader(repeat byte, count int) *RepeatReader
NewRepeatReader returns a repeat reader
type RoundRobin ¶
type RoundRobin[T any] struct { // contains filtered or unexported fields }
RoundRobin is a helper for distributing load across multiple resources in a round-robin fashion.
func NewRoundRobin ¶
func NewRoundRobin[T any](items []T) *RoundRobin[T]
NewRoundRobin creates a new round-robin inst
func (*RoundRobin[T]) ForEach ¶
func (r *RoundRobin[T]) ForEach(fn func(T))
ForEach applies the supplied closure to each item.
func (*RoundRobin[T]) Next ¶
func (r *RoundRobin[T]) Next() T
Next gets the next item that is up for use.
type SlicePool ¶
type SlicePool interface { // Zero zeroes slice Zero(b []byte) // Get returns a new or already allocated slice Get() []byte // Put returns slice back to the pool Put(b []byte) // Size returns a slice size Size() int64 }
SlicePool manages a pool of slices in attempts to manage memory in go more efficiently and avoid frequent allocations
type SliceSyncPool ¶
SliceSyncPool is a sync pool of slices (usually large) of the same size to optimize memory usage, see sync.Pool for more details
func NewSliceSyncPool ¶
func NewSliceSyncPool(sliceSize int64) *SliceSyncPool
NewSliceSyncPool returns a new slice pool, using sync.Pool of pre-allocated or newly allocated slices of the predefined size and capacity
func (*SliceSyncPool) Get ¶
func (s *SliceSyncPool) Get() []byte
Get returns a new or already allocated slice
func (*SliceSyncPool) Put ¶
func (s *SliceSyncPool) Put(b []byte)
Put returns slice back to the pool
type Stater ¶
Stater is extension interface of the net.Conn for implementations that track connection statistics.
type SyncBuffer ¶
type SyncBuffer struct {
// contains filtered or unexported fields
}
SyncBuffer is in memory bytes buffer that is safe for concurrent writes
func (*SyncBuffer) Bytes ¶
func (b *SyncBuffer) Bytes() []byte
Bytes returns contents of the buffer after this call, all writes will fail
func (*SyncBuffer) Close ¶
func (b *SyncBuffer) Close() error
Close closes reads and writes on the buffer
func (*SyncBuffer) String ¶
func (b *SyncBuffer) String() string
String returns contents of the buffer after this call, all writes will fail
type SyncMap ¶
type SyncMap[K comparable, V any] struct { // contains filtered or unexported fields }
SyncMap is a generics version of a sync.Map.
func (*SyncMap[K, V]) Delete ¶
func (s *SyncMap[K, V]) Delete(key K)
Delete deletes the value for a key.
func (*SyncMap[K, V]) LoadAndDelete ¶
LoadAndDelete loads the value for a key and deletes it if it exists.
type SyncString ¶
SyncString is a string value that can be concurrently accessed
type SyncWriter ¶
func NewSyncWriter ¶
func NewSyncWriter(w io.Writer) *SyncWriter
type TLSConn ¶
type TLSConn interface { net.Conn // ConnectionState returns basic TLS details about the connection. // More info at: https://pkg.go.dev/crypto/tls#Conn.ConnectionState ConnectionState() tls.ConnectionState // Handshake runs the client or server handshake protocol if it has not yet // been run. // More info at: https://pkg.go.dev/crypto/tls#Conn.Handshake Handshake() error // HandshakeContext runs the client or server handshake protocol if it has // not yet been run. // More info at: https://pkg.go.dev/crypto/tls#Conn.HandshakeContext HandshakeContext(context.Context) error }
TLSConn is a `net.Conn` that implements some of the functions defined by the `tls.Conn` struct. This interface can be used where it could receive a `tls.Conn` wrapped in another connection. For example, in the ALPN Proxy, some TLS Connections can be wrapped with ping protocol.
type Tracer ¶
type Tracer struct { // Started records starting time of the call Started time.Time // Description is arbitrary description Description string }
Tracer helps to trace execution of functions
type TrackingConn ¶
type TrackingConn struct { // net.Conn is the underlying net.Conn. net.Conn // contains filtered or unexported fields }
TrackingConn is a net.Conn that keeps track of how much data was transmitted (TX) and received (RX) over the net.Conn. A maximum of about 18446 petabytes can be kept track of for TX and RX before it rolls over. See https://golang.org/ref/spec#Numeric_types for more details.
func NewTrackingConn ¶
func NewTrackingConn(conn net.Conn) *TrackingConn
NewTrackingConn returns a net.Conn that can keep track of how much data was transmitted over it.
func (*TrackingConn) Stat ¶
func (s *TrackingConn) Stat() (uint64, uint64)
Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn.
type TrackingReader ¶
type TrackingReader struct {
// contains filtered or unexported fields
}
TrackingReader is an io.Reader that counts the total number of bytes read. It's thread-safe if the underlying io.Reader is thread-safe.
func NewTrackingReader ¶
func NewTrackingReader(r io.Reader) *TrackingReader
NewTrackingReader creates a TrackingReader around r.
func (*TrackingReader) Count ¶
func (r *TrackingReader) Count() uint64
Count returns the total number of bytes read so far.
type TrackingWriter ¶
type TrackingWriter struct {
// contains filtered or unexported fields
}
TrackingWriter is an io.Writer that counts the total number of bytes written. It's thread-safe if the underlying io.Writer is thread-safe.
func NewTrackingWriter ¶
func NewTrackingWriter(w io.Writer) *TrackingWriter
NewTrackingWriter creates a TrackingWriter around w.
func (*TrackingWriter) Count ¶
func (w *TrackingWriter) Count() uint64
Count returns the total number of bytes written so far.
type UID ¶
type UID interface { // New returns a new UUID4. New() string }
UID provides an interface for generating unique identifiers.
type WebLinks ¶
type WebLinks struct { // NextPage is the next page of pagination links. NextPage string // PrevPage is the previous page of pagination links. PrevPage string // FirstPage is the first page of pagination links. FirstPage string // LastPage is the last page of pagination links. LastPage string }
WebLinks holds the pagination links parsed out of a request header conforming to RFC 8288.
func ParseWebLinks ¶
ParseWebLinks partially implements RFC 8288 parsing, enough to support GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more details on Web Linking and https://github.com/google/go-github for the API client that this function was original extracted from.
Link headers typically look like:
Link: <https://api.github.com/user/teams?page=2>; rel="next", <https://api.github.com/user/teams?page=34>; rel="last"
Source Files ¶
- addr.go
- anonymizer.go
- app.go
- archive.go
- bcrypt.go
- broadcaster.go
- buf.go
- certs.go
- circular_buffer.go
- cli.go
- config.go
- conn.go
- copy.go
- disk.go
- ec2.go
- equals.go
- errors.go
- fields.go
- fncache.go
- fs.go
- fs_unix.go
- http.go
- inmemory_fs.go
- jsontools.go
- kernel.go
- keys.go
- linking.go
- listener.go
- loadbalancer.go
- net.go
- pipenetconn.go
- pipenetconn_unix.go
- proxyconn.go
- proxyjump.go
- rand.go
- repeat.go
- replace.go
- retry.go
- round.go
- roundrobin.go
- slice.go
- spki.go
- sync_map.go
- sync_writer.go
- syslog.go
- time.go
- timeout.go
- tls.go
- uid.go
- unpack.go
- unsafe.go
- utils.go
- ver.go
- writer.go
Directories ¶
Path | Synopsis |
---|---|
diagnostics
|
|
TODO(nklaassen): evaluate the risks and utility of allowing traits to be used as regular expressions.
|
TODO(nklaassen): evaluate the risks and utility of allowing traits to be used as regular expressions. |
package socks implements a SOCKS5 handshake.
|
package socks implements a SOCKS5 handshake. |
typical (TYPed predICAte Library) is a library for building better predicate expression parsers faster.
|
typical (TYPed predICAte Library) is a library for building better predicate expression parsers faster. |