utils

package
v0.0.0-...-5c79d48 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 15, 2024 License: AGPL-3.0 Imports: 80 Imported by: 0

Documentation

Index

Constants

View Source
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
)
View Source
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
)
View Source
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"
)
View Source
const (
	// FSLockRetryDelay is a delay between attempts to acquire lock.
	FSLockRetryDelay = 10 * time.Millisecond
)
View Source
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"
)
View Source
const PortStartingNumber = 20000

PortStartingNumber is a starting port number for tests

View Source
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

View Source
var ErrFnCacheClosed = errors.New("fncache permanently closed")

ErrFnCacheClosed is returned from Get when the FnCache context is closed

View Source
var ErrLimitReached = &trace.LimitExceededError{Message: "the read limit is reached"}

ErrLimitReached means that the read limit is reached.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
var SafeConfigWithIndent = jsoniter.Config{
	IndentionStep:                 2,
	EscapeHTML:                    false,
	MarshalFloatWith6Digits:       true,
	ObjectFieldMustBeSimpleString: true,
	SortMapKeys:                   true,
}.Froze()

SafeConfigWithIndent is equivalent to SafeConfig except with indentation enabled.

View Source
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

func AllowWhitespace(s string) string

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

func AsBool(v string) bool

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

func BcryptFromPassword(password []byte, cost int) ([]byte, error)

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 ByteCount

func ByteCount(b int64) string

ByteCount converts a size in bytes to a human-readable string.

func CalculateSPKI

func CalculateSPKI(cert *x509.Certificate) string

CalculateSPKI the hash value of the SPKI header in a certificate.

func CanUserWriteTo

func CanUserWriteTo(path string) (bool, error)

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

func CheckCertificateFormatFlag(s string) (string, error)

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

func CheckVersion(currentVersion, minVersion string) error

CheckVersion compares a version with a minimum version supported.

func ChooseRandomString

func ChooseRandomString(slice []string) string

ChooseRandomString returns a random string from the given slice.

func CipherSuiteMapping

func CipherSuiteMapping(cipherSuites []string) ([]uint16, error)

CipherSuiteMapping transforms Teleport formatted cipher suites strings into uint16 IDs.

func ClickableURL

func ClickableURL(in string) string

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

func ClientIPFromConn(conn net.Conn) (string, error)

ClientIPFromConn extracts host from provided remote address.

func Color

func Color(color int, v interface{}) string

Color formats the string in a terminal escape color

func CompileExpression

func CompileExpression(expression string) (*regexp.Regexp, error)

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

func ContainsExpansion(val string) bool

ContainsExpansion returns true if value contains expansion syntax, e.g. $1 or ${10}

func CopyFile

func CopyFile(src, dest string, perm os.FileMode) error

func CopyStringsMap

func CopyStringsMap(in map[string]string) map[string]string

CopyStringsMap returns a copy of the strings map

func CryptoRandomHex

func CryptoRandomHex(length int) (string, error)

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 DNSName

func DNSName(hostport string) (string, error)

DNSName extracts DNS name from host:port string.

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

func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (net.Conn, net.Conn, error)

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

func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)

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

func EscapeControl(s string) string

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

func Extract(r io.Reader, dir string) error

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

func FSTryReadLock(filePath string) (unlock func() error, err error)

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

func FSTryWriteLock(filePath string) (unlock func() error, err error)

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

func FastMarshal(v interface{}) ([]byte, error)

FastMarshal uses the json-iterator library for fast JSON marshaling. Note, this function unmarshals floats with 6 digits precision.

func FastMarshalIndent

func FastMarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

FastMarshal uses the json-iterator library for fast JSON marshaling with indentation. Note, this function unmarshals floats with 6 digits precision.

func FastUnmarshal

func FastUnmarshal(data []byte, v interface{}) error

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

func FileExists(fp string) bool

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

func FormatErrorWithNewline(err error) string

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

func FromSlice[T any](r []T, key func(T) string) map[string]T

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

func GetAndReplaceRequestBody(req *http.Request) ([]byte, error)

GetAndReplaceRequestBody returns the request body and replaces the drained body reader with io.NopCloser allowing for further body processing by http transport.

func GetAndReplaceResponseBody

func GetAndReplaceResponseBody(response *http.Response) ([]byte, error)

GetAndReplaceResponseBody returns the response body and replaces the drained body reader with io.NopCloser allowing for further body processing.

func GetAnyHeader

