helpers

package
v1.2.3-fred.10 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2022 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Overview

Copyright 2022 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	HostID = "00000000-0000-0000-0000-000000000000"
	Site   = "local-site"
)
View Source
const (
	Loopback = "127.0.0.1"
	Host     = "localhost"
)

Variables

This section is empty.

Functions

func CloseAgent

func CloseAgent(teleAgent *teleagent.AgentServer, socketDirPath string) error

func CreateAgent

func CreateAgent(me *user.User, key *client.Key) (*teleagent.AgentServer, string, string, error)

CreateAgent creates a SSH agent with the passed in private key and certificate that can be used in tests. This is useful so tests don't clobber your system agent.

func EnableDesktopService

func EnableDesktopService(config *service.Config)

func EnableKube

func EnableKube(t *testing.T, config *service.Config, clusterName string) error

func EnableKubernetesService

func EnableKubernetesService(t *testing.T, config *service.Config)

func ExternalSSHCommand

func ExternalSSHCommand(o CommandOptions) (*exec.Cmd, error)

ExternalSSHCommand runs an external SSH command (if an external ssh binary exists) with the passed in parameters.

func GetKubeClusters

func GetKubeClusters(t *testing.T, as *auth.Server) []types.KubeCluster

GetKubeClusters gets all kubernetes clusters accessible from a given auth server.

func GetLocalIP

func GetLocalIP() (string, error)

GetLocalIP gets the non-loopback IP address of this host.

func MakeProxyAddr

func MakeProxyAddr(user, pass, host string) string

func MustCreateUserIdentityFile

func MustCreateUserIdentityFile(t *testing.T, tc *TeleInstance, username string, ttl time.Duration) string

func MustGetCurrentUser

func MustGetCurrentUser(t *testing.T) *user.User

func NewListener

func NewListener(t *testing.T, ty service.ListenerType, fds *[]service.FileDescriptor) string

NewListener creates a new TCP listener on 127.0.0.1:0, adds it to the FileDescriptor slice (with the specified type) and returns its actual local address as a string (for use in configuration). The idea is to subvert Teleport's file-descriptor injection mechanism (used to share ports between parent and child processes) to inject preconfigured listeners to Teleport instances under test. The ports are allocated and bound at runtime, so there should be no issues with port clashes on parallel tests.

The resulting file descriptor is added to the `fds` slice, which can then be given to a teleport instance on startup in order to suppl

func NewListenerOn

func NewListenerOn(t *testing.T, hostAddr string, ty service.ListenerType, fds *[]service.FileDescriptor) string

NewListener creates a new TCP listener on `hostAddr`:0, adds it to the FileDescriptor slice (with the specified type) and returns its actual local address as a string (for use in configuration). The idea is to subvert Teleport's file-descriptor injection mechanism (used to share ports between parent and child processes) to inject preconfigured listeners to Teleport instances under test. The ports are allocated and bound at runtime, so there should be no issues with port clashes on parallel tests.

The resulting file descriptor is added to the `fds` slice, which can then be given to a teleport instance on startup in order to suppl

func Port

func Port(t *testing.T, addr string) int

PortStr extracts the port number from the supplied string, which is assumed to be a host:port pair. The port value is returned as an integer. Any errors result in an immediately failed test.

func PortStr

func PortStr(t *testing.T, addr string) string

PortStr extracts the port number from the supplied string, which is assumed to be a host:port pair. The port is returned as a string. Any errors result in an immediately failed test.

func SetTestTimeouts

func SetTestTimeouts(t time.Duration)

SetTestTimeouts affects global timeouts inside Teleport, making connections work faster but consuming more CPU (useful for integration testing). NOTE: This function modifies global values for timeouts, etc. If your tests call this function, they MUST NOT BE RUN IN PARALLEL, as they may stomp on other tests.

func SetupUser

func SetupUser(process *service.TeleportProcess, username string, roles []types.Role) error

SetupUser sets up user in the cluster

func SetupUserCreds

func SetupUserCreds(tc *client.TeleportClient, proxyHost string, creds UserCreds) error

SetupUserCreds sets up user credentials for client

func SingleProxyPortSetupOn

func SingleProxyPortSetupOn(addr string) func(*testing.T, *[]service.FileDescriptor) *InstanceListeners

SingleProxyPortSetupOn creates a constructor function that will in turn generate an InstanceConfig that allows proxying of multiple protocols over a single port when invoked.

func StandardListenerSetupOn

