postgresql

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 39 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// Authentication failures
	FailureReasonProxyInvalidUsername = "invalid_username" // Username not found
	FailureReasonProxyInvalidPassword = "invalid_password" // Wrong password
	FailureReasonProxyUserDisabled    = "user_disabled"    // Account disabled

	// Authorization failures
	FailureReasonNoGrant          = "no_grant"           // No grant for database
	FailureReasonGrantExpired     = "grant_expired"      // Grant expired
	FailureReasonGrantNotStarted  = "grant_not_started"  // Grant not yet active
	FailureReasonWrongAccessLevel = "wrong_access_level" // Write attempt with read-only grant

	// Quota failures
	FailureReasonQueryQuotaExceeded = "query_quota_exceeded" // Max queries reached
	FailureReasonBytesQuotaExceeded = "bytes_quota_exceeded" // Max bytes reached

	// Server failures
	FailureReasonDatabaseNotFound   = "database_not_found"   // Server config doesn't exist
	FailureReasonDatabaseDisabled   = "database_disabled"    // Server disabled by admin
	FailureReasonUpstreamConnFailed = "upstream_conn_failed" // Can't connect to target database
)

Proxy failure reasons

Variables

View Source
var (
	ErrExpectedStartupMessage   = errors.New("expected StartupMessage")
	ErrMissingCredentials       = errors.New("missing username or database")
	ErrInvalidPassword          = errors.New("invalid password")
	ErrQueryLimitExceeded       = errors.New("query limit exceeded")
	ErrDataLimitExceeded        = errors.New("data transfer limit exceeded")
	ErrWriteNotPermitted        = errors.New("write operations not permitted with read-only access")
	ErrPasswordChangeNotAllowed = errors.New("password modification is not allowed through the proxy")
	ErrReadOnlyBypassAttempt    = errors.New("attempt to disable read-only mode is not permitted: " +
		"your access grant is read-only and cannot be changed for this session")
	// ErrReadOnlyPinLost ends a read_only session whose upstream reported
	// default_transaction_read_only no longer on — a route to turning it off
	// that the statement checks did not recognize. See readOnlyPinLost.
	ErrReadOnlyPinLost = errors.New("session terminated by dbbat: your access grant is read-only " +
		"and the session's read-only mode was turned off")
	// ErrReadOnlyTxEndInBatch refuses a COMMIT/END/ROLLBACK that is followed by
	// another statement in the same batch. Without a transaction boundary inside
	// a batch, a changed session default cannot reach any statement of it.
	ErrReadOnlyTxEndInBatch = errors.New("a transaction-ending statement cannot be followed by " +
		"another statement in the same batch on a read-only access grant")
	// ErrStatementTimeoutManaged refuses a client statement that would unset
	// or widen the session's statement_timeout. It is a courtesy, not the
	// security boundary — dbbat's own watchdog is that — but without it a
	// client that sets the value to 0 would only ever meet the disconnect,
	// with nothing explaining why.
	ErrStatementTimeoutManaged = errors.New("statement_timeout is managed by dbbat and cannot be " +
		"changed for this session")
	ErrDDLNotPermitted  = errors.New("DDL operations not permitted: your access grant blocks schema modifications")
	ErrCopyNotPermitted = errors.New("COPY not permitted: your access grant blocks COPY commands")

	ErrAPIKeyOwnerMismatch = errors.New("API key does not belong to user")
	ErrAPIKeyVerifyFailed  = errors.New("API key verification failed")

	// Startup negotiation errors. SSL/GSS encryption probes are length-8
	// frames with a magic version code; anything else of that shape is
	// rejected, and runaway clients are bounded by the round limit.
	ErrUnknownStartupMagic      = errors.New("unknown length-8 startup magic")
	ErrTooManyNegotiationRounds = errors.New("too many SSL/GSS negotiation rounds")

	// ErrStartupMessageTooLarge / ErrPasswordMessageTooLarge reject a
	// pre-auth frame whose declared length exceeds what the protocol allows.
	// The length is four attacker-controlled bytes on an unauthenticated
	// socket, so it has to be checked *before* it sizes an allocation.
	ErrStartupMessageTooLarge  = errors.New("startup message exceeds the maximum length")
	ErrPasswordMessageTooLarge = errors.New("password message exceeds the maximum length")
	// ErrMalformedMessageLength rejects a declared length that cannot even
	// cover its own 4-byte length field (including the negative values a
	// high bit in the first byte would otherwise produce).
	ErrMalformedMessageLength = errors.New("declared message length is malformed")

	// ErrCancelRequestHandled ends a connection that carried a CancelRequest.
	// Not a failure: a CancelRequest is a one-shot out-of-band signal on its
	// own TCP connection, and PostgreSQL closes it without a reply.
	ErrCancelRequestHandled = errors.New("cancel request handled")
)

Authentication and authorization errors.