func GetAnyHeader(header http.Header, keys ...string) string

GetAnyHeader returns the first non-empty value by the provided keys.

func GetEC2InstanceIdentityDocument

func GetEC2InstanceIdentityDocument(ctx context.Context) (*imds.InstanceIdentityDocument, error)

func GetEC2NodeID

func GetEC2NodeID(ctx context.Context) (string, error)

GetEC2NodeID returns the node ID to use for this EC2 instance when using Simplified Node Joining.

func GetHostUUIDPath

func GetHostUUIDPath(dataDir string) string

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

func GetListenerFile(listener net.Listener) (*os.File, error)

GetListenerFile returns file associated with listener

func GetRawEC2IdentityDocument

func GetRawEC2IdentityDocument(ctx context.Context) ([]byte, error)

GetRawEC2IdentityDocument fetches the PKCS7 RSA2048 InstanceIdentityDocument from the IMDS for this EC2 instance.

func GetSingleHeader

func GetSingleHeader(headers http.Header, key string) (string, error)

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

func GlobToRegexp(in string) string

GlobToRegexp replaces glob-style standalone wildcard values with real .* regexp-friendly values, does not modify regexp-compatible values, quotes non-wildcard values

func GuessHostIP

func GuessHostIP() (ip net.IP, err error)

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

func HasPrefixAny(prefix string, values []string) bool

HasPrefixAny determines if any of the string values have the given prefix.

func Host

func Host(hostname string) (string, error)

Host extracts host from host:port string

func HostUUIDExistsLocally

func HostUUIDExistsLocally(dataDir string) bool

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

func IsCertExpiredError(err error) bool

IsCertExpiredError specifies whether this error indicates expired SSH certificate

func IsConnectionRefused

func IsConnectionRefused(err error) bool

IsConnectionRefused returns true if the given err is "connection refused" error.

func IsDir

func IsDir(path string) bool

IsDir is a helper function to quickly check if a given path is a valid directory

func IsFailedToSendCloseNotifyError

func IsFailedToSendCloseNotifyError(err error) bool

IsFailedToSendCloseNotifyError returns true if the provided error is the "tls: failed to send closeNotify".

func IsGroupMember

func IsGroupMember(gid int) (bool, error)

IsGroupMember returns whether currently logged user is a member of a group

func IsHandshakeFailedError

func IsHandshakeFailedError(err error) bool

IsHandshakeFailedError specifies whether this error indicates failed handshake

func IsLocalhost

func IsLocalhost(host string) bool

IsLocalhost returns true if this is a local hostname or ip

func IsOKNetworkError

func IsOKNetworkError(err error) bool

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

func IsPredicateError(err error) bool

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

func IsRedirect(code int) bool

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

func IsUntrustedCertErr(err error) bool

IsUntrustedCertErr checks if an error is an untrusted cert error.

func IsUseOfClosedNetworkError

func IsUseOfClosedNetworkError(err error) bool

IsUseOfClosedNetworkError returns true if the specified error indicates the use of a closed network connection.

func IsValidHostname

func IsValidHostname(hostname string) bool

IsValidHostname checks if a string represents a valid hostname.

func IsValidUnixUser

func IsValidUnixUser(u string) bool

IsValidUnixUser checks if a string represents a valid UNIX username.

func KernelVersion

func KernelVersion() (*semver.Version, error)

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

func MajorSemver(version string) (string, error)

MajorSemver returns the major version as a semver string. Ex: 13.4.3 -> 13.0.0

func MarshalPrivateKey

func MarshalPrivateKey(key crypto.Signer) ([]byte, []byte, error)

MarshalPrivateKey will return a PEM encoded crypto.Signer. Only supports RSA private keys.

func MarshalPublicKey

func MarshalPublicKey(signer crypto.Signer) ([]byte, error)

MarshalPublicKey returns a PEM encoded public key for a given crypto.Signer

func MatchString

func MatchString(input, expression string) (bool, error)

MatchString will match an input against the given expression. The expression is cached for later use.

func MeetsVersion

func MeetsVersion(gotVer, minVer string) bool

MeetsVersion returns true if gotVer is empty or at least minVer.

func MinTTL

func MinTTL(a, b time.Duration) time.Duration

MinTTL selects the smallest non-zero duration from a and b.

func MinVerWithoutPreRelease

func MinVerWithoutPreRelease(currentVersion, minVersion string) (bool, error)

