config

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultApprovalSlackDelay is how long a hold waits before escalating.
	DefaultApprovalSlackDelay = "30s"
	// ApprovalSlackSQLMaxLen bounds the SQL text copied into Slack.
	ApprovalSlackSQLMaxLen = 500
)

Default approval-hold settings.

View Source
const (
	DefaultDumpMaxSize   = 10 * 1024 * 1024 // 10MB
	DefaultDumpRetention = "24h"
)

Default dump settings.

View Source
const (
	DefaultMaxResultRows  = 100000
	DefaultMaxResultBytes = 100 * 1024 * 1024 // 100MB
)

Default query storage limits.

View Source
const (
	DefaultRateLimitEnabled = true
	DefaultRateLimitRPM     = 60
	DefaultRateLimitRPMAnon = 10
	DefaultRateLimitBurst   = 10
)

Default rate limiting settings.

View Source
const (
	DefaultHashMemoryMB = 64
	DefaultHashTime     = 1
	DefaultHashThreads  = 4
)

Default hash settings (matching current argon2id defaults).

View Source
const (
	DefaultAuthCacheEnabled    = true
	DefaultAuthCacheTTLSeconds = 300 // 5 minutes
	DefaultAuthCacheMaxSize    = 10000
)

Default auth cache settings.

View Source
const DefaultBaseURL = "/app"

DefaultBaseURL is the default base URL path for the frontend.

View Source
const DefaultDemoTargetDB = "demo:demo@localhost/demo"

DefaultDemoTargetDB is the default value for DemoTargetDB.

View Source
const DefaultLogLevel = "info"

DefaultLogLevel is the default log level.

View Source
const DefaultQueryStorageRetention = "0"

DefaultQueryStorageRetention keeps query history forever. Retention is opt-in: see QueryStorageConfig.Retention.

View Source
const FallbackInstanceID = "dbbat"

FallbackInstanceID is used when no DBB_INSTANCE_ID is set and the hostname cannot be read. It is deliberately a constant rather than a random value: two runs of the same process must agree on the id, or a restart would never recognize (and therefore never reclaim) the connections its predecessor left open.

It is also the one way replicas can end up sharing an id without anyone asking for it — every replica that cannot read its hostname lands here — and a shared id defeats the reconcile's own-instance branch. Reaching it at all takes a broken container; see resolveInstanceID.

Variables

View Source
var (
	ErrDSNRequired    = errors.New("DBB_DSN environment variable is required")
	ErrKeyRequired    = errors.New("either DBB_KEY or DBB_KEYFILE must be set")
	ErrInvalidKeySize = errors.New("encryption key must be 32 bytes")
)

Configuration errors.

Functions

func DefaultKeyFilePath

func DefaultKeyFilePath() (string, error)

DefaultKeyFilePath returns the path to the default key file (~/.dbbat/key).

func ParseLogLevel added in v0.1.0

func ParseLogLevel(level string) slog.Level

ParseLogLevel parses a log level string and returns the corresponding slog.Level. Supported values (case-insensitive): debug, info, warn, warning, error. Returns slog.LevelInfo for invalid values.

Types

type ApprovalConfig added in v0.20.0

type ApprovalConfig struct {
	// Enabled turns the approval gate on. When false, approval patterns on
	// grants are inert: nothing is ever held.
	Enabled bool `koanf:"enabled"`
	// SlackDelay is how long a hold must remain pending before a Slack
	// notification fires. Zero disables Slack escalation entirely. There is
	// no presence detection: if an admin was watching, they had this long to
	// act, and resolving the hold cancels the pending notification.
	SlackDelay string `koanf:"slack_delay"`
	// SlackSQL includes the (truncated) SQL text in the Slack message.
	// Default on. Slack is a lower trust boundary than the dbbat UI and this
	// feature pipes production query text into it, so it is switchable off.
	SlackSQL bool `koanf:"slack_sql"`
}

ApprovalConfig configures pattern-triggered approval holds — the four-eyes control that suspends a matching statement mid-flight until a second human approves it.

Enabled defaults to **false**. This feature blocks a live database connection on a human being; it ships off and gets turned on deliberately, per deployment.

func (ApprovalConfig) SlackDelayDuration added in v0.20.0

func (c ApprovalConfig) SlackDelayDuration() time.Duration

SlackDelayDuration parses SlackDelay, falling back to the default on a malformed value (a typo must not silently disable escalation). A zero or negative value disables escalation, which is an explicit opt-out.

type AuthCacheConfig added in v0.0.1

type AuthCacheConfig struct {
	// Enabled enables/disables the authentication cache.
	Enabled bool `koanf:"enabled"`

	// TTLSeconds is the time-to-live for cache entries in seconds.
	TTLSeconds int `koanf:"ttl_seconds"`

	// MaxSize is the maximum number of cache entries.
	MaxSize int `koanf:"max_size"`
}

AuthCacheConfig holds configuration for authentication caching.

type Config

type Config struct {
	// Proxy listen address.
	ListenPG string `koanf:"listen_pg"`

	// Oracle proxy listen address (empty = disabled).
	ListenOracle string `koanf:"listen_ora"`

	// MySQL proxy listen address (empty = disabled).
	ListenMySQL string `koanf:"listen_mysql"`

	// MongoDB proxy listen address (empty = disabled).
	ListenMongo string `koanf:"listen_mongo"`

	// REST API listen address.
	ListenAPI string `koanf:"listen_api"`

	// PostgreSQL DSN for DBBat storage.
	DSN string `koanf:"dsn"`

	// Base64-encoded encryption key (alternative to KeyFile).
	Key string `koanf:"key"`

	// Path to file containing encryption key (alternative to Key).
	KeyFile string `koanf:"keyfile"`

	// ConfigFile path (not loaded from config, set via CLI).
	ConfigFile string `koanf:"-"`

	// Encryption key for database credentials (32 bytes).
	// Populated from Key or KeyFile after loading.
	EncryptionKey []byte `koanf:"-"`

	// RunMode controls whether test data is provisioned on startup.
	RunMode RunMode `koanf:"run_mode"`

	// InstanceID identifies this dbbat process among the replicas sharing the
	// same store. It is stamped on every connection row so the startup
	// reconcile of crash-orphaned connections only ever touches connections
	// this instance opened. Defaults to the hostname, which is the pod name
	// under Kubernetes. Empty is not a valid runtime value — Load fills it in.
	InstanceID string `koanf:"instance_id"`

	// DemoTargetDB specifies the only allowed database target in demo mode.
	// Format: "user:password@host/dbname" (e.g., "demo:demo@localhost/demo")
	// Only applies when RunMode is "demo". If empty, defaults to "demo:demo@localhost/demo".
	DemoTargetDB string `koanf:"demo_target_db"`

	// QueryStorage holds query result storage configuration.
	QueryStorage QueryStorageConfig `koanf:"query_storage"`

	// RateLimit holds rate limiting configuration.
	RateLimit RateLimitConfig `koanf:"rate_limit"`

	// Hash holds password hashing configuration.
	Hash HashConfig `koanf:"hash"`

	// AuthCache holds authentication cache configuration.
	AuthCache AuthCacheConfig `koanf:"auth_cache"`

	// BaseURL is the base URL path for the frontend app (default: "/app").
	BaseURL string `koanf:"base_url"`

	// Redirects contains dev redirect rules parsed from DBB_REDIRECTS env var.
	// Not loaded from config file, parsed from environment only.
	Redirects []RedirectRule `koanf:"-"`

	// LogLevel controls the logging verbosity (debug, info, warn, error).
	// Default is "info".
	LogLevel string `koanf:"log_level"`

	// SlackAuth holds Slack OAuth configuration.
	SlackAuth SlackAuthConfig `koanf:"slack_auth"`

	// SlackNotify holds outbound Slack notification configuration for
	// grant request events.
	SlackNotify SlackNotifyConfig `koanf:"slack_notify"`

	// PublicURL is the externally reachable base URL for this dbbat
	// instance. Used to build deep-links in Slack notifications. Required
	// only if SlackNotify is enabled.
	PublicURL string `koanf:"public_url"`

	// Dump holds session packet dump configuration.
	Dump DumpConfig `koanf:"dump"`

	// MySQL holds MySQL proxy specific configuration.
	MySQL MySQLConfig `koanf:"mysql"`

	// Mongo holds MongoDB proxy specific configuration.
	Mongo MongoConfig `koanf:"mongo"`

	// PG holds PostgreSQL proxy specific configuration.
	PG PGConfig `koanf:"pg"`

	// Approval holds pattern-triggered approval-hold configuration.
	Approval ApprovalConfig `koanf:"approval"`
}

Config holds the application configuration.

func Load

func Load(opts LoadOptions, cliOverrides ...func(*Config)) (*Config, error)

Load reads configuration from environment variables and optional config file. Priority order: CLI overrides > Environment variables > Config file > Defaults

func (*Config) GetDemoTarget

func (c *Config) GetDemoTarget() *DemoTarget

GetDemoTarget parses and returns the demo target configuration. Returns nil if not in demo mode.

func (*Config) GetHashParams added in v0.0.1

func (c *Config) GetHashParams() ResolvedHashParams

GetHashParams returns the resolved hash parameters.

func (*Config) IsDemoMode

func (c *Config) IsDemoMode() bool

IsDemoMode returns true if running in demo mode.

func (*Config) ValidateDemoTarget

func (c *Config) ValidateDemoTarget(username, password, host, database string) string

ValidateDemoTarget checks if the given credentials match the demo target. Returns an error message if validation fails, or empty string if valid.

type DemoTarget

type DemoTarget struct {
	Username string
	Password string
	Host     string
	Server   string
}

DemoTarget holds the parsed demo target database credentials.

func ParseDemoTargetDB

func ParseDemoTargetDB(s string) *DemoTarget

ParseDemoTargetDB parses a demo target string in format "user:pass@host/dbname".

type DumpConfig added in v0.5.0

type DumpConfig struct {
	// Dir is the directory for dump files. Empty = disabled.
	Dir string `koanf:"dir"`

	// MaxSize is the maximum dump file size per session in bytes.
	MaxSize int64 `koanf:"max_size"`

	// Retention is the auto-delete duration for old dumps (e.g., "24h").
	Retention string `koanf:"retention"`
}

DumpConfig holds configuration for session packet dumps.

type HashConfig added in v0.0.1

type HashConfig struct {
	// Preset is a named configuration preset (default, low, minimal).
	Preset string `koanf:"preset"`

	// MemoryMB is the memory parameter in megabytes (1-1024).
	MemoryMB int `koanf:"memory_mb"`

	// Time is the time/iterations parameter (1-10).
	Time int `koanf:"time"`

	// Threads is the parallelism parameter (1-16).
	Threads int `koanf:"threads"`
}

HashConfig holds password hashing configuration.

type LoadOptions

type LoadOptions struct {
	// ConfigFile is the path to a config file (YAML, JSON, or TOML).
	ConfigFile string
}

LoadOptions configures how configuration is loaded.

type MongoConfig added in v0.16.0

type MongoConfig struct {
	// TLS holds TLS server-termination settings for the proxy. Mongo TLS is
	// implicit-from-byte-0 (no STARTTLS dance): when certs are configured (or
	// auto-generated) the proxy terminates TLS, and SASL PLAIN auth is only
	// accepted over TLS. When Disable is true the listener stays plaintext.
	TLS TLSConfig `koanf:"tls"`
}

MongoConfig holds configuration specific to the MongoDB proxy.

type MySQLConfig added in v0.7.0

type MySQLConfig struct {
	// TLS holds TLS server-termination settings for the proxy. When enabled,
	// the proxy advertises CLIENT_SSL and accepts SSL Request packets from
	// clients, terminating the TLS session at the proxy. Required for clean
	// caching_sha2_password full-auth (cleartext password over TLS).
	TLS TLSConfig `koanf:"tls"`
}

MySQLConfig holds configuration specific to the MySQL proxy.

type PGConfig added in v0.8.0

type PGConfig struct {
	// TLS holds TLS server-termination settings for the proxy. When enabled,
	// the proxy responds 'S' to SSLRequest and terminates TLS at the proxy.
	// Without this, clients with sslmode=prefer silently fall back to
	// plaintext and credentials travel over the wire in the clear.
	TLS TLSConfig `koanf:"tls"`
}

PGConfig holds configuration specific to the PostgreSQL proxy.

type QueryStorageConfig

type QueryStorageConfig struct {
	// MaxResultRows is the maximum number of rows to store per query.
	MaxResultRows int `koanf:"max_result_rows"`

	// MaxResultBytes is the maximum total bytes to store per query.
	MaxResultBytes int64 `koanf:"max_result_bytes"`

	// StoreResults enables/disables result storage globally.
	StoreResults bool `koanf:"store_results"`

	// Retention is how long query history (and the captured result rows
	// hanging off it) is kept, as a Go duration (e.g. "720h").
	//
	// Empty or "0" means keep forever, and that is the default: dbbat is an
	// audit tool, so an upgrade must never silently start deleting history.
	// Operators opt in — "720h" (30 days) is a reasonable starting point.
	Retention string `koanf:"retention"`
}

QueryStorageConfig holds configuration for query result storage.

func (QueryStorageConfig) RetentionDuration added in v0.20.0

func (c QueryStorageConfig) RetentionDuration() time.Duration

RetentionDuration parses Retention into a duration. A zero or negative result means "disabled — keep forever", and no sweep is scheduled.

A malformed value also disables the sweep rather than falling back to some built-in period: this sweep permanently deletes audit data, so a typo must never be interpreted as "delete more". The caller warns about it (see RetentionMisconfigured).

func (QueryStorageConfig) RetentionMisconfigured added in v0.20.0

func (c QueryStorageConfig) RetentionMisconfigured() bool

RetentionMisconfigured reports that Retention was set to something that is neither empty nor a usable positive duration — i.e. retention silently ends up disabled and the operator probably did not mean that.

type RateLimitConfig

type RateLimitConfig struct {
	// Enabled enables/disables rate limiting.
	Enabled bool `koanf:"enabled"`

	// RequestsPerMinute is the rate limit for authenticated users.
	RequestsPerMinute int `koanf:"requests_per_minute"`

	// RequestsPerMinuteAnon is the rate limit for unauthenticated requests (by IP).
	RequestsPerMinuteAnon int `koanf:"requests_per_minute_anon"`

	// Burst allows short bursts above the rate limit.
	Burst int `koanf:"burst"`
}

RateLimitConfig holds configuration for API rate limiting.

type RedirectRule

type RedirectRule struct {
	// PathPrefix is the path prefix to match (e.g., "/app").
	PathPrefix string
	// TargetHost is the target host to proxy to (e.g., "localhost:5173").
	TargetHost string
	// TargetPath is the path on the target (e.g., "/").
	TargetPath string
}

RedirectRule represents a path-based redirect for development proxying.

type ResolvedHashParams added in v0.0.1

type ResolvedHashParams struct {
	MemoryKB uint32
	Time     uint32
	Threads  uint8
}

ResolvedHashParams returns the hash parameters after applying presets. Individual settings override preset values.

type RunMode

type RunMode string

RunMode represents the application run mode.

const (
	// RunModeDefault is the default production mode.
	RunModeDefault RunMode = ""
	// RunModeTest provisions test data on startup.
	RunModeTest RunMode = "test"
	// RunModeDemo provisions demo data on startup with additional protections.
	RunModeDemo RunMode = "demo"
)

type SlackAuthConfig added in v0.4.0

type SlackAuthConfig struct {
	ClientID        string `koanf:"client_id"`
	ClientSecret    string `koanf:"client_secret"`
	TeamID          string `koanf:"team_id"`
	AutoCreateUsers bool   `koanf:"auto_create_users"`
	DefaultRole     string `koanf:"default_role"`
}

SlackAuthConfig holds Slack OAuth configuration.

func (SlackAuthConfig) Enabled added in v0.4.0

func (c SlackAuthConfig) Enabled() bool

Enabled returns true if Slack OAuth is configured with both client ID and secret.

type SlackNotifyConfig added in v0.10.0

type SlackNotifyConfig struct {
	// BotToken is the Slack bot user OAuth token (xoxb-...). Empty
	// disables notifications.
	BotToken string `koanf:"bot_token"`
	// Channel is the Slack channel id or name (e.g. "#dbbat") where
	// notifications are posted. Defaults to "#dbbat".
	Channel string `koanf:"channel"`
	// SigningSecret is the Slack app signing secret used to verify inbound
	// interaction callbacks (Approve/Deny button clicks). Empty disables
	// interactivity: messages carry no buttons and the inbound endpoint is
	// not registered — outbound notifications still work.
	SigningSecret string `koanf:"signing_secret"`
	// AppToken is the Slack app-level token (xapp-...) with the
	// connections:write scope. When set together with a bot token, dbbat
	// opens an outbound Socket Mode connection and receives Approve/Deny
	// interactions over it instead of the inbound HTTP endpoint — for
	// deployments that can't accept inbound Slack traffic. Empty = no Socket
	// Mode.
	AppToken string `koanf:"app_token"`
}

SlackNotifyConfig configures outbound Slack notifications for grant request events. Distinct from SlackAuthConfig (login OIDC) so deployments can enable one without the other.

func (SlackNotifyConfig) Enabled added in v0.10.0

func (c SlackNotifyConfig) Enabled() bool

Enabled returns true when a bot token is set. Channel is enforced at startup when Enabled is true; this method only gates whether the notifier should run at all.

func (SlackNotifyConfig) Interactive added in v0.14.0

func (c SlackNotifyConfig) Interactive() bool

Interactive returns true when Approve/Deny buttons should be rendered and an inbound interaction transport should be served. A bot token (to carry the buttons on notification messages) plus at least one inbound transport — a signing secret (the HTTP endpoint) or an app-level token (Socket Mode) — is required. A signing secret or app token without a bot token is a misconfiguration caught at startup.

func (SlackNotifyConfig) SocketMode added in v0.14.0

func (c SlackNotifyConfig) SocketMode() bool

SocketMode returns true when dbbat should open an outbound Slack Socket Mode connection: both an app-level token and a bot token are set. An app token without a bot token is a misconfiguration caught at startup.

type TLSConfig added in v0.7.0

type TLSConfig struct {
	// CertFile is the path to a PEM-encoded server certificate.
	CertFile string `koanf:"cert_file"`

	// KeyFile is the path to a PEM-encoded server private key.
	KeyFile string `koanf:"key_file"`

	// Disable turns off TLS termination entirely. When true, SSL Request
	// packets from clients are refused and connections stay plaintext.
	Disable bool `koanf:"disable"`
}

TLSConfig holds TLS server-side termination settings.

When CertFile and KeyFile are both empty (and Disable is false), the proxy auto-generates a self-signed certificate at startup. This is suitable for development; production deployments should provide a real certificate.

Jump to

Keyboard shortcuts

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