View Source
var (
	// ErrUpstreamAuthFailed is returned when the target refused the stored
	// database credentials.
	ErrUpstreamAuthFailed = upstream.ErrPostgresAuthFailed
	// ErrUpstreamTLSRequired is returned when the target refused TLS while
	// ssl_mode demanded it.
	ErrUpstreamTLSRequired = upstream.ErrPostgresTLSRequired
	// ErrUpstreamSSLResponse is returned when the target answered the
	// SSLRequest with neither 'S' nor 'N'.
	ErrUpstreamSSLResponse = upstream.ErrPostgresSSLResponse
)

Upstream connect failures. The upstream login itself lives in internal/proxy/upstream (one implementation, shared with the connectivity check); these names are kept as aliases so callers and tests in this package — and anything outside it that already matched on them — keep working.

View Source
var ErrTLSConfigInvalid = errors.New("postgresql tls: cert_file and key_file must both be set or both empty")

ErrTLSConfigInvalid is returned when only one of cert/key files is set.

View Source
var ErrUpstreamReadOnlyMode = errors.New("upstream error setting read-only mode")

ErrUpstreamReadOnlyMode is returned when the upstream fails to set read-only mode. Kept as the historical name; ErrUpstreamSessionSetup is what the generalized setup path actually returns, and it wraps to this so callers and tests that matched on read-only still do.

View Source
var ErrUpstreamSessionSetup = fmt.Errorf("%w (session setup)", ErrUpstreamReadOnlyMode)

ErrUpstreamSessionSetup is returned when the upstream refuses one of the session-setup statements (the read-only pin, the statement limit). A session that cannot be pinned is failed rather than served unbounded.

Functions

This section is empty.

Types

type Server

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

Server is the PostgreSQL proxy server.

func NewServer

func NewServer(
	dataStore *store.Store,
	encryptionKey []byte,
	queryStorage config.QueryStorageConfig,
	dumpConfig config.DumpConfig,
	authCache *cache.AuthCache,
	pgConfig config.PGConfig,
	logger *slog.Logger,
) (*Server, error)

NewServer creates a new proxy server.

func (*Server) Addr added in v0.18.0

func (s *Server) Addr() net.Addr

Addr returns the listener's bound address, or nil if the server has not started accepting connections yet. Useful in tests that pass ":0" for the listen address and need to discover the OS-assigned port.

func (*Server) SetApprovalDeps added in v0.20.0

func (s *Server) SetApprovalDeps(deps shared.ApprovalDeps)

SetApprovalDeps installs the approval-hold collaborators. Called by the wiring in main; a server without them simply never holds anything.

func (*Server) SetDumpUploader added in v0.23.0

func (s *Server) SetDumpUploader(uploader *dump.Uploader)

SetDumpUploader installs the process-wide capture uploader, so this proxy's finished captures are shipped to blob storage on session close. Called by the process wiring; nil means local-only captures, which is the default.

func (*Server) SetQueryTagging added in v0.29.0

func (s *Server) SetQueryTagging(enabled bool)

SetQueryTagging turns the sqlcommenter-style statement tag on. Called by the wiring in main from DBB_QUERY_TAGGING; a server without it forwards every statement byte-for-byte as it always did. It sets the environment default the queryTaggingResolver falls back to, and remains the decision of record for a server built without a resolver (tests, fixtures).

func (*Server) SetQueryTaggingResolver added in v0.30.0

func (s *Server) SetQueryTaggingResolver(r *shared.QueryTaggingResolver)

SetQueryTaggingResolver installs the per-session tagging resolver over the tagging.* store parameters. Called by the wiring in main; a server without one keeps deciding from the DBB_QUERY_TAGGING default set above.

func (*Server) SetRowWriter added in v0.20.0

func (s *Server) SetRowWriter(writer *shared.RowWriter)

SetRowWriter installs the process-wide result-row writer, replacing (and shutting down) the private one NewServer created. Batching across every protocol is where the design pays off most: a busy proxy with many small result sets then issues one INSERT per ~1000 rows overall rather than one per query.

func (*Server) SetStatementTimeouts added in v0.29.0

func (s *Server) SetStatementTimeouts(r *shared.StatementTimeoutResolver)

SetStatementTimeouts installs the resolver for the instance-wide per-statement limit. Called by the wiring in main; a server without one never imposes a limit that the grant definition did not itself carry.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server.

func (*Server) Start

func (s *Server) Start(addr string) error

Start starts the proxy server.

type Session

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

Session represents a proxy session.

func NewSession

func NewSession(
	clientConn net.Conn,
	dataStore *store.Store,
	encryptionKey []byte,
	logger *slog.Logger,
	ctx context.Context,
	queryStorage config.QueryStorageConfig,
	dumpConfig config.DumpConfig,
	authCache *cache.AuthCache,
	tlsConfig *tls.Config,
	rowWriter *shared.RowWriter,
) *Session

NewSession creates a new session.

func (*Session) Run

func (s *Session) Run() error

Run runs the session.

Jump to

Keyboard shortcuts

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