MinVerWithoutPreRelease compares semver strings, but skips prerelease. This allows to compare two versions and ignore dev,alpha,beta, etc. strings.

func MultiCloser

func MultiCloser(closers ...io.Closer) io.Closer

MultiCloser implements io.Close, it sequentially calls Close() on each object

func NetAddrsToStrings

func NetAddrsToStrings(netAddrs []NetAddr) []string

NetAddrsToStrings takes a list of netAddrs and returns a list of address strings.

func NewCertPoolFromPath

func NewCertPoolFromPath(path string) (*x509.CertPool, error)

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 NewLogger

func NewLogger() *logrus.Logger

NewLogger creates a new empty logrus logger.

func NewLoggerForTests

func NewLoggerForTests() *logrus.Logger

NewLoggerForTests creates a new logrus logger for test environments.

func NewSlogLoggerForTests

func NewSlogLoggerForTests() *slog.Logger

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

func NewSyslogHook(w io.Writer) (logrus.Hook, error)

NewSyslogHook provides a logrus.Hook that sends output to syslog.

func NewSyslogWriter

func NewSyslogWriter() (io.Writer, error)

NewSyslogWriter creates a writer that outputs to the local machine syslog.

func NilCloser

func NilCloser(r io.Closer) io.Closer

NilCloser returns closer if it's not nil otherwise returns a nop closer

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

func NoopHTTPMiddleware(next http.Handler) http.Handler

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

func NormalizePath(path string, evaluateSymlinks bool) (string, error)

NormalizePath normalises path, evaluating symlinks and converting local paths to absolute

func ObeyIdleTimeout

func ObeyIdleTimeout(conn net.Conn, timeout time.Duration) net.Conn

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

func OpaqueAccessDenied(err error) error

OpaqueAccessDenied returns a generic NotFound instead of AccessDenied so as to avoid leaking the existence of secret resources.

func OpenFileAllowingUnsafeLinks(path string) (*os.File, error)

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(path string) (*os.File, error)

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

func ParseAdvertiseAddr(advertiseIP string) (string, string, error)

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

func ParsePrivateKey(bytes []byte) (crypto.Signer, error)

ParsePrivateKey parses a PEM encoded private key and returns a crypto.Signer. Only supports RSA private keys.

func ParsePrivateKeyDER

func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)

ParsePrivateKeyDER parses unencrypted DER-encoded private key

func ParsePrivateKeyPEM

func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)

ParsePrivateKeyPEM parses PEM-encoded private key

func ParsePublicKey

func ParsePublicKey(bytes []byte) (crypto.PublicKey, error)

ParsePublicKey parses a PEM encoded public key and returns a crypto.PublicKey. Only support RSA public keys.

func PercentUsed

func PercentUsed(path string) (float64, error)

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

func RandomDuration(max time.Duration) time.Duration

RandomDuration returns a duration in a range [0, max)

func ReadAtMost

func ReadAtMost(r io.Reader, limit int64) ([]byte, error)

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

func ReadHostUUID(dataDir string) (string, error)

ReadHostUUID reads host UUID from the file in the data dir

func ReadOrMakeHostUUID

func ReadOrMakeHostUUID(dataDir string) (string, error)

ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, returns the UUID from it, otherwise generates one

func ReadPath

func ReadPath(path string) ([]byte, error)

ReadPath reads file contents

func ReadYAML

func ReadYAML(reader io.Reader) (interface{}, error)

ReadYAML can unmarshal a stream of documents, used in tests.

func RecursiveChown

func RecursiveChown(dir string, uid, gid int) error

func RecursiveCopy

func RecursiveCopy(src, dest string, skip func(src, dest string) (bool, error)) error

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

func RegexMatchesAny(inputs []string, expression string) (bool, error)

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

func RemoveAllSecure(path string) error

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

func RemoveFileIfExist(filePath string) error

RemoveFileIfExist removes file if exits.

func RemoveFromSlice

func RemoveFromSlice(slice []string, values ...string) []string

RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.

func RemoveSecure

func RemoveSecure(filePath string) error

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

func RenameHeader(header http.Header, oldKey, newKey string)

RenameHeader moves all values from the old header key to the new header key.

func ReplaceInSlice

func ReplaceInSlice(s []string, old string, new string) []string

ReplaceInSlice replaces element old with new and returns a new slice.

func ReplaceLocalhost

func ReplaceLocalhost(addr, replaceWith string) string

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

