mongodb

package
v0.26.1 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 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

Overview

Package mongodb implements a transparent MongoDB wire-protocol proxy for dbbat: it terminates client authentication (SASL PLAIN over TLS or a dbb_ API key), authenticates to the upstream MongoDB with stored credentials (SCRAM-SHA-256), and grant-checks, classifies, logs and quota-enforces every command — the same pipeline as the PostgreSQL/Oracle/MySQL proxies.

The wire framing is hand-rolled (no Go library offers a MongoDB *server* handshake) following the contract in specs/todos/2026-07-14-mongodb-support.md §1–§7. BSON document encode/decode uses go.mongodb.org/mongo-driver/v2/bson.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAuthenticationFailed — SASL PLAIN verification failed (bad password,
	// unknown user, or API-key mismatch).
	ErrAuthenticationFailed = errors.New("authentication failed")
	// ErrUpstreamRejected — the upstream MongoDB rejected our hello or SASL
	// exchange (ok != 1).
	ErrUpstreamRejected = errors.New("dbbat: upstream MongoDB rejected the exchange")
	// ErrDatabaseNotResolvable — the target dbbat database could not be
	// resolved from authSource / user#db / a single active grant.
	ErrDatabaseNotResolvable = errors.New("dbbat: could not resolve target database; " +
		"connect with authSource=<dbbat-database-name> (or username 'user#database')")
	// ErrNoActiveGrant — the user has no current grant on the resolved database.
	ErrNoActiveGrant = errors.New("dbbat: no active grant for this database")
	// ErrTLSRequired — a PLAIN auth attempt arrived on a non-TLS connection.
	ErrTLSRequired = errors.New("dbbat: PLAIN authentication requires TLS")
	// ErrUpstreamConnect — the outbound connection to the upstream MongoDB failed.
	ErrUpstreamConnect = errors.New("dbbat: upstream MongoDB connection failed")
	// ErrUpstreamTLSHandshake — the TLS handshake with the upstream failed.
	// Distinguished from every other upstream failure because it is the one
	// signal that may downgrade an opportunistic ssl_mode to plaintext.
	ErrUpstreamTLSHandshake = errors.New("dbbat: upstream MongoDB TLS handshake failed")
	// ErrUpstreamNoAttempt — the ssl_mode produced no connection attempt at
	// all. Unreachable with a plan from upstream.PlanFor; it exists so the
	// exhausted-loop path is not a silent nil.
	ErrUpstreamNoAttempt = errors.New("dbbat: ssl_mode produced no upstream connection attempt")
	// ErrCommandBlocked — a command was refused by grant controls or the
	// always-blocked list.
	ErrCommandBlocked = errors.New("dbbat: command not permitted")
	// ErrPreAuthNotAllowed — a non-allowlisted command was issued before auth.
	ErrPreAuthNotAllowed = errors.New("dbbat: authentication required")
	// ErrLegacyOpCode — a pre-OP_MSG opcode arrived after authentication.
	// dbbat decodes only OP_MSG, so forwarding one would hand the upstream a
	// command that skipped the $db check, the grant controls and the query log
	// entirely. Refused instead — see docs/mongodb.md.
	ErrLegacyOpCode = errors.New("dbbat: legacy wire protocol opcodes are not supported; " +
		"use a driver that speaks OP_MSG (MongoDB 3.6+)")
	// ErrQueryLimitExceeded — the grant's max_query_count quota has been reached.
	ErrQueryLimitExceeded = errors.New("dbbat: query count limit exceeded for this grant")
	// ErrDataLimitExceeded — the grant's max_bytes_transferred quota has been reached.
	ErrDataLimitExceeded = errors.New("dbbat: data transfer limit exceeded for this grant")
)

Sentinel errors for the MongoDB proxy session lifecycle. The user-facing text is what a mongosh / driver surfaces in the errmsg field (contract §7).

