utils

package
v0.0.0-...-3ee2c51 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2024 License: Apache-2.0 Imports: 21 Imported by: 52

Documentation

Overview

Package utils defines several functions used across the Teleport API and other packages

Index

Constants

View Source
const (
	// ContextDelegator is a delegator for access requests set in the context
	// of the request
	ContextDelegator contextKey = "delegator"
)
View Source
const HumanTimeFormatString = "Mon Jan _2 15:04 UTC"

HumanTimeFormatString is a human readable date formatting

Variables

This section is empty.

Functions

func All

func All[S ~[]E, E any](s S, predicate func(E) bool) bool

All checks if all elements of slice satisfy given predicate. If the slice is empty, it returns true.

func Any

func Any[S ~[]E, E any](s S, predicate func(E) bool) bool

Any checks if any element of slice satisfy given predicate. If the slice is empty, it returns false.

func CloneProtoMsg

func CloneProtoMsg[T protoadapt.MessageV1](msg T) T

CloneProtoMsg returns a deep copy of msg. Modifying the returned protobuf message will not affect msg. If msg contains any empty slices, the returned copy will have nil slices instead.

func ContainSameUniqueElements

func ContainSameUniqueElements[S ~[]E, E comparable](s1, s2 S) bool

ContainSameUniqueElements returns true if the input slices contain the same unique elements. Ordering and duplicates are ignored.

func CopyStrings

func CopyStrings(in []string) []string

CopyStrings makes a deep copy of the passed in string slice and returns the copy.

func CountBy

func CountBy[S ~[]E, E any](elements S, mapper func(E) string) map[string]int

CountBy counts the occurrences of each element in a slice based on a given mapper function.

func CurrentUser

func CurrentUser() (*user.User, error)

CurrentUser is just like user.Current, except an error is returned if the user lookup exceeds 10 seconds. This is because if user.Current is called on a domain joined host, the user lookup will contact potentially multiple domain controllers which can hang.

func DecodeClusterName

func DecodeClusterName(serverName string) (string, error)

DecodeClusterName decodes cluster name, returns NotFound if no cluster name is encoded (empty subdomain), so servers can detect cases when no server name passed returns BadParameter if encoding does not match

func Deduplicate

func Deduplicate[T comparable](in []T) []T

Deduplicate deduplicates list of comparable values.

func DeduplicateAny

func DeduplicateAny[T any](in []T, compare func(T, T) bool) []T

DeduplicateAny deduplicates list of any values with compare function.

func EncodeClusterName

func EncodeClusterName(clusterName string) string

EncodeClusterName encodes cluster name in the SNI hostname

func GetDelegator

func GetDelegator(ctx context.Context) string

GetDelegator attempts to load the context value AccessRequestDelegator, returning the empty string if no value was found.

func GetProxyURL

func GetProxyURL(dialAddr string) *url.URL

GetProxyURL gets the HTTP proxy address to use for a given address, if any.

func HumanTimeFormat

func HumanTimeFormat(d time.Time) string

HumanTimeFormat formats time as recognized by humans

func IsLoopback

func IsLoopback(host string) bool

IsLoopback returns 'true' if a given hostname resolves *only* to the local host's loopback interface

func JoinStrings

func JoinStrings[T ~string](elems []T, sep string) T

JoinStrings returns a string that is all the elements in the slice `T[]` joined by `sep` This being generic allows for the usage of custom string times, without having to convert the elements to a string to be passed into `strings.Join`.

func MapToStrings

func MapToStrings(m map[string]string) []string

MapToStrings collects keys and values of a map into a slice of strings.

func ObjectToStruct

func ObjectToStruct(in interface{}, out interface{}) error

ObjectToStruct is converts any structure into JSON and then unmarshalls it into another structure.

Teleport configuration uses this (strange, at first) trick to convert from one struct type to another, if their fields are loosely compatible via their `json` tags

Example: assume you have two structs:

type A struct {
    Name string `json:"name"`
	   Age  int    `json:"age"`
}

type B struct {
	   FullName string `json:"name"`
}

Now you can convert B to A:

		b := &B{ FullName: "Bob Dilan"}
		var a *A
		utils.ObjectToStruct(b, &a)
		fmt.Println(a.Name)

 > "Bob Dilan"

func ParseBool

func ParseBool(value string) (bool, error)

ParseBool parses string as boolean value, returns error in case if value is not recognized

func ParseSessionsURI

func ParseSessionsURI(in string) (*url.URL, error)

ParseSessionsURI parses uri per convention of session upload URIs file is a default scheme

func ParseURL

func ParseURL(addr string) (*url.URL, error)

ParseURL parses an absolute URL. Unlike url.Parse, absolute URLs without a scheme are allowed.

func StrictObjectToStruct

func StrictObjectToStruct(in interface{}, out interface{}) error

StrictObjectToStruct converts any structure into JSON and then unmarshalls it into another structure using a strict decoder.

func ToLowerStrings

func ToLowerStrings(strs []string) []string

ToLowerStrings lower cases each string in a slice.

func UTC

func UTC(t *time.Time)

UTC converts time to UTC timezone

func WithDelegator

func WithDelegator(ctx context.Context, delegator string) context.Context

WithDelegator creates a child context with the AccessRequestDelegator value set. Optionally used by AuthServer.SetAccessRequestState to log a delegating identity.

Types

type HTTPRoundTripper

type HTTPRoundTripper struct {
	*http.Transport
	// contains filtered or unexported fields
}