func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)

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

func ReplaceRegexpWith(expr *regexp.Regexp, replaceWith string, input string) (string, error)

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

func ReplaceUnspecifiedHost(addr *NetAddr, defaultPort int) string

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

func Round(x float64) float64

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

func Roundtrip(addr string) (string, error)

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

func RoundtripWithConn(conn net.Conn) (string, error)

RoundtripWithConn uses HTTP GET on the existing connection, used in tests as it only performs GET request on /

func SetupTLSConfig

func SetupTLSConfig(config *tls.Config, cipherSuites []uint16)

SetupTLSConfig sets up cipher suites in existing TLS config

func SliceMatchesRegex

func SliceMatchesRegex(input string, expressions []string) (bool, error)

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

func SplitHostPort(hostname string) (string, string, error)

SplitHostPort splits host and port and checks that host is not empty

func SplitIdentifiers

func SplitIdentifiers(s string) []string

SplitIdentifiers splits list of identifiers by commas/spaces/newlines. Helpful when accepting lists of identifiers in CLI (role names, request IDs, etc).

func StatDir

func StatDir(path string) (os.FileInfo, error)

StatDir stats directory, returns error if file exists, but not a directory

func StatFile

func StatFile(path string) (os.FileInfo, error)

StatFile stats path, returns error if it exists but a directory.

func StoreErrorOf

func StoreErrorOf(f func() error, err *error)

StoreErrorOf stores the error returned by f within *err.

func StreamJSONArray

func StreamJSONArray[T any](items stream.Stream[T], out io.Writer, indent bool) error

StremJSONArray streams the elements of a stream.Stream as a json array with optional indentation (used to stream to CLI).

func StringMapsEqual

func StringMapsEqual(a, b map[string]string) bool

StringMapsEqual returns true if two strings maps are equal

func StringSliceSubset

func StringSliceSubset(a []string, b []string) error

StringSliceSubset returns true if b is a subset of a.

func StringsSet

func StringsSet(in []string) map[string]struct{}

StringsSet creates set of string (map[string]struct{}) from a list of strings

func StringsSliceFromSet

func StringsSliceFromSet(in map[string]struct{}) []string

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 TLSConfig

func TLSConfig(cipherSuites []uint16) *tls.Config

TLSConfig returns default TLS configuration strong defaults.

func ThisFunction

func ThisFunction() string

ThisFunction returns calling function name

func ToJSON

func ToJSON(data []byte) ([]byte, error)

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

func ToLowerCaseASCII(in string) string

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

func ToTTL(c clockwork.Clock, tm time.Time) time.Duration

ToTTL converts expiration time to TTL duration relative to current time as provided by clock

func TryReadValueAsFile

func TryReadValueAsFile(value string) (string, error)

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

func UintSliceSubset(a []uint16, b []uint16) error

UintSliceSubset returns true if b is a subset of a.

func UnsafeSliceData

func UnsafeSliceData[T any](slice []T) (*T, error)

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

func UserMessageFromError(err error) string

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

func VersionBeforeAlpha(version string) string

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

func WriteHostUUID(dataDir string, id string) error

WriteHostUUID writes host UUID into a file

func WriteJSON

func WriteJSON(w io.Writer, values interface{}) error

WriteJSON marshals multiple documents as a JSON list with indentation.

func WriteJSONArray

func WriteJSONArray[T any](w io.Writer, values []T) error

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.

func WriteYAML

func WriteYAML(w io.Writer, values interface{}) error

WriteYAML detects whether value is a list and marshals multiple documents delimited by `---`, otherwise, marshals a single value

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

type BufferSyncPool struct {
	sync.Pool
	// contains filtered or unexported fields
}

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.

func (*CaptureNBytesWriter) Write

func (w *CaptureNBytesWriter) Write(p []byte) (int, error)

Write implements io.Writer.

type CircularBuffer

type CircularBuffer struct {
	sync.Mutex
	// contains filtered or unexported fields
}

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

type CloseBroadcaster struct {
	sync.Once
	C chan struct{}
}

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.

func (CloseFunc) Close

func (cf CloseFunc) Close() error

type CloserConn

type CloserConn struct {
	net.Conn
	// contains filtered or unexported fields
}

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.

func (*CloserConn) Wait

func (c *CloserConn) Wait()

Wait for connection to close.

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

func (CombinedReadWriteCloser) Read

func (o CombinedReadWriteCloser) Read(p []byte) (int, error)