func StandardListenerSetupOn(addr string) func(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

StandardListenerSetupOn returns a InstanceListenerSetupFunc that will create a new InstanceListeners configured with each service listening on its own port, all bound to the supplied address

func StartAndWait

func StartAndWait(process *service.TeleportProcess, expectedEvents []string) ([]service.Event, error)

func TestMainImplementation

func TestMainImplementation(m *testing.M)

TestMainImplementation will re-execute Teleport to run a command if "exec" is passed to it as an argument. Otherwise, it will run tests as normal.

func TryCreateTrustedCluster

func TryCreateTrustedCluster(t *testing.T, authServer *auth.Server, trustedCluster types.TrustedCluster)

TryCreateTrustedCluster performs several attempts to create a trusted cluster, retries on connection problems and access denied errors to let caches propagate and services to start

Duplicated in tool/tsh/tsh_test.go

func WaitForActiveTunnelConnections

func WaitForActiveTunnelConnections(t *testing.T, tunnel reversetunnel.Server, clusterName string, expectedCount int)

WaitForActiveTunnelConnections waits for remote cluster to report a minimum number of active connections

func WaitForAuditEventTypeWithBackoff

func WaitForAuditEventTypeWithBackoff(t *testing.T, cli *auth.Server, startTime time.Time, eventType string) []apievents.AuditEvent

func WaitForClusters

func WaitForClusters(tun reversetunnel.Server, expected int) func() bool

func WaitForNodeCount

func WaitForNodeCount(ctx context.Context, t *TeleInstance, clusterName string, count int) error

WaitForNodeCount waits for a certain number of nodes to show up in the remote site.

func WaitForProxyCount

func WaitForProxyCount(t *TeleInstance, clusterName string, count int) error

WaitForProxyCount waits a set time for the proxy count in clusterName to reach some value.

func WaitForTunnelConnections

func WaitForTunnelConnections(t *testing.T, authServer *auth.Server, clusterName string, expectedCount int)

WaitForTunnelConnections waits for remote tunnels connections

Types

type ClientConfig

type ClientConfig struct {
	// Login is SSH login name
	Login string
	// Cluster is a cluster name to connect to
	Cluster string
	// Host string is a target host to connect to
	Host string
	// Port is a target port to connect to
	Port int
	// Proxy is an optional alternative proxy to use
	Proxy *ProxyConfig
	// ForwardAgent controls if the client requests it's agent be forwarded to
	// the server.
	ForwardAgent bool
	// JumpHost turns on jump host mode
	JumpHost bool
	// Labels represents host labels
	Labels map[string]string
	// Interactive launches with the terminal attached if true
	Interactive bool
	// Source IP to used in generated SSH cert
	SourceIP string
	// EnableEscapeSequences will scan Stdin for SSH escape sequences during command/shell execution.
	EnableEscapeSequences bool
}

ClientConfig is a client configuration

type CommandOptions

type CommandOptions struct {
	ForwardAgent bool
	ForcePTY     bool
	ControlPath  string
	SocketPath   string
	ProxyPort    string
	NodePort     string
	Command      string
}

CommandOptions controls how the SSH command is built.

type DisabledIMDSClient

type DisabledIMDSClient struct{}

DisabledIMDSClient is an EC2 instance metadata client that is always disabled. This is faster than the default client when not testing instance metadata behavior.

func (*DisabledIMDSClient) GetHostname

func (d *DisabledIMDSClient) GetHostname(ctx context.Context) (string, error)

func (*DisabledIMDSClient) GetTags

func (d *DisabledIMDSClient) GetTags(ctx context.Context) (map[string]string, error)

func (*DisabledIMDSClient) GetType

func (*DisabledIMDSClient) IsAvailable

func (d *DisabledIMDSClient) IsAvailable(ctx context.Context) bool

type DiscardServer

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

DiscardServer is a SSH server that discards SSH exec requests and starts with the passed in host signer.

func NewDiscardServer

func NewDiscardServer(host string, port int, hostSigner ssh.Signer) (*DiscardServer, error)

func (*DiscardServer) HandleNewChan

func (s *DiscardServer) HandleNewChan(_ context.Context, ccx *sshutils.ConnectionContext, newChannel ssh.NewChannel)

func (*DiscardServer) Start

func (s *DiscardServer) Start() error

func (*DiscardServer) Stop

func (s *DiscardServer) Stop()

type Fixture

type Fixture struct {
	Me *user.User

	// Priv/pub pair to avoid re-generating it
	Priv []byte
	Pub  []byte

	// Log defines the test-specific logger
	Log utils.Logger
}

func NewFixture

func NewFixture(t *testing.T) *Fixture

func (*Fixture) DefaultInstanceConfig

func (s *Fixture) DefaultInstanceConfig(t *testing.T) InstanceConfig

func (*Fixture) NewTeleportInstance

func (s *Fixture) NewTeleportInstance(t *testing.T) *TeleInstance

func (*Fixture) NewTeleportWithConfig

func (s *Fixture) NewTeleportWithConfig(t *testing.T, logins []string, instanceSecrets []*InstanceSecrets, teleportConfig *service.Config) *TeleInstance

NewTeleportWithConfig is a helper function that will create a running Teleport instance with the passed in user, instance secrets, and Teleport configuration.

type InstanceConfig

type InstanceConfig struct {
	// ClusterName is a cluster name of the instance
	ClusterName string
	// HostID is a host id of the instance
	HostID string
	// NodeName is a node name of the instance
	NodeName string
	// Priv is SSH private key of the instance
	Priv []byte
	// Pub is SSH public key of the instance
	Pub []byte
	// Log specifies the logger
	Log utils.Logger
	// Ports is a collection of instance ports.
	Listeners *InstanceListeners

	Fds []service.FileDescriptor
}

InstanceConfig is an instance configuration

type InstanceListenerSetupFunc

type InstanceListenerSetupFunc func(*testing.T, *[]service.FileDescriptor) *InstanceListeners

InstanceListenerSetupFunc defines a function type used for specifying the listener setup for a given test. InstanceListenerSetupFuncs are useful when you need to have some distance between the test configuration and actually executing the listener setup.

type InstanceListeners

type InstanceListeners struct {
	Web               string
	SSH               string
	SSHProxy          string
	Auth              string
	ReverseTunnel     string
	MySQL             string
	Postgres          string
	Mongo             string
	IsSinglePortSetup bool
}

InstanceListeners represents the listener configuration for a test cluster. Each address field is expected to be hull host:port pair.

func SeparateMongoAndPostgresPortSetup

func SeparateMongoAndPostgresPortSetup(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

WebReverseTunnelMuxPortSetup generates a listener config with a defined port for Postgres and Mongo

func SeparateMongoPortSetup

func SeparateMongoPortSetup(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

WebReverseTunnelMuxPortSetup generates a listener config with a defined port for MongoDB

func SeparatePostgresPortSetup

func SeparatePostgresPortSetup(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

WebReverseTunnelMuxPortSetup generates a listener config with a defined port for Postgres

func SingleProxyPortSetup

func SingleProxyPortSetup(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

SingleProxyPortSetup generates an InstanceConfig that allows proxying of multiple protocols over a single port.

func StandardListenerSetup

func StandardListenerSetup(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

StandardListenerSetup creates an InstanceListeners configures with each service listening on its own port, all bound to the loopback address

func WebReverseTunnelMuxPortSetup

func WebReverseTunnelMuxPortSetup(t *testing.T, fds *[]service.FileDescriptor) *InstanceListeners

WebReverseTunnelMuxPortSetup generates a listener config using the same port for web and tunnel, and independent ports for all other services.

type InstanceSecrets

type InstanceSecrets struct {
	// instance name (aka "site name")
	SiteName string `json:"site_name"`
	// instance keys+cert (reused for hostCA and userCA)
	// PubKey is instance public key
	PubKey []byte `json:"pub"`
	// PrivKey is instance private key
	PrivKey []byte `json:"priv"`
	// Cert is SSH host certificate
	Cert []byte `json:"cert"`
	// TLSCACert is the certificate of the trusted certificate authority
	TLSCACert []byte `json:"tls_ca_cert"`
	// TLSCert is client TLS X509 certificate
	TLSCert []byte `json:"tls_cert"`
	// TunnelAddr is a reverse tunnel listening port, allowing
	// other sites to connect to i instance. Set to empty
	// string if i instance is not allowing incoming tunnels
	TunnelAddr string `json:"tunnel_addr"`
	// list of users i instance trusts (key in the map is username)
	Users map[string]*User `json:"users"`
}

func (*InstanceSecrets) AllowedLogins

func (s *InstanceSecrets) AllowedLogins() []string

func (*InstanceSecrets) AsSlice

func (s *InstanceSecrets) AsSlice() []*InstanceSecrets

func (*InstanceSecrets) GetCAs

func (s *InstanceSecrets) GetCAs() ([]types.CertAuthority, error)

GetCAs return an array of CAs stored by the secrets object. In i case we always return hard-coded userCA + hostCA (and they share keys for simplicity)

func (*InstanceSecrets) GetIdentity

func (s *InstanceSecrets) GetIdentity() *auth.Identity

func (*InstanceSecrets) GetRoles

func (s *InstanceSecrets) GetRoles(t *testing.T) []types.Role

GetRoles returns a list of roles to initiate for this secret

func (*InstanceSecrets) String

func (s *InstanceSecrets) String() string

type ProxyAuthorizer

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

func NewProxyAuthorizer

func NewProxyAuthorizer(handler http.Handler, authDB map[string]string) *ProxyAuthorizer

func (*ProxyAuthorizer) LastError

func (p *ProxyAuthorizer) LastError() error

func (*ProxyAuthorizer) ServeHTTP

func (p *ProxyAuthorizer) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*ProxyAuthorizer) SetError

func (p *ProxyAuthorizer) SetError(err error)

type ProxyConfig

type ProxyConfig struct {
	// Name is a proxy name
	Name string
	// SSHAddr the address the node ssh service should listen on
	SSHAddr string
	// WebAddr the address the web service should listen on
	WebAddr string
	// ReverseTunnelAddr the address the reverse proxy service should listen on
	ReverseTunnelAddr string
	// Disable the web service
	DisableWebService bool
	// Disable the web ui
	DisableWebInterface bool
	// Disable ALPN routing
	DisableALPNSNIListener bool
	// FileDescriptors holds FDs to be injected into the Teleport process
	FileDescriptors []service.FileDescriptor
}

ProxyConfig is a set of configuration parameters for Proxy TODO(tcsc): Add file descriptor slice to inject FDs into proxy process

type ProxyHandler

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

func (*ProxyHandler) Count

func (p *ProxyHandler) Count() int

Count returns the number of connections that have been proxied.

func (*ProxyHandler) ServeHTTP

func (p *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP only accepts the CONNECT verb and will tunnel your connection to the specified host. Also tracks the number of connections that it proxies for debugging purposes.

type TeleInstance

type TeleInstance struct {
	// Secrets holds the keys (pub, priv and derived cert) of i instance
	Secrets InstanceSecrets

	// Hostname is the name of the host where instance is running
	Hostname string

	// Internal stuff...
	Process              *service.TeleportProcess
	Config               *service.Config
	Tunnel               reversetunnel.Server
	RemoteClusterWatcher *reversetunnel.RemoteClusterTunnelManager

	// Nodes is a list of additional nodes
	// started with this instance
	Nodes []*service.TeleportProcess

	// UploadEventsC is a channel for upload events
	UploadEventsC chan events.UploadEvent

	// Log specifies the instance logger
	Log utils.Logger
	InstanceListeners
	Fds []service.FileDescriptor
	// contains filtered or unexported fields
}

TeleInstance represents an in-memory instance of a teleport process for testing

func NewInstance

func NewInstance(t *testing.T, cfg InstanceConfig) *TeleInstance

NewInstance creates a new Teleport process instance.

The caller is responsible for calling StopAll on the returned instance to clean up spawned processes.

func (*TeleInstance) AddClientCredentials

func (i *TeleInstance) AddClientCredentials(tc *client.TeleportClient, cfg ClientConfig) (*client.TeleportClient, error)

AddClientCredentials adds authenticated credentials to a client. (server CAs and signed session key).

func (*TeleInstance) AddUser

func (i *TeleInstance) AddUser(username string, mappings []string) *User

Adds a new user into i Teleport instance. 'mappings' is a comma-separated list of OS users

func (*TeleInstance) AddUserWithRole

func (i *TeleInstance) AddUserWithRole(username string, roles ...types.Role) *User

AddUserUserWithRole adds user with one or many assigned roles

func (*TeleInstance) AsTrustedCluster

func (i *TeleInstance) AsTrustedCluster(token string, roleMap types.RoleMap) types.TrustedCluster

func (*TeleInstance) Create

func (i *TeleInstance) Create(t *testing.T, trustedSecrets []*InstanceSecrets, enableSSH bool, console io.Writer) error

Create creates a new instance of Teleport which trusts a list of other clusters (other instances)

func (*TeleInstance) CreateEx

func (i *TeleInstance) CreateEx(t *testing.T, trustedSecrets []*InstanceSecrets, tconf *service.Config) error

CreateEx creates a new instance of Teleport which trusts a list of other clusters (other instances)

Unlike Create() it allows for greater customization because it accepts a full Teleport config structure

func (*TeleInstance) GenerateConfig

func (i *TeleInstance) GenerateConfig(t *testing.T, trustedSecrets []*InstanceSecrets, tconf *service.Config) (*service.Config, error)

GenerateConfig generates instance config

func (*TeleInstance) GetSiteAPI

func (i *TeleInstance) GetSiteAPI(siteName string) auth.ClientI

GetSiteAPI is a helper which returns an API endpoint to a site with a given name. i endpoint implements HTTP-over-SSH access to the site's auth server.

func (*TeleInstance) NewClient

func (i *TeleInstance) NewClient(cfg ClientConfig) (*client.TeleportClient, error)

NewClient returns a fully configured and pre-authenticated client (pre-authenticated with server CAs and signed session key).

func (*TeleInstance) NewClientWithCreds

func (i *TeleInstance) NewClientWithCreds(cfg ClientConfig, creds UserCreds) (tc *client.TeleportClient, err error)

NewClientWithCreds creates client with credentials

func (*TeleInstance) NewUnauthenticatedClient

func (i *TeleInstance) NewUnauthenticatedClient(cfg ClientConfig) (tc *client.TeleportClient, err error)

NewUnauthenticatedClient returns a fully configured and un-authenticated client

func (*TeleInstance) Reset

func (i *TeleInstance) Reset() (err error)

Reset re-creates the teleport instance based on the same configuration This is needed if you want to stop the instance, reset it and start again

func (*TeleInstance) Start

func (i *TeleInstance) Start() error

Start will start the TeleInstance and then block until it is ready to process requests based off the passed in configuration.

func (*TeleInstance) StartApp

func (i *TeleInstance) StartApp(conf *service.Config) (*service.TeleportProcess, error)

func (*TeleInstance) StartApps

func (i *TeleInstance) StartApps(configs []*service.Config) ([]*service.TeleportProcess, error)

func (*TeleInstance) StartDatabase

func (i *TeleInstance) StartDatabase(conf *service.Config) (*service.TeleportProcess, *auth.Client, error)

StartDatabase starts the database access service with the provided config.

func (*TeleInstance) StartKube

func (i *TeleInstance) StartKube(t *testing.T, conf *service.Config, clusterName string) (*service.TeleportProcess, error)

func (*TeleInstance) StartNode

func (i *TeleInstance) StartNode(tconf *service.Config) (*service.TeleportProcess, error)

StartNode starts a SSH node and connects it to the cluster.

func (*TeleInstance) StartNodeAndProxy

func (i *TeleInstance) StartNodeAndProxy(t *testing.T, name string) (sshPort, webProxyPort, sshProxyPort int)

StartNodeAndProxy starts a SSH node and a Proxy Server and connects it to the cluster.

func (*TeleInstance) StartNodeWithTargetPort

func (i *TeleInstance) StartNodeWithTargetPort(tconf *service.Config, authPort string) (*service.TeleportProcess, error)

StartNodeWithTargetPort starts a node and connects it to the cluster via a specified port.

func (*TeleInstance) StartProxy

StartProxy starts another Proxy Server and connects it to the cluster.

func (*TeleInstance) StartReverseTunnelNode

func (i *TeleInstance) StartReverseTunnelNode(tconf *service.Config) (*service.TeleportProcess, error)

StartReverseTunnelNode starts a SSH node and connects it to the cluster via reverse tunnel.

func (*TeleInstance) StopAll

func (i *TeleInstance) StopAll() error

StopAll stops all spawned processes (auth server, nodes, proxies). StopAll should always be called at the end of TeleInstance's usage.

func (*TeleInstance) StopAuth

func (i *TeleInstance) StopAuth(removeData bool) error

StopAuth stops the auth server process. If removeData is true, the data directory is also cleaned up.

func (*TeleInstance) StopNodes

func (i *TeleInstance) StopNodes() error

StopNodes stops additional nodes

func (*TeleInstance) StopProxy

func (i *TeleInstance) StopProxy() error

StopProxy loops over the extra nodes in a TeleInstance and stops all nodes where the proxy server is enabled.

type User

type User struct {
	Username      string       `json:"username"`
	AllowedLogins []string     `json:"logins"`
	Key           *client.Key  `json:"key"`
	Roles         []types.Role `json:"-"`
}

type UserCreds

type UserCreds struct {
	// Key is user client key and certificate
	Key client.Key
	// HostCA is a trusted host certificate authority
	HostCA types.CertAuthority
}

UserCreds holds user client credentials

func GenerateUserCreds

func GenerateUserCreds(req UserCredsRequest) (*UserCreds, error)

GenerateUserCreds generates key to be used by client

type UserCredsRequest

type UserCredsRequest struct {
	// Process is a teleport process
	Process *service.TeleportProcess
	// Username is a user to generate certs for
	Username string
	// RouteToCluster is an optional cluster to route creds to
	RouteToCluster string
	// SourceIP is an optional source IP to use in SSH certs
	SourceIP string
}

UserCredsRequest is a request to generate user creds

Jump to

Keyboard shortcuts

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