common

package
v11.3.3 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2022 License: Apache-2.0 Imports: 50 Imported by: 0

Documentation

Overview

Package common provides common utilities used by all supported database implementations.

Index

Constants

View Source
const (
	// DefaultMongoDBServerSelectionTimeout is the timeout for selecting a
	// MongoDB server to connect to.
	DefaultMongoDBServerSelectionTimeout = 5 * time.Second

	// MaxPages is the maximum number of pages to iterate over when fetching cloud databases.
	MaxPages = 10
)

Variables

This section is empty.

Functions

func ConvertConnectError

func ConvertConnectError(err error, sessionCtx *Session) error

ConvertConnectError converts common connection errors to trace errors with extra information/recommendations if necessary.

func ConvertError

func ConvertError(err error) error

ConvertError converts errors to trace errors.

func IsUnrecognizedAWSEngineNameError

func IsUnrecognizedAWSEngineNameError(err error) bool

IsUnrecognizedAWSEngineNameError checks if the err is non-nil and came from using an engine filter that the AWS region does not recognize.

func MakeDatabaseMetadata

func MakeDatabaseMetadata(session *Session) events.DatabaseMetadata

MakeDatabaseMetadata returns common database metadata for database session.

func MakeEventMetadata

func MakeEventMetadata(session *Session, eventType, eventCode string) events.Metadata

MakeEventMetadata returns common event metadata for database session.

func MakeServerMetadata

func MakeServerMetadata(session *Session) events.ServerMetadata

MakeServerMetadata returns common server metadata for database session.

func MakeSessionMetadata

func MakeSessionMetadata(session *Session) events.SessionMetadata

MakeSessionMetadata returns common session metadata for database session.

func MakeTestClientTLSCert

func MakeTestClientTLSCert(config TestClientConfig) (*tls.Certificate, error)

MakeTestClientTLSCert returns TLS certificate suitable for configuring test database Postgres/MySQL clients.

func MakeTestClientTLSConfig

func MakeTestClientTLSConfig(config TestClientConfig) (*tls.Config, error)

MakeTestClientTLSConfig returns TLS config suitable for configuring test database Postgres/MySQL clients.

func MakeTestServerTLSConfig

func MakeTestServerTLSConfig(config TestServerConfig) (*tls.Config, error)

MakeTestServerTLSConfig returns TLS config suitable for configuring test database Postgres/MySQL servers.

func MakeUserMetadata

func MakeUserMetadata(session *Session) events.UserMetadata

MakeUserMetadata returns common user metadata for database session.

func RegisterEngine

func RegisterEngine(fn EngineFn, names ...string)

RegisterEngine registers a new engine constructor.

Types

type Audit

type Audit interface {
	// OnSessionStart is called on successful/unsuccessful database session start.
	OnSessionStart(ctx context.Context, session *Session, sessionErr error)
	// OnSessionEnd is called when database session terminates.
	OnSessionEnd(ctx context.Context, session *Session)
	// OnQuery is called when a database query or command is executed.
	OnQuery(ctx context.Context, session *Session, query Query)
	// EmitEvent emits the provided audit event.
	EmitEvent(ctx context.Context, event events.AuditEvent)
}

Audit defines an interface for database access audit events logger.

func NewAudit

func NewAudit(config AuditConfig) (Audit, error)

NewAudit returns a new instance of the audit events emitter.

type AuditConfig

type AuditConfig struct {
	// Emitter is used to emit audit events.
	Emitter events.Emitter
}

AuditConfig is the audit events emitter configuration.

func (*AuditConfig) Check

func (c *AuditConfig) Check() error

Check validates the config.

type Auth