func (CombinedReadWriteCloser) Write

func (o CombinedReadWriteCloser) Write(p []byte) (int, error)

type ConnWithAddr

type ConnWithAddr struct {
	net.Conn
	// contains filtered or unexported fields
}

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) GetInt

func (f Fields) GetInt(key string) int

GetInt returns an int representation of a field.

func (Fields) GetString

func (f Fields) GetString(key string) string

GetString returns a string representation of a field.

func (Fields) GetStrings

func (f Fields) GetStrings(key string) []string

GetStrings returns a slice-of-strings representation of a field.

func (Fields) GetTime

func (f Fields) GetTime(key string) time.Time

GetTime returns a time.Time representation of a field.

func (Fields) HasField

func (f Fields) HasField(key string) bool

HasField returns true if the field exists.

type FieldsCondition

type FieldsCondition func(Fields) bool

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.

func (*FnCache) Shutdown

func (c *FnCache) Shutdown(ctx context.Context)

Shutdown expires all items in the cache. If the OnExpires callback was set in the FnCacheConfig it will be called once per item in the cache.

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

type HTTPDoClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoClient is an interface that defines the Do function of http.Client.

type HTTPMiddleware

type HTTPMiddleware func(next http.Handler) http.Handler

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 NewInMemoryFile(name string, mode fs.FileMode, modTime time.Time, content []byte) *InMemoryFile

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) Mode

func (fi *InMemoryFile) Mode() fs.FileMode

Mode returns the fs.FileMode

func (*InMemoryFile) Name

func (fi *InMemoryFile) Name() string

Name returns the file's name

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

func ParseProxyJump(in string) ([]JumpHost, error)

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

func ParseKeyStorePEM(keyPEM, certPEM string) (*KeyStore, error)

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

func WrapLogger(logger *logrus.Entry) Logger

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

func AddrsFromStrings(s apiutils.Strings, defaultPort int) ([]NetAddr, error)

AddrsFromStrings returns strings list converted to address list

func DialAddrFromListenAddr

func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr

DialAddrFromListenAddr returns dial address from listen address

func FromAddr

func FromAddr(a net.Addr) NetAddr

FromAddr returns NetAddr from golang standard net.Addr

func JoinAddrSlices

func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr

JoinAddrSlices joins two addr slices and returns a resulting slice

func MustParseAddr

func MustParseAddr(a string) *NetAddr

MustParseAddr parses the provided string into NetAddr or panics on an error

func MustParseAddrList

func MustParseAddrList(aList ...string) []NetAddr

MustParseAddrList parses the provided list of strings into a NetAddr list or panics on error

func ParseAddr

func ParseAddr(a string) (*NetAddr, error)

ParseAddr takes strings like "tcp://host:port/path" and returns *NetAddr or an error

func ParseAddrs

func ParseAddrs(addrs []string) (result []NetAddr, err error)

ParseAddrs parses the provided slice of strings as a slice of NetAddr's.

func ParseHostPortAddr

func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error)

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

func (a *NetAddr) FullAddress() string

FullAddress returns full address including network and address (tcp://0.0.0.0:1243)

func (*NetAddr) Host

func (a *NetAddr) Host() string

Host returns host part of address without port

func (*NetAddr) IsEmpty

func (a *NetAddr) IsEmpty() bool

IsEmpty returns true if address is empty

func (*NetAddr) IsHostUnspecified

func (a *NetAddr) IsHostUnspecified() bool

IsHostUnspecified returns true if this address' host is unspecified.

func (*NetAddr) IsLocal

func (a *NetAddr) IsLocal() bool

IsLocal returns true if this is a local address

func (*NetAddr) IsLoopback

func (a *NetAddr) IsLoopback() bool

IsLoopback returns true if this is a loopback address

func (*NetAddr) MarshalYAML

func (a *NetAddr) MarshalYAML() (interface{}, error)

MarshalYAML defines how a network address should be marshaled to a string

func (*NetAddr) Network

func (a *NetAddr) Network() string

Network returns the scheme for this network address (tcp or unix)

func (*NetAddr) Port

func (a *NetAddr) Port(defaultPort int) int

Port returns defaultPort if no port is set or is invalid, the real port otherwise

func (*NetAddr) Set

func (a *NetAddr) Set(s string) error

func (*NetAddr) String

func (a *NetAddr) String() string

String returns address without network (0.0.0.0:1234)

func (*NetAddr) UnmarshalYAML

func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML defines how a string can be unmarshalled into a network address

type OpenFileWithFlagsFunc

type OpenFileWithFlagsFunc func(name string, flag int, perm os.FileMode) (*os.File, error)

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) Read