View Source
var (
	ErrShortMessage         = errors.New("mongodb: message shorter than declared")
	ErrMessageTooLarge      = errors.New("mongodb: message exceeds maximum size")
	ErrUnsupportedCompress  = errors.New("mongodb: unsupported OP_COMPRESSED compressor")
	ErrCompressedSizeMismat = errors.New("mongodb: OP_COMPRESSED uncompressed size mismatch")
	ErrUnknownOpCode        = errors.New("mongodb: unknown opcode")
	ErrBadSection           = errors.New("mongodb: invalid OP_MSG section kind")
	ErrNoCommandBody        = errors.New("mongodb: OP_MSG has no kind-0 command body")
	ErrEmptyCommandBody     = errors.New("mongodb: empty command document")
)

Wire-parsing errors.

View Source
var ErrTLSConfigInvalid = errors.New("mongodb 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.

Functions

This section is empty.

Types

type Server

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

Server is the MongoDB proxy server. It accepts MongoDB client connections, authenticates them against the DBBat user store (SASL PLAIN / dbb_ API keys), and proxies commands to the upstream MongoDB configured for the requested database.

func NewServer

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

NewServer creates a new MongoDB proxy server.

func (*Server) Addr

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

Addr returns the listener's bound address, or nil if the server has not started accepting connections yet.

func (*Server) SetApprovalDeps added in v0.20.0

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

SetApprovalDeps installs the approval-hold collaborators. A server without them 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) 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) 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 on addr.

type Session

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

Session is a single client connection through the MongoDB proxy.

func (*Session) KillHeldQuery added in v0.20.0

func (s *Session) KillHeldQuery() bool

KillHeldQuery ends a command parked on a human, in response to a MongoDB killOperations. Reports whether anything was parked.

func (*Session) Run

func (s *Session) Run() error

Run drives the session lifecycle (contract §2):

  1. optional TLS termination (peek first byte)
  2. PRE-AUTH: answer hello/ping/etc — monitoring connections stay here forever, never dialing upstream or recording a connection
  3. on saslStart: authenticate, resolve grant, dial upstream, record
  4. relay commands until either side closes

type UpstreamConfig added in v0.21.0

type UpstreamConfig struct {
	// Host is the target hostname, used for TLS server-name verification; the
	// transport comes from the injected dial function.
	Host string
	// Username and Password are the stored upstream credentials.
	Username string
	Password string
	// AuthSource is the upstream user's own auth database. It is deliberately
	// NOT the client's authSource (which carries the dbbat database selector,
	// contract §5).
	AuthSource string
	// AppName is advertised in the hello handshake's client metadata.
	AppName string
	// SSLMode is the row's ssl_mode; interpreted by upstream.PlanFor.
	SSLMode string
}

UpstreamConfig is everything a MongoDB login needs from a server row.

type UpstreamConn added in v0.21.0

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

UpstreamConn is an authenticated connection to a target MongoDB.

The connector below is the MongoDB entry of the shared upstream-connect set (see internal/proxy/upstream). It lives in this package rather than in internal/proxy/upstream only because it is written on top of this package's OP_MSG codec, which the whole proxy is built from; the ssl_mode policy it applies is the shared one, so there is still exactly one description of what a mode means. The connectivity check calls ConnectUpstream directly.

func ConnectUpstream added in v0.21.0

func ConnectUpstream(ctx context.Context, dial upstream.DialFunc, cfg UpstreamConfig) (*UpstreamConn, error)

ConnectUpstream dials the target through dial, applies the ssl_mode policy, runs the hello handshake and authenticates via SCRAM-SHA-256 (contract §5). It is the one implementation the proxy and the connectivity check share.

MongoDB has no in-band encryption negotiation: a connection is TLS from the first byte or not at all. An opportunistic ssl_mode is therefore a redial — attempt the TLS handshake, and fall back to plaintext only when that handshake is what failed. Once bytes have been exchanged as a client, a failure is the server's answer about *us*, not about the transport, so a rejected credential ends the chain rather than downgrading the retry.

func (*UpstreamConn) Close added in v0.21.0

func (u *UpstreamConn) Close() error

Close tears the connection down. Safe on a nil receiver.

func (*UpstreamConn) TLS added in v0.21.0

func (u *UpstreamConn) TLS() bool

TLS reports whether this connection is encrypted.

Jump to

Keyboard shortcuts

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