type Auth interface {
	// GetRDSAuthToken generates RDS/Aurora auth token.
	GetRDSAuthToken(sessionCtx *Session) (string, error)
	// GetRedshiftAuthToken generates Redshift auth token.
	GetRedshiftAuthToken(sessionCtx *Session) (string, string, error)
	// GetCloudSQLAuthToken generates Cloud SQL auth token.
	GetCloudSQLAuthToken(ctx context.Context, sessionCtx *Session) (string, error)
	// GetCloudSQLPassword generates password for a Cloud SQL database user.
	GetCloudSQLPassword(ctx context.Context, sessionCtx *Session) (string, error)
	// GetAzureAccessToken generates Azure database access token.
	GetAzureAccessToken(ctx context.Context, sessionCtx *Session) (string, error)
	// GetAzureCacheForRedisToken retrieves auth token for Azure Cache for Redis.
	GetAzureCacheForRedisToken(ctx context.Context, sessionCtx *Session) (string, error)
	// GetTLSConfig builds the client TLS configuration for the session.
	GetTLSConfig(ctx context.Context, sessionCtx *Session) (*tls.Config, error)
	// GetAuthPreference returns the cluster authentication config.
	GetAuthPreference(ctx context.Context) (types.AuthPreference, error)
	// GetAzureIdentityResourceID returns the Azure identity resource ID
	// attached to the current compute instance. If Teleport is not running on
	// Azure VM returns an error.
	GetAzureIdentityResourceID(ctx context.Context, identityName string) (string, error)
	// Closer releases all resources used by authenticator.
	io.Closer
}

Auth defines interface for creating auth tokens and TLS configurations.

func NewAuth

func NewAuth(config AuthConfig) (Auth, error)

NewAuth returns a new instance of database access authenticator.

type AuthClient

type AuthClient interface {
	// GenerateDatabaseCert generates client certificate used by a database
	// service to authenticate with the database instance.
	GenerateDatabaseCert(ctx context.Context, req *proto.DatabaseCertRequest) (*proto.DatabaseCertResponse, error)
	// GetAuthPreference returns the cluster authentication config.
	GetAuthPreference(ctx context.Context) (types.AuthPreference, error)
}

AuthClient is an interface that defines a subset of libauth.Client's functions that are required for database auth.

type AuthConfig

type AuthConfig struct {
	// AuthClient is the cluster auth client.
	AuthClient AuthClient
	// Clients provides interface for obtaining cloud provider clients.
	Clients cloud.Clients
	// Clock is the clock implementation.
	Clock clockwork.Clock
	// Log is used for logging.
	Log logrus.FieldLogger
}

AuthConfig is the database access authenticator configuration.

func (*AuthConfig) CheckAndSetDefaults

func (c *AuthConfig) CheckAndSetDefaults() error

CheckAndSetDefaults validates the config and sets defaults.

type ConnectParams

type ConnectParams struct {
	// User is a database username.
	User string
	// Database is a database name/schema.
	Database string
	// ClientIP is a client real IP. Currently, used for rate limiting.
	ClientIP string
}

ConnectParams keeps parameters used when connecting to Service.

type Engine

type Engine interface {
	// InitializeConnection initializes the client connection. No DB connection is made at this point, but a message
	// can be sent to a client in a database format.
	InitializeConnection(clientConn net.Conn, sessionCtx *Session) error
	// SendError sends an error to a client in database encoded format.
	// NOTE: Client connection must be initialized before this function is called.
	SendError(error)
	// HandleConnection proxies the connection received from the proxy to
	// the particular database instance.
	HandleConnection(context.Context, *Session) error
}

Engine defines an interface for specific database protocol engine such as Postgres or MySQL.

func GetEngine

func GetEngine(name string, conf EngineConfig) (Engine, error)

GetEngine returns a new engine for the provided configuration.

type EngineConfig

type EngineConfig struct {
	// Auth handles database access authentication.
	Auth Auth
	// Audit emits database access audit events.
	Audit Audit
	// AuthClient is the cluster auth server client.
	AuthClient *auth.Client
	// CloudClients provides access to cloud API clients.
	CloudClients cloud.Clients
	// Context is the database server close context.
	Context context.Context
	// Clock is the clock interface.
	Clock clockwork.Clock
	// Log is used for logging.
	Log logrus.FieldLogger
	// Users handles database users.
	Users Users
}

EngineConfig is the common configuration every database engine uses.

func (*EngineConfig) CheckAndSetDefaults

func (c *EngineConfig) CheckAndSetDefaults() error

CheckAndSetDefaults validates the config and sets default values.

type EngineFn

type EngineFn func(EngineConfig) Engine

EngineFn defines a database engine constructor function.

type Proxy

type Proxy interface {
	// HandleConnection takes the client connection, handles all database
	// specific startup actions and starts proxying to remote server.
	HandleConnection(context.Context, net.Conn) error
}

Proxy defines an interface a database proxy should implement.

type ProxyContext

type ProxyContext struct {
	// Identity is the authorized client Identity.
	Identity tlsca.Identity
	// Cluster is the remote Cluster running the database server.
	Cluster reversetunnel.RemoteSite
	// Servers is a list of database Servers that proxy the requested database.
	Servers []types.DatabaseServer
	// AuthContext is a context of authenticated user.
	AuthContext *auth.Context
}

ProxyContext contains parameters for a database session being proxied.

type Query

type Query struct {
	// Query is the SQL query text.
	Query string
	// Parameters contains optional prepared statement parameters.
	Parameters []string
	// Database is optional database name the query is executed in.
	Database string
	// Error contains error, if any, signaling query failure.
	Error error
}

Query combines database query parameters.

type Service

type Service interface {
	// Authorize authorizes the provided client TLS connection.
	Authorize(ctx context.Context, tlsConn utils.TLSConn, params ConnectParams) (*ProxyContext, error)
	// Connect is used to connect to remote database server over reverse tunnel.
	Connect(ctx context.Context, proxyCtx *ProxyContext) (net.Conn, error)
	// Proxy starts proxying between client and service connections.
	Proxy(ctx context.Context, proxyCtx *ProxyContext, clientConn, serviceConn net.Conn) error
}

Service defines an interface for connecting to a remote database service.

type Session

type Session struct {
	// ID is the unique session ID.
	ID string
	// ClusterName is the cluster the database service is a part of.
	ClusterName string
	// HostID is the id of this database server host.
	HostID string
	// Database is the database user is connecting to.
	Database types.Database
	// Identity is the identity of the connecting Teleport user.
	Identity tlsca.Identity
	// Checker is the access checker for the identity.
	Checker services.AccessChecker
	// DatabaseUser is the requested database user.
	DatabaseUser string
	// DatabaseName is the requested database name.
	DatabaseName string
	// StartupParameters define initial connection parameters such as date style.
	StartupParameters map[string]string
	// Log is the logger with session specific fields.
	Log logrus.FieldLogger
	// LockTargets is a list of lock targets applicable to this session.
	LockTargets []types.LockTarget
}

Session combines parameters for a database connection session.

func (*Session) MFAParams

func (c *Session) MFAParams(authPrefMFARequirement types.RequireMFAType) services.AccessMFAParams

MFAParams returns MFA params for the given auth context and auth preference MFA requirement.

func (*Session) String

func (c *Session) String() string

String returns string representation of the session parameters.

type TestClientConfig

type TestClientConfig struct {
	// AuthClient will be used to retrieve trusted CA.
	AuthClient auth.ClientI
	// AuthServer will be used to generate database access certificate for a user.
	AuthServer *auth.Server
	// Address is the address to connect to (web proxy).
	Address string
	// Cluster is the Teleport cluster name.
	Cluster string
	// Username is the Teleport user name.
	Username string
	// RouteToDatabase contains database routing information.
	RouteToDatabase tlsca.RouteToDatabase
}

TestClientConfig combines parameters for a test Postgres/MySQL client.

type TestServerConfig

type TestServerConfig struct {
	// AuthClient will be used to retrieve trusted CA.
	AuthClient auth.ClientI
	// Name is the server name for identification purposes.
	Name string
	// AuthUser is used in tests simulating IAM token authentication.
	AuthUser string
	// AuthToken is used in tests simulating IAM token authentication.
	AuthToken string
	// CN allows setting specific CommonName in the database server certificate.
	//
	// Used when simulating test Cloud SQL database which should contains
	// <project-id>:<instance-id> in its certificate.
	CN string
	// ListenTLS creates a TLS listener when true instead of using a net listener.
	// This is used to simulate MySQL connections through the GCP Cloud SQL Proxy.
	ListenTLS bool
	// ClientAuth sets tls.ClientAuth in server's tls.Config. It can be used to force client
	// certificate validation in tests.
	ClientAuth tls.ClientAuthType

	Listener net.Listener
}

TestServerConfig combines parameters for a test Postgres/MySQL server.

func (*TestServerConfig) CheckAndSetDefaults

func (cfg *TestServerConfig) CheckAndSetDefaults() error

func (*TestServerConfig) Close

func (cfg *TestServerConfig) Close() error

func (*TestServerConfig) CloseOnError

func (cfg *TestServerConfig) CloseOnError(err *error) error

func (*TestServerConfig) Port

func (cfg *TestServerConfig) Port() (string, error)

type Users

type Users interface {
	GetPassword(ctx context.Context, database types.Database, userName string) (string, error)
}

Users defines an interface for managing database users.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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