HTTPRoundTripper is a wrapper for http.Transport that - adds extra HTTP headers to all requests, and - downgrades requests to plain HTTP when proxy is at localhost and the wrapped http.Transport has TLSClientConfig.InsecureSkipVerify set to true.

func NewHTTPRoundTripper

func NewHTTPRoundTripper(transport *http.Transport, extraHeaders map[string]string) *HTTPRoundTripper

NewHTTPRoundTripper creates a new initialized HTTP roundtripper.

func (*HTTPRoundTripper) CloseIdleConnections

func (rt *HTTPRoundTripper) CloseIdleConnections()

CloseIdleConnections forwards closing of idle connections on to the wrapped transport. This is required to ensure that the underlying http.Transport has its idle connections closed per the http.Client docs:

> If the Client's Transport does not have a CloseIdleConnections method
> then this method does nothing.

func (*HTTPRoundTripper) RoundTrip

func (rt *HTTPRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes a single HTTP transaction. Part of the RoundTripper interface.

type HostResolver

type HostResolver interface {
	// LookupHost performs a hostname lookup.  See net.Resolver.LookupHost for details.
	LookupHost(ctx context.Context, host string) (addrs []string, err error)
}

HostResolver provides an interface matching the net.Resolver.LookupHost method. Typically only used as a means of overriding dns resolution behavior in tests.

type RouteableServer

type RouteableServer interface {
	GetName() string
	GetHostname() string
	GetAddr() string
	GetUseTunnel() bool
	GetPublicAddrs() []string
}

RouteableServer is an interface describing the subset of the types.Server interface required to make a routing decision.

type SSHRouteMatcher

type SSHRouteMatcher struct {
	// contains filtered or unexported fields
}

SSHRouteMatcher is a helper used to decide if an ssh dial request should match a given server. This is broken out of proxy.Router as a standalone helper in order to let other parts of teleport easily find matching servers when generating error messages or building access requests.

func NewSSHRouteMatcher

func NewSSHRouteMatcher(host, port string, caseInsensitive bool) SSHRouteMatcher

NewSSHRouteMatcher builds a new matcher for ssh routing decisions.

func NewSSHRouteMatcherFromConfig

func NewSSHRouteMatcherFromConfig(cfg SSHRouteMatcherConfig) (*SSHRouteMatcher, error)

NewSSHRouteMatcherFromConfig sets up an ssh route matcher from the supplied configuration.

func (*SSHRouteMatcher) IsEmpty

func (m *SSHRouteMatcher) IsEmpty() bool

IsEmpty checks if this route matcher has had a hostname set.

func (*SSHRouteMatcher) MatchesServerIDs

func (m *SSHRouteMatcher) MatchesServerIDs() bool

MatchesServerIDs checks if this matcher wants to perform server ID matching.

func (*SSHRouteMatcher) RouteToServer

func (m *SSHRouteMatcher) RouteToServer(server RouteableServer) bool

RouteToServer checks if this route matcher wants to route to the supplied server.

func (*SSHRouteMatcher) RouteToServerScore

func (m *SSHRouteMatcher) RouteToServerScore(server RouteableServer) (score int)

RouteToServerScore checks wether this route matcher wants to route to the supplied server and represents the result of that check as an integer score indicating the strength of the match. Positive scores indicate a match, higher being stronger.

type SSHRouteMatcherConfig

type SSHRouteMatcherConfig struct {
	// Host is the target host that we want to route to.
	Host string
	// Port is an optional target port. If empty or zero
	// it will match servers listening on any port.
	Port string
	// Resolver can be set to override default hostname lookup
	// behavior (used in tests).
	Resolver HostResolver
	// CaseInsensitive enabled case insensitive routing when true.
	CaseInsensitive bool
}

SSHRouteMatcherConfig configures an SSHRouteMatcher.

type Strings

type Strings []string

Strings is a list of string that can unmarshal from list of strings or a scalar string from scalar yaml or json property

func (Strings) MarshalJSON

func (s Strings) MarshalJSON() ([]byte, error)

MarshalJSON marshals to scalar value if there is only one value in the list to list otherwise

func (Strings) MarshalYAML

func (s Strings) MarshalYAML() (interface{}, error)

MarshalYAML marshals to scalar value if there is only one value in the list, marshals to list otherwise

func (*Strings) UnmarshalJSON

func (s *Strings) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals scalar string or strings slice to Strings

func (*Strings) UnmarshalYAML

func (s *Strings) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is used to allow Strings to unmarshal from scalar string value or from the list

Directories

Path Synopsis
grpc
Package keypaths defines several keypaths used by multiple Teleport services.
Package keypaths defines several keypaths used by multiple Teleport services.
Package keys defines common interfaces for Teleport client keys.
Package keys defines common interfaces for Teleport client keys.
Package prompt implements CLI prompts to the user.
Package prompt implements CLI prompts to the user.
Package retryutils defines common retry and jitter logic.
Package retryutils defines common retry and jitter logic.
Package sshutils defines several functions and types used across the Teleport API and other Teleport packages when working with SSH.
Package sshutils defines several functions and types used across the Teleport API and other Teleport packages when working with SSH.
ppk
Package ppk provides functions implementing conversion between Teleport's native RSA keypairs and PuTTY's PPK format.
Package ppk provides functions implementing conversion between Teleport's native RSA keypairs and PuTTY's PPK format.
Package tlsutils contains utilities for TLS configuration and formats.
Package tlsutils contains utilities for TLS configuration and formats.

Jump to

Keyboard shortcuts

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