Documentation ¶
Overview ¶
Package common provides common utilities used by all supported database implementations.
Index ¶
- Constants
- func CheckEngines(names ...string) error
- func ConvertConnectError(err error, sessionCtx *Session) error
- func ConvertError(err error) error
- func GetConnectionSetupTimeObserver(db types.Database) func()
- func GetMessagesFromClientMetric(db types.Database) prometheus.Counter
- func GetMessagesFromServerMetric(db types.Database) prometheus.Counter
- func MakeDatabaseMetadata(session *Session) events.DatabaseMetadata
- func MakeEventMetadata(session *Session, eventType, eventCode string) events.Metadata
- func MakeServerMetadata(session *Session) events.ServerMetadata
- func MakeSessionMetadata(session *Session) events.SessionMetadata
- func MakeTestClientTLSCert(config TestClientConfig) (*tls.Certificate, error)
- func MakeTestClientTLSConfig(config TestClientConfig) (*tls.Config, error)
- func MakeTestServerTLSConfig(config TestServerConfig) (*tls.Config, error)
- func MakeUserMetadata(session *Session) events.UserMetadata
- func RegisterEngine(fn EngineFn, names ...string)
- type Audit
- type AuditConfig
- type Auth
- type AuthClient
- type AuthClientCA
- type AuthConfig
- type AutoUsers
- type ConnectParams
- type Engine
- type EngineConfig
- type EngineFn
- type Proxy
- type ProxyContext
- type Query
- type Service
- type Session
- func (c *Session) CheckUsernameForAutoUserProvisioning() error
- func (c *Session) GetAccessState(authPref types.AuthPreference) services.AccessState
- func (c *Session) String() string
- func (c *Session) WithUser(user string) *Session
- func (c *Session) WithUserAndDatabase(user string, defaultDatabase string) *Session
- type TestClientConfig
- type TestServerConfig
- type UserProvisioner
- type Users
Constants ¶
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 )
const ( // SQLStateActiveUser is the SQLSTATE raised by deactivation procedure when // user has active connections. SQLStateActiveUser = "TP000" // SQLStateUsernameDoesNotMatch is the SQLSTATE raised by activation // procedure when the Teleport username does not match user's attributes. // // Possibly there is a hash collision, or someone manually updated the user // attributes. SQLStateUsernameDoesNotMatch = "TP001" // SQLStateRolesChanged is the SQLSTATE raised by activation procedure when // the user has active connections but roles has changed. SQLStateRolesChanged = "TP002" // SQLStateUserDropped is the SQLSTATE returned by the delete procedure // indicating the user was dropped. SQLStateUserDropped = "TP003" // SQLStateUserDeactivated is the SQLSTATE returned by the delete procedure // indicating was deactivated. SQLStateUserDeactivated = "TP004" )
Teleport-related SQL states.
SQLSTATE reference: https://en.wikipedia.org/wiki/SQLSTATE
Variables ¶
This section is empty.
Functions ¶
func CheckEngines ¶
CheckEngines checks if provided engine names are registered.
func ConvertConnectError ¶
ConvertConnectError converts common connection errors to trace errors with extra information/recommendations if necessary.
func ConvertError ¶
ConvertError converts errors to trace errors.
func GetConnectionSetupTimeObserver ¶
GetConnectionSetupTimeObserver returns a callback that will observe connection setup time metric. The value observed will be time between the call of this function and the invocation of the callback.
func GetMessagesFromClientMetric ¶
func GetMessagesFromClientMetric(db types.Database) prometheus.Counter
GetMessagesFromClientMetric increments the messages from client metric.
func GetMessagesFromServerMetric ¶
func GetMessagesFromServerMetric(db types.Database) prometheus.Counter
GetMessagesFromServerMetric increments the messages from server metric.
func MakeDatabaseMetadata ¶
func MakeDatabaseMetadata(session *Session) events.DatabaseMetadata
MakeDatabaseMetadata returns common database metadata for database session.
func MakeEventMetadata ¶
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 ¶
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) // OnPermissionsUpdate is called when granular database-level user permissions are updated. OnPermissionsUpdate(ctx context.Context, session *Session, entries []events.DatabasePermissionEntry) }
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 // Recorder is used to record session events. Recorder libevents.SessionPreparerRecorder // Database is the database in context. Database types.Database // Component is the component in use. Component string }
AuditConfig is the audit events emitter configuration.
type Auth ¶
type Auth interface { // GetRDSAuthToken generates RDS/Aurora auth token. GetRDSAuthToken(ctx context.Context, sessionCtx *Session) (string, error) // GetRedshiftAuthToken generates Redshift auth token. GetRedshiftAuthToken(ctx context.Context, sessionCtx *Session) (string, string, error) // GetRedshiftServerlessAuthToken generates Redshift Serverless auth token. GetRedshiftServerlessAuthToken(ctx context.Context, sessionCtx *Session) (string, string, error) // GetElastiCacheRedisToken generates an ElastiCache Redis auth token. GetElastiCacheRedisToken(ctx context.Context, sessionCtx *Session) (string, error) // GetMemoryDBToken generates a MemoryDB auth token. GetMemoryDBToken(ctx context.Context, sessionCtx *Session) (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) // GetAWSIAMCreds returns the AWS IAM credentials, including access key, // secret access key and session token. GetAWSIAMCreds(ctx context.Context, sessionCtx *Session) (string, 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 AuthClientCA ¶
type AuthClientCA interface { // GenerateDatabaseCert generates client certificate used by a database // service to authenticate with the database instance. GenerateDatabaseCert(context.Context, *proto.DatabaseCertRequest) (*proto.DatabaseCertResponse, error) // GetCertAuthority returns cert authority by id GetCertAuthority(context.Context, types.CertAuthID, bool) (types.CertAuthority, error) }
AuthClientCA contains the required methods to Generate mTLS certificate to be used by the postgres TestServer.
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 AutoUsers ¶
type AutoUsers interface { // ActivateUser creates or enables a database user. ActivateUser(context.Context, *Session) error // DeactivateUser disables a database user. DeactivateUser(context.Context, *Session) error // DeleteUser deletes the database user. DeleteUser(context.Context, *Session) error }
AutoUsers defines an interface for automatic user provisioning a particular database engine should implement.
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.
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 // DataDir is the Teleport data directory DataDir string // GetUserProvisioner is automatic database users creation handler. GetUserProvisioner func(AutoUsers) *UserProvisioner }
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 reversetunnelclient.RemoteSite // Servers is a list of database Servers that proxy the requested database. Servers []types.DatabaseServer // AuthContext is a context of authenticated user. AuthContext *authz.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, clientSrcAddr, clientDstAddr net.Addr) (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 // AutoCreateUserMode indicates whether the database user should be auto-created. AutoCreateUserMode types.CreateDatabaseUserMode // DatabaseUser is the requested database user. DatabaseUser string // DatabaseName is the requested database name. DatabaseName string // DatabaseRoles is a list of roles for auto-provisioned users. DatabaseRoles []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 // AuthContext is the identity context of the user. AuthContext *authz.Context }
Session combines parameters for a database connection session.
func (*Session) CheckUsernameForAutoUserProvisioning ¶
CheckUsernameForAutoUserProvisioning checks the username when using auto-provisioning.
When using auto-provisioning, force the database username to be same as Teleport username. If it's not provided explicitly, some database clients get confused and display incorrect username.
func (*Session) GetAccessState ¶
func (c *Session) GetAccessState(authPref types.AuthPreference) services.AccessState
GetAccessState returns the AccessState based on the underlying services.AccessChecker and tlsca.Identity.
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 // PinnedIP is an IP client's certificate should be pinned to. PinnedIP 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 AuthClientCA // 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 // Users is a list of possible users. If anything provided is outside this list // it will return access denied. Users []string // AllowAnyUser sets the engine to accept any database user. AllowAnyUser bool 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 UserProvisioner ¶
type UserProvisioner struct { // AuthClient is the cluster auth server client. AuthClient *auth.Client // Backend is the particular database implementation. Backend AutoUsers // Log is the logger. Log logrus.FieldLogger // Clock is the clock to use. Clock clockwork.Clock }
UserProvisioner handles automatic database user creation.
func (*UserProvisioner) Activate ¶
func (a *UserProvisioner) Activate(ctx context.Context, sessionCtx *Session) (func(), error)
Activate creates or enables a database user.
Returns a cleanup function that the caller must call once the connection to database has been established to release the cluster lock acquired by this function to make sure no 2 processes run user activation simultaneously.