func (nc *PipeNetConn) Read(buf []byte) (n int, e error)

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

func (*PipeNetConn) Write

func (nc *PipeNetConn) Write(buf []byte) (n int, e error)

type PortList

type PortList struct {
	sync.Mutex
	// contains filtered or unexported fields
}

PortList is a list of TCP ports.

func GetFreeTCPPorts

func GetFreeTCPPorts(n int, offset ...int) (PortList, error)

GetFreeTCPPorts returns n ports starting from port 20000.

func (*PortList) Pop

func (p *PortList) Pop() string

Pop returns a value from the list, it panics if the value is not there

func (*PortList) PopInt

func (p *PortList) PopInt() int

PopInt returns a value from the list, it panics if not enough values were allocated

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

func (*RepeatReader) Read

func (r *RepeatReader) Read(data []byte) (int, error)

Read copies the same byte over and over to the data count times

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

type SliceSyncPool struct {
	sync.Pool
	// contains filtered or unexported fields
}

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

func (*SliceSyncPool) Size

func (s *SliceSyncPool) Size() int64

Size returns a slice size

func (*SliceSyncPool) Zero

func (s *SliceSyncPool) Zero(b []byte)

Zero zeroes slice of any length

type Stater

type Stater interface {
	// Stat returns TX, RX data.
	Stat() (uint64, uint64)
}

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 NewSyncBuffer

func NewSyncBuffer() *SyncBuffer

NewSyncBuffer returns new in memory buffer

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

func (*SyncBuffer) Write

func (b *SyncBuffer) Write(data []byte) (n int, err error)

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]) Load

func (s *SyncMap[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key.

func (*SyncMap[K, V]) LoadAndDelete

func (s *SyncMap[K, V]) LoadAndDelete(key K) (value V, ok bool)

LoadAndDelete loads the value for a key and deletes it if it exists.

func (*SyncMap[K, V]) Range

func (s *SyncMap[K, V]) Range(f func(key K, value V) bool)

Range calls a function sequentially for each key and value in the map. Note that the map is not locked between evaluations of f.

func (*SyncMap[K, V]) Store

func (s *SyncMap[K, V]) Store(key K, value V)

Store sets the value for a key.

type SyncString

type SyncString struct {
	sync.Mutex
	// contains filtered or unexported fields
}

SyncString is a string value that can be concurrently accessed

func (*SyncString) Set

func (s *SyncString) Set(v string)

Set sets the value of the string

func (*SyncString) Value

func (s *SyncString) Value() string

Value returns value of the string

type SyncWriter

type SyncWriter struct {
	io.Writer
	sync.Mutex
}

func NewSyncWriter

func NewSyncWriter(w io.Writer) *SyncWriter

func (*SyncWriter) Write

func (sw *SyncWriter) Write(b []byte) (int, error)

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

func NewTracer

func NewTracer(description string) *Tracer

NewTracer returns a new tracer

func (*Tracer) Start

func (t *Tracer) Start() *Tracer

Start logs start of the trace

func (*Tracer) Stop

func (t *Tracer) Stop() *Tracer

Stop logs stop of the trace

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) Read

func (s *TrackingConn) Read(b []byte) (n int, err error)

func (*TrackingConn) Stat

func (s *TrackingConn) Stat() (uint64, uint64)

Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn.

func (*TrackingConn) Write

func (s *TrackingConn) Write(b []byte) (n int, err error)

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.

func (*TrackingReader) Read

func (r *TrackingReader) Read(b []byte) (int, error)

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.

func (*TrackingWriter) Write

func (w *TrackingWriter) Write(b []byte) (int, error)

type UID

type UID interface {
	// New returns a new UUID4.
	New() string
}

UID provides an interface for generating unique identifiers.

func NewFakeUID

func NewFakeUID() UID

NewFakeUID returns a new fake UID generator used in tests.

func NewRealUID

func NewRealUID() UID

NewRealUID returns a new real UID generator.

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(response *http.Response) WebLinks

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"

type WriteContextCloser

type WriteContextCloser interface {
	Close(ctx context.Context) error
	io.Writer
}

WriteContextCloser provides close method with context

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL