A transparent database proxy for query observability, access control, and safety. Supports PostgreSQL, Oracle, MySQL/MariaDB, MongoDB and Microsoft SQL Server. Every query logged. Every connection tracked.
This project uses Conventional Commits and release-please for automated releases.
PR titles MUST follow the conventional commit format:
<type>(<scope>): <description>
Types:
| Type | Description | Version Bump |
|---|---|---|
feat |
New feature | Minor (0.x.0) |
fix |
Bug fix | Patch (0.0.x) |
docs |
Documentation only | None |
style |
Code style (formatting, semicolons) | None |
refactor |
Code change that neither fixes a bug nor adds a feature | None |
perf |
Performance improvement | Patch |
test |
Adding or updating tests | None |
build |
Build system or external dependencies | None |
ci |
CI configuration | None |
chore |
Other changes (deps, tooling) | None |
Scopes (optional): api, auth, config, crypto, db, deploy, deps, docs, dump, grants, migrations, mongodb, mssql, mysql, oracle, postgresql, proxy, store, ui, release, ci
This list is enforced by the scopes: input of .github/workflows/semantic-pr.yml β same set, same order. Edit both or neither.
Breaking Changes: Add ! after type/scope or include BREAKING CHANGE: in body for major version bumps.
Examples:
feat(api): add user export endpointfix(proxy): handle connection timeout gracefullychore(deps): update go dependenciesfeat!: redesign authentication flow(breaking change)
- Language: Go
- Storage: PostgreSQL
- ORM:
uptrace/bunwith SQL migrations - Proxies:
- PostgreSQL wire protocol via
jackc/pgx/v5 - Oracle TNS/TTC (hand-rolled) β see
docs/oracle.md - MySQL/MariaDB via
go-mysql-org/go-mysql(server + client) β seedocs/mysql.md - MongoDB wire protocol (hand-rolled
OP_MSG; BSON viago.mongodb.org/mongo-driver/v2) β seedocs/mongodb.md - Microsoft SQL Server TDS (hand-rolled) β see
docs/mssql.md
- PostgreSQL wire protocol via
- Tunnels (
via_uid): a server row with protocolsshorkubernetesis a dial path, never a grantable target. SSH opens adirect-tcpipchannel to anyhost:port; Kubernetes opens apods/portforwardstream to a pod's own port (host=<pod>orsvc/<name>,port= container port) β a database merely routable from the cluster network is out of scope. Seedocs/kubernetes.md - API:
gin-gonic/ginwith OpenAPI 3.0 docs - CLI:
urfave/cli/v3 - Config:
knadh/koanf - Logging:
log/slog - Frontend: React 19 + TypeScript + Vite (see
front/CLAUDE.md). Edit forms are pages with their own route (<entity>/$uid); create forms are dialogs on the list page - Capture format: Protocol-agnostic pcapng, readable by tcpdump/Wireshark (
docs/dump-format.md) - Live stream + approvals: WebSocket event stream and pattern-triggered approval holds (
docs/approvals.md) - Tamper-evident audit trail:
audit_log,queriesandquery_rowsare HMAC-chained with a key HKDF-derived fromDBB_KEY;dbbat audit verifywalks the chains (docs/audit-chain.md) - MCP (AI agents): Streamable-HTTP endpoint at
/api/v1/mcpviagithub.com/modelcontextprotocol/go-sdk. Agent statements are executed by dialing dbbat's own proxy listener over loopback as the API key's owner β never a parallel internal path. All five protocols (docs/mcp.md)
dbbat/
βββ main.go # Entry point with CLI commands (serve, db, dump)
βββ internal/
β βββ config/ # koanf-based config loading (env, file, CLI)
β βββ crypto/ # Password hashing (Argon2id) + AES-256-GCM encryption
β βββ migrations/sql/ # SQL migration files (up/down)
β βββ store/ # Database models and CRUD operations
β βββ cache/ # Auth cache shared by API + proxies
β βββ safe/ # Goroutine panic guards (`RunRelay`/`RunGuarded`/`RunWatchdog`/`RunMaintenance`). A **leaf**: standard library only, so every package β `cache` and `proxy/upstream` included β can import it without a cycle. A test fails the build if a non-stdlib import creeps in
β βββ events/ # In-process topic broker behind GET /api/v1/stream
β βββ approval/ # Registry of queries parked awaiting a human
β βββ mcp/ # MCP server for AI agents; executes SQL by dialing our own proxy listeners (see docs/mcp.md)
β βββ dump/ # Session packet dump format (read/write/anonymise)
β β βββ decode/ # `dbbat dump decode`: a capture as one line per protocol message, redacted by default (PostgreSQL only so far)
β βββ api/ # REST API handlers and middleware
β β βββ openapi.yml # OpenAPI 3.0 specification
β βββ proxy/
β β βββ shared/ # Auth, query interception, upstream transport (dial + SSH bastion + K8s tunnel)
β β βββ upstream/ # One upstream-connect path per protocol, shared by the proxies and the connectivity check (ssl_mode policy lives here); also the sole home of `k8s.io/client-go` (`kubernetes*.go`)
β β βββ conncheck/ # Connectivity check: runs the connectors above, classifies the failure
β β βββ postgresql/ # PostgreSQL wire protocol proxy
β β βββ oracle/ # Oracle TNS/TTC proxy (see docs/oracle.md)
β β βββ mysql/ # MySQL/MariaDB proxy (see docs/mysql.md)
β β βββ mongodb/ # MongoDB wire protocol proxy (see docs/mongodb.md)
β β βββ mssql/ # SQL Server TDS proxy (see docs/mssql.md)
β β βββ kubernetes/ # No product code: the `//go:build integration` end-to-end suite for the K8s tunnel (a real k3s cluster) β it lives outside `upstream/` because it also drives the proxy and conncheck, which import it
β βββ auth/ # OAuth provider abstraction
β βββ slack/ # Slack OIDC login (fixed endpoints, userInfo-based)
β βββ oidc/ # Generic OIDC login: any issuer, verified ID tokens, PKCE
βββ front/ # React frontend (see front/CLAUDE.md)
βββ website/ # Docusaurus site for dbbat.com
βββ docs/ # Protocol-level technical notes (oracle, mysql, mongodb, mssql, kubernetes tunnel, dump format, mcp)
βββ docker-compose.yml
βββ go.mod
# Development
make dev # Start full dev environment (frontend + backend with hot reload)
make dev-front # Start only frontend dev server
make dev-back # Start only backend with Air
make dev-stop # Stop all dev servers
# Building
make build-app # Build everything (frontend + backend binary)
make build-binary # Build Go binary only
make build-front # Build frontend only (to internal/api/resources/)
make build-image # Build Docker image
# Testing
make test # Run Go unit tests
make test-e2e # Run Playwright E2E tests
make lint # Run golangci-lint
# Website media (on demand only β never part of a release)
make showcase # Regenerate website/static/img/showcase/ from a live demo instance
# Integration suites (real containers via testcontainers; `make test` skips them)
make test-integration-mongodb # ./internal/proxy/mongodb/...
make test-integration-mssql # ./internal/proxy/mssql/... (amd64 image)
make test-integration-mysql # ./internal/proxy/mysql/...
make test-integration-postgresql # ./internal/proxy/postgresql/...
make test-e2e-oracle # ./internal/proxy/oracle/...
make test-integration-kubernetes # ./internal/proxy/kubernetes/ (a real k3s cluster)
# Other
make demo # Build and run in demo mode
make clean # Clean build artifactsNever kill the running dbbat instance. It is started beforehand with make dev which provides live reload (Air). Restarting it would break the dev workflow. The test mode credentials are admin/admintest.
When debugging the server, read the latest log in logs/ first: tail -50 "$(ls -t logs/*.log | head -1)".
Deployment-specific notes (hosts, keys, runbooks) stay out of this public file, in the gitignored
CLAUDE.priv.md, imported when present: @CLAUDE.priv.md
Whenever you identify a follow-up task β an out-of-scope improvement, a deferred fix, a known limitation, or "we should also do X later" β write it into specs/todos/ autonomously, in the same turn, without being asked. Don't just mention it in chat or leave it only in an ephemeral task list: chat scrolls away, specs/todos/ is the durable backlog.
Conventions (see specs/README.md):
- One markdown file per task, named
specs/todos/YYYY-MM-DD-NN-short-kebab-name.md(date = today).NNis a two-digit execution order within that date, so a plainlsofspecs/todos/reads as the queue: lowest date, then lowest number, gets done first. Filing a new todo means picking its slot β append it after the lastNNof the day unless it genuinely blocks something already queued, in which case renumber. Order by what must happen first (a prerequisite, a suite that currently verifies nothing, a live correctness bug), not by when it was written. - Lead with
# Title, then## Goal,## Why, and## Implementation(sketch the approach + key files). Enough that someone can pick it up cold. - Never create GitHub issues, and never ask for one to be created. Don't add
"No GitHub issue filed yet β one should be" notes to a spec, and don't treat a
missing issue as outstanding work; the spec file is the tracking item. Link an
existing issue only if one already happens to exist. See
specs/README.md. - When a todo is implemented, move its file to
specs/done/YYYY/MM/(keep the same filename).
This applies even when the current task is otherwise complete β capture the follow-up before moving on.
./dbbat # Start server (default command)
./dbbat serve # Start server explicitly
./dbbat db migrate # Run pending migrations
./dbbat db rollback # Rollback last migration group
./dbbat db status # Show migration status
./dbbat dump anonymise <in> [out] # Strip session metadata from a .pcapng capture
./dbbat dump decode <in> [--rows] # Print a capture as one line per protocol message (PostgreSQL only so far; values redacted unless --rows)
./dbbat audit verify # Walk the audit_log HMAC chain; non-zero exit on a break
./dbbat audit verify --queries [--connection <uid>] # Same for the per-connection query chains
./dbbat audit verify --rows [--connection <uid>] # Same for the per-query captured result row chains| Variable | Description | Required |
|---|---|---|
DBB_DSN |
PostgreSQL DSN for DBBat storage | Yes |
DBB_LISTEN_PG |
PostgreSQL proxy listen address (default: :5433) |
No |
DBB_LISTEN_ORA |
Oracle proxy listen address (default: :1522; empty disables) |
No |
DBB_LISTEN_MYSQL |
MySQL/MariaDB proxy listen address (default: :3307; empty disables) |
No |
DBB_LISTEN_MONGO |
MongoDB proxy listen address (default: :27018; empty disables) |
No |
DBB_LISTEN_MSSQL |
SQL Server (TDS) proxy listen address (default: :1434; empty disables). 1434/tcp is free β the SQL Server Browser that owns 1434 is UDP-only |
No |
DBB_LISTEN_API |
REST API listen address (default: :4200) |
No |
DBB_KEY |
Base64-encoded AES-256 encryption key | No |
DBB_KEYFILE |
Path to file containing encryption key | No |
DBB_RUN_MODE |
Run mode: empty, test, or demo |
No |
DBB_LOG_LEVEL |
Log level: debug, info, warn, error (default: info) |
No |
DBB_INSTANCE_ID |
Identifies this process among replicas sharing the store (default: hostname). Stamped on connection rows next to a non-configurable per-run UUID, and registered in the instances table β keyed by (instance_id, run_id) β with a 30s heartbeat. The reconcile closes crash-orphaned connections whose owning run deregistered or went 15min without a heartbeat, never a run that is still heartbeating, so replicas sharing an id are safe (just confusing). The liveness half also re-runs every ~7.5min while the process lives, covering both crashed peers and this id's own previous runs. That same tick re-stamps the query-chain head of the sessions this run still has open (Store.RefreshOpenChainStamps), which is what bounds how long a live session's tail goes unsealed. |
No |
DBB_DUMP_DIR |
Directory for session dump files (empty = disabled) | No |
DBB_DUMP_MAX_SIZE |
Max dump file size per session in bytes (default: 10MB) | No |
DBB_RETENTION_DUMPS_DELETE_AFTER |
Auto-delete dumps older than this (default: 24h, the one default that is not "never"; 0 = never). Applies to the local spool only β dbbat never expires objects it uploaded. Run by the retention sweeper, not by the proxies |
No |
DBB_DUMP_UPLOAD_URL |
Blob bucket finished captures are uploaded to on session close, e.g. s3://bucket/prefix (s3:// for S3 and any S3-compatible store, file:// for a directory; no gs:// or azblob:// driver, see the S3 route in website/docs/features/session-dumps.md). Empty = local disk only, the default. Requires DBB_DUMP_DIR, which becomes the spool: captures are always written locally and uploaded once complete, never streamed live. Object key <prefix>/YYYY/MM/DD/<instance-id>/<connection-uid>.pcapng, recorded on the connection row so downloads never LIST the bucket. Remote retention is the bucket lifecycle policy. See docs/dump-format.md |
No |
DBB_QUERY_TAGGING |
Prepend a sqlcommenter-style comment β /*dbbat='<version>',user='<user>',conn='<12hex>',grant='<definition-slug>'*/ β to every statement forwarded to the target, so the target's own tooling (RDS Performance Insights, pg_stat_statements, the slow log) can attribute it to a dbbat user/connection/grant rather than to the one shared role every session logs in as. Off by default: it changes the bytes the database receives. It is the deployment default, not the switch: the tagging.enabled store parameter wins over it when set β in both directions, a stored false overriding a DBB_QUERY_TAGGING=true β and that is the layer the Settings page and PUT /instance/tagging edit, without a redeploy. Resolved per session, at authentication (shared.QueryTaggingResolver, over the same cached read as the statement timeout), so a live session keeps the decision it authenticated under; terminate it to make it reconnect under the new one. PostgreSQL, MySQL/MariaDB and MongoDB β on MongoDB there is no statement text to comment, so the same dbbat='β¦',user='β¦',conn='β¦',grant='β¦' string rides in the command's comment field (find, aggregate, getMore, insert, update, delete, β¦ β an allowlist), where system.profile, the Atlas profiler and db.currentOp() echo it back; a client-supplied comment wins and that command is forwarded untouched, since the field is single-valued and a driver's own tracing may own it. Oracle has its own switch, DBB_QUERY_TAGGING_ORACLE (below), and this one deliberately does not reach it. SQL Server is a follow-up. Prepended rather than appended, because pg_stat_activity.query and the slow log truncate at the end. It carries no timestamp and no per-statement id, so repeated executions stay byte-identical and the digest keeps aggregating them. conn= is the same 12 hex characters as the app-name c= tag. Applied on the wire only: PG Query and Parse (once β every Execute inherits it), MySQL COM_QUERY and COM_STMT_PREPARE (COM_STMT_EXECUTE is binary and untouched), MongoDB the forwarded OP_MSG body. Every grant control, every bypass scan and every approval pattern runs on the client's text beforehand, and the queries table, the audit chain, the UI's text search and the .pcapng captures all store the client's text β the tag is reconstructible from the connection row, so it is never persisted. See docs/postgresql.md, docs/mysql.md and docs/mongodb.md |
No |
DBB_QUERY_TAGGING_ORACLE |
Oracle's own statement tag: off (default) or user. The deployment default for the tagging.oracle store parameter, which wins over it when set (Settings page / PUT /instance/tagging); an unrecognized value is a startup failure here but a 400 there, and one that reaches the store anyway folds to off with a WARN rather than failing every replica's next restart. Separate from DBB_QUERY_TAGGING because the trade-off is Oracle's alone β V$SQL keys on statement text, so every distinct tag is a distinct SQL_ID holding its own shared-pool cursor. Measured on 23ai (600 executions of one join): a per-connection tag costs 200 cursors and 9.6MB for 200 sessions and has no ceiling; dropping conn= bounds it at one cursor per dbbat user, ~48KB and one hard parse each, then a flat plateau (a second 600 executions added zero loads and zero bytes). Hence user as the only non-off value, and shared.NewUserQueryTagger's conn-less bytes. Anything else is a startup failure. Unlike the other three protocols, the Oracle proxy relays the client's own TNS packets, so turning this on does not oblige it to tag: internal/proxy/oracle/ttc_statement_rewrite.go rewrites a frame only when it can relocate the statement to the byte β the SQL-length field's offset, width and encoding (compressed int on the 03 5e/11 69 execs, sqlLen*3 ub4 for the 4-byte OCI dialect, a plain-byte-count ub8 for the 64-bit one, decodeVarLen on OALL8), the value's span and its CLR framing (short, bare, or 0xFE-chunked) β and re-encoding what it read reproduces the client's own bytes. Injected in clientToUpstream between the blocked check and the write loop, so the controls, the queries row, the audit chain and the capture have all already run on the client's text. The decision is per session and taken once: a client shape the locator cannot certify runs untagged start to finish and logs why, because a statement tagged on some executions and not others would get two SQL_IDs and double the cursor count the design exists to bound. 186/186 recorded frames in testdata/*.pcapng locate and round-trip, plus the three 64-bit OCI parses in testdata/oci64_parse_execs.hex that no pcapng recording can carry; see docs/oracle.md |
No |
DBB_RETENTION_QUERIES_DELETE_AFTER |
Auto-delete query history (and captured result rows) older than this Go duration. Unset or 0 = never; 720h (30 days) is a reasonable opt-in value. The statement window, and the one store.Options.QueryRetention is fed from. Config key retention.queries.delete_after |
No |
DBB_RETENTION_QUERIES_ARCHIVE_AFTER |
Move the result rows of a closed connection to the archive bucket (DBB_ARCHIVE_URL) this long after it closed. Unset or 0 = never. Ignored with a startup WARN while DBB_ARCHIVE_URL is unset. Config key retention.queries.archive_after |
No |
DBB_ARCHIVE_URL |
Bucket (s3://bucket/prefix or file:///dir) archived result rows go to. Empty = archival does not exist. See docs/archive.md |
No |
DBB_RETENTION_CONNECTIONS_DELETE_AFTER |
Auto-delete closed connections β the session ledger (who, from where, to which database, under which grant) β once disconnected_at is older than this Go duration, cascading to whatever queries and rows they still have. Unset or 0 = never (no inheritance: statements can expire while the ledger stays). It must be β₯ the statement window; a shorter one, a malformed or negative value, an unknown DBB_RETENTION_* name, a removed pre-uniform name still set (the three old *_RETENTION variables are never read, the WARN gives the new name), or a non-zero value with statements kept forever zeroes every window (dumps included) with a startup WARN, never a startup failure. All rules live in config.Config.RetentionWindows(). Note the object key of an uploaded capture lives on the connection row, so a ledger window shorter than the bucket lifecycle orphans those objects |
No |
DBB_MYSQL_TLS_DISABLE |
Refuse TLS upgrade on the MySQL listener (default: false) |
No |
DBB_MYSQL_TLS_CERT_FILE |
PEM cert for MySQL TLS termination (auto self-signed if empty) | No |
DBB_MYSQL_TLS_KEY_FILE |
PEM RSA key for MySQL TLS termination (auto-generated if empty) | No |
DBB_PG_TLS_DISABLE |
Refuse TLS upgrade on the PostgreSQL listener (default: false) |
No |
DBB_PG_TLS_CERT_FILE |
PEM cert for PostgreSQL TLS termination (auto self-signed if empty) | No |
DBB_PG_TLS_KEY_FILE |
PEM key for PostgreSQL TLS termination (auto-generated if empty) | No |
DBB_MONGO_TLS_DISABLE |
Keep the MongoDB listener plaintext β refuse TLS termination (default: false) |
No |
DBB_MONGO_TLS_CERT_FILE |
PEM cert for MongoDB TLS termination (auto self-signed if empty) | No |
DBB_MONGO_TLS_KEY_FILE |
PEM key for MongoDB TLS termination (auto-generated if empty) | No |
DBB_MSSQL_TLS_DISABLE |
Keep the SQL Server listener plaintext β answer ENCRYPT_NOT_SUP (default: false) |
No |
DBB_MSSQL_TLS_CERT_FILE |
PEM cert for SQL Server TLS termination (auto self-signed if empty) | No |
DBB_MSSQL_TLS_KEY_FILE |
PEM key for SQL Server TLS termination (auto-generated if empty) | No |
DBB_MSSQL_TLS_MAX_VERSION |
Client-leg TLS ceiling: 1.2 (default) or 1.3; anything else fails at startup. TDS encapsulates the handshake and un-wraps it the moment it completes, and at 1.3 the client finishes on a write, so drivers differ on whether that last flight is still framed β the proxy sniffs the first byte and follows either choice, but 1.3 is verified against go-mssqldb only (ODBC/JDBC untested), hence opt-in. The upstream leg stays at 1.2. See docs/mssql.md |
No |
DBB_OIDC_ISSUER |
OIDC issuer URL for the generic SSO provider (internal/auth/oidc). Setting it enables the provider; discovery is lazy, so an unreachable IdP delays the first login instead of blocking startup. Registered under provider key oidc; the callback is /api/v1/auth/oidc/callback |
No |
DBB_OIDC_CLIENT_ID |
OIDC client id. Required once the issuer is set β a half-configured provider fails at startup | If issuer set |
DBB_OIDC_CLIENT_SECRET |
OIDC client secret. Same rule | If issuer set |
DBB_OIDC_SCOPES |
Space- or comma-separated scopes (default: openid email profile); openid is always added |
No |
DBB_OIDC_DISPLAY_NAME |
Login-button label, surfaced through GET /api/v1/auth/providers as display_name (default: SSO) |
No |
DBB_OIDC_EMAIL_DOMAINS |
Comma-separated allowlist checked against the verified ID-token email claim β the generic equivalent of Slack's team-id gating. Empty = any domain the issuer vouches for, which on a multi-tenant issuer (accounts.google.com, Entra /common) means any account on the internet |
No |
DBB_OIDC_GROUPS_CLAIM |
ID-token claim carrying directory group membership (default: groups). Both encodings are accepted β a JSON array and the single-string shorthand β and a lone string is one group, never a delimited list. A token that delegates this claim through _claim_names (Entra's groups overage, past ~200 memberships) is read as membership unknown, not empty: the login succeeds, DBB_OIDC_ROLE_MAPPING is skipped entirely, roles are left untouched with no default-role floor, and a WARN names the user and the claim. dbbat never follows the pointer to Microsoft Graph |
No |
DBB_OIDC_ROLE_MAPPING |
Binds dbbat roles to directory groups: admin=db-admins,viewer=analysts. Pairs split on commas only (group names contain spaces); repeat a role to union its groups. Values match exactly, case included β Entra sends group object ids, not names. Applied on every login, authoritative only for the roles it names, floored at the default role, and refuses to strip the last admin. Empty = roles stay manual. Malformed = startup failure. See website/docs/configuration/sso.md |
No |
DBB_AUTH_AUTO_CREATE_USERS |
Let a verified OAuth/OIDC identity with no local account provision one on first login (default: true). Provider-agnostic β it gates Slack, the generic OIDC issuer and anything added later, which is why it is no longer named after Slack. Legacy alias DBB_SLACK_AUTH_AUTO_CREATE_USERS is still accepted; the canonical setting wins whenever both are present, whichever source each came from (env or config file) β the alias spans two config keys, so precedence is resolved against what the operator actually configured, not just the environment |
No |
DBB_AUTH_DEFAULT_ROLE |
Role an auto-provisioned account starts with, and the floor DBB_OIDC_ROLE_MAPPING never digs below (default: connector). Validated against the known roles at startup β a typo is a startup failure, not a user silently provisioned into a role nothing recognizes. Matched exactly: Admin is refused, never folded to admin, because the pre-rename code read this value raw and a mis-cased one granted nothing β normalizing it would turn a dormant typo into a real admin default on upgrade alone. Legacy alias DBB_SLACK_AUTH_DEFAULT_ROLE, same precedence rule |
No |
DBB_AUTH_AUTO_CREATE_USERS_<PROVIDER> / DBB_AUTH_DEFAULT_ROLE_<PROVIDER> |
Per-provider override of the two settings above (..._SLACK, ..._OIDC); equivalently auth.providers.<name>.auto_create_users / .default_role in a config file. Each setting resolves per-provider β instance-wide β default, which is what lets a deployment trust a tightly-gated Entra tenant to mint accounts while refusing the same from a Slack workspace full of contractors. Two things fail closed at startup rather than becoming an override that quietly does not apply β both would leave the operator with the policy they were trying to change: a per-provider role goes through the same exact-match KnownRoles check (Admin still refused), and a provider name outside config.KnownOAuthProviders is an error. The bool is a *bool internally because auto-provisioning defaults to on, so "unset" and "false" must be distinguishable. Gating a provider blocks account creation, never sign-in by an account that already exists. The legacy DBB_SLACK_AUTH_* aliases stay instance-wide β they are not the Slack override |
No |
DBB_SLACK_NOTIFY_BOT_TOKEN |
Slack bot user OAuth token (xoxb-...); empty disables notifications |
No |
DBB_SLACK_NOTIFY_CHANNEL |
Default Slack channel id or name for notifications (default: #dbbat); used by a grant definition that names no notify_channel |
No |
DBB_SLACK_NOTIFY_CHANNELS |
Named extra channels a grant definition can route to with notify_channel: comma-separated key=channel pairs, e.g. prod=#dbbat-prod,nonprod=#dbbat-nonprod. Keys match ^[a-z0-9][a-z0-9_-]*$, none is reserved (a definition with notify_channel: none posts nothing, except approval holds which fall back to the default channel). Grant requests, terminations, byte notices and approval holds all follow the definition's channel; a request's follow-ups keep the channel it was first posted in. Malformed = startup failure; a stored key missing from the config only WARNs and uses the default. Keys are listed in GET /instance notify_channels |
No |
DBB_SLACK_SIGNING_SECRET |
Slack app signing secret; enables Approve/Deny buttons + inbound interactions endpoint. Empty = link-through-UI (no buttons). Requires the bot token. Legacy alias DBB_SLACK_NOTIFY_SIGNING_SECRET is also accepted; the canonical name wins if both are set. |
No |
DBB_SLACK_NOTIFY_APP_TOKEN |
Slack app-level token (xapp-..., scope connections:write); enables Socket Mode β receives Approve/Deny clicks over an outbound WebSocket instead of the inbound endpoint (for deployments Slack can't reach inbound). Requires the bot token. |
No |
DBB_SLACK_NOTIFY_TERMINATIONS |
Post a Slack message when dbbat ends a session on its own for a reason worth a human's attention: statement_timeout, admin_terminated, quota_exceeded (never grant_revoked β already went through a human β, grant_expired, or instance_lost). Default true; only meaningful when DBB_SLACK_NOTIFY_BOT_TOKEN is set. Repeated terminations for the same (user, database, reason) within 10 minutes are coalesced into one follow-up rather than flooding the channel |
No |
DBB_SLACK_NOTIFY_SQL |
Include the (truncated, 200-char) statement text in a termination Slack message. Default true, mirrors DBB_APPROVAL_SLACK_SQL |
No |
DBB_SLACK_NOTIFY_BYTES_STEP |
Byte soft limit per grant: each time a grant's cumulative bytes (the quota's own aggregate, across all its connections and replicas) cross another multiple of this step, reply in the grant request's Slack thread, or post to DBB_SLACK_NOTIFY_CHANNEL for a grant with no request. Never blocks. A byte count or a binary size (1GiB); default 0 = off; negative or unparsable = startup failure. A definition's notify_bytes_step overrides it (0 = off for that definition). Swept every minute on the instance heartbeat loop; access_grants.bytes_notified_steps is claimed with a conditional UPDATE, which is the cross-replica dedupe. Also writes a grant.bytes_threshold audit entry. Bytes count at statement completion. See internal/store/grant_bytes_notify.go |
No |
DBB_SLACK_NOTIFY_RENEWAL_WINDOW |
Auto-approved renewal threading: an auto-approved grant request that renews an earlier one (same user, database and definition lineage, controls read_only/block_ddl/block_copy unchanged, earlier grant still active or ended within this window) is posted as a one-line reply in the thread of the first request of the chain instead of a new top-level message. The root rolls over once it is older than the window. A Go duration; default 24h; 0 = off; negative or malformed = startup failure. Requests needing a decision always stay top-level. Persisted in grant_requests.slack_thread_root_uid, whose slack_channel/slack_message_ts then hold the root's coordinates (never chat.update them). A #name channel is matched to the stored channel ID only after this process has posted to it once, so the first renewal after a restart may post top-level |
No |
DBB_PUBLIC_URL |
Externally reachable base URL; used for deep-links in Slack notifications | If notify enabled |
DBB_TRUSTED_PROXIES |
Reverse proxies (IPs or CIDRs, comma- or space-separated) whose X-Forwarded-For / X-Real-IP the API believes. Empty, the default, trusts nobody: the client IP is the socket peer whatever headers it sends. That IP keys the anonymous rate limits and the access log's client_ip, so trusting every peer (gin's own default) let a client pick a fresh rate-limit bucket per request. Behind an ingress, set the ingress's CIDR (Helm: config.trustedProxies), or every client shares the ingress's bucket. A malformed entry is a startup failure |
No |
DBB_STATEMENT_TIMEOUT |
Instance-wide per-statement time limit, as a Go duration (30s, 5m). Empty or 0 β the default β means no limit, so an upgrade never starts cancelling statements on its own. It is the lowest of three layers: the operator-set limits.statement_timeout store parameter wins over it (the way public.* wins over DBB_LISTEN_*), and a grant definition's statement_timeout_seconds wins over both β including an explicit 0, which is how a dump or ETL definition stays usable. A malformed value disables the limit with a startup WARN rather than shortening it. Enforcement is dbbat's own watchdog (LimitGuard, 250ms tick, limit + 2s grace); the server-side setting each protocol offers is only how the client learns why. See "Per-statement time limits" below |
No |
DBB_APPROVAL_ENABLED |
Enable pattern-triggered approval holds (four-eyes on a statement). Off by default β a hold blocks a live database connection on a human. See docs/approvals.md |
No |
DBB_APPROVAL_SLACK_DELAY |
How long a hold stays pending before escalating to Slack (default: 30s; 0 disables) |
No |
DBB_APPROVAL_SLACK_SQL |
Include the (truncated) SQL text in the Slack escalation (default: true) |
No |
DBB_MCP_ENABLED |
Serve the Model Context Protocol endpoint at POST /api/v1/mcp for AI agents (default: true). API-key authenticated; every agent statement runs through the proxy listener over loopback, so grants, quotas, logging and approval holds apply unchanged. All five protocols are covered; on MongoDB the statement is <command> <extJSON> rather than SQL. false removes the routes entirely. See docs/mcp.md |
No |
Note: If no encryption key is provided, one is created at ~/.dbbat/key.
make test # Uses testcontainers-go for PostgreSQLBehind //go:build integration, so make test neither compiles nor runs them.
make test-integration-mongodb # and -mysql, -postgresql, -mssql, plus test-e2e-oraclemake test-integration-kubernetes is the odd one out: instead of an upstream
database container it boots a k3s cluster (privileged container) and runs a
PostgreSQL pod inside it, so the tunnel is exercised against a real API server
and a real kubelet β the websocket transport, RBAC as the API server evaluates
it, and a pod that is deleted mid-suite. The cluster is pinned to β₯1.31
(K3S_TEST_IMAGE overrides it) because the websocket port-forward handler is
only on by default from there. See docs/kubernetes.md.
Use the Make target, not a bare go test -tags integration ./internal/proxy/....
Every test starts its own upstream container and its own PostgreSQL storage
container, so a suite is dominated by container startup: the MongoDB suite
takes ~4min idle, ~7min with other containers competing for the Docker daemon,
and has been seen past 12min. go test's default timeout is 10min, so the bare
command panics on a busy machine even when nothing is wrong. The targets pass
-timeout 40m, matching .github/workflows/integration.yml; a run that exceeds
that is a real regression, not a busy laptop.
make test-e2e # Builds app, starts server in test mode, runs Playwrightmake test-e2e / bun run test:e2e[:chromium] without CI=true.
Without it, front/e2e/global-setup.ts runs docker compose up -d postgres, which mounts the
persistent dbbat_postgres-data volume that make dev uses, then starts dbbat with
DBB_RUN_MODE=test, which drops every table on startup (DropTablesFirst, no prompt). That
wiped months of local audit_log history on 2026-09-23. demo mode does the same. Instead:
build, start a throwaway, uniquely named PostgreSQL container on a non-default port (never 5001,
never the compose postgres service), run ./dbbat serve with DBB_RUN_MODE=test against it on
:8080, then CI=true bun run test:e2e (the setup then only polls the health endpoint), and
remove the container. When a subagent runs E2E, check the command it actually ran, not its
summary.
Test mode credentials: admin/admintest, viewer/viewer, connector/connector
front/showcase/ is a separate Playwright project that regenerates the
website's marketing screenshots and the two approval-hold clips into
website/static/img/showcase/. It is not part of make test-e2e and never
gates CI.
make showcase # everything
SHOWCASE_PROJECT=video make showcase # just the psql clip
SHOWCASE_PROJECT=mcp-poster,mcp-video make showcase # just the MCP clip + its poster
SHOWCASE_SKIP_BUILD=1 make showcase # reuse the existing ./dbbat
SHOWCASE_KEEP=1 make showcase # leave the stack up to poke at
SHOWCASE_PG_TIMEOUT=120 make showcase # give the upstream more time on a cold pullscripts/showcase.sh owns the lifecycle: it starts its own throwaway
PostgreSQL container and its own demo-mode dbbat on ports 8099/5499/5099,
and removes only what it created. It never calls docker compose β demo mode
drops every table on startup, so pointing it at the shared dev stack would
destroy that database. Demo-mode credentials are admin/admin,
viewer/viewer, connector/connector.
There are two approval clips, the same hold from either side. The first
drives a real pg client through the proxy; the second (mcp-approval-hold-*)
issues the statement over MCP as an AI agent would β real JSON-RPC against
POST /api/v1/mcp with a dbb_ key β and shows query answering
approval_pending, the human releasing it, and await_approval handing back
the rows. Both draw their client pane and the mouse pointer (neither a real
terminal nor a real agent is reproducible in CI, and Playwright records no
cursor); neither fakes a result. ffmpeg transcodes each WebM to AV1
(libsvtav1) plus an H.264 fallback for Safari.
Every run writes website/static/img/showcase/manifest.json
(version/commit/generatedAt), version read from
.release-please-manifest.json β regeneration is on demand, so the manifest is
what makes staleness visible. .github/workflows/showcase.yml exposes the same
pipeline as a workflow_dispatch job, plus a non-blocking rot guard that runs
the suite on front/ pull requests with the output discarded.
The homepage consumes all of it (website/src/components/ProductShowcase/),
manifest caption included. It is the site's only screenshot set β the old
hand-captured website/static/img/screenshots/ is gone. The clip never carries
an autoplay attribute: playback starts from an effect, and only when the
visitor has not asked for reduced motion.
Add files to internal/migrations/sql/:
YYYYMMDDHHMMSS_description.up.sql
YYYYMMDDHHMMSS_description.down.sql
Use --bun:split directive to split multiple statements.
Client β DBBat (auth + grant check) β Target PostgreSQL
Client β DBBat (service-name lookup, O5LOGON proxy auth) β Target Oracle
Client β DBBat (caching_sha2_password / TLS termination) β Target MySQL/MariaDB
Client β DBBat (SCRAM-SHA-256 or PLAIN-over-TLS, authSource lookup) β Target MongoDB
Client β DBBat (TDS PRELOGIN + encapsulated TLS + LOGIN7, SQL auth) β Target SQL Server
The same auth + grant + query-logging pipeline runs across all five protocols (internal/proxy/shared).
- Every grant is an instance of a grant definition and carries no shape of
its own:
POST /api/v1/grantsassigns a definition to a user + database, and a grant request approval materializes the same thing. The grant row holds who/where/when, revocation andpriority; everything below lives on the definition and is read through accessors onstore.AccessGrant. - Time-windowed grants (
starts_at,expires_at; the length is the definition'sduration_seconds) - Controls:
read_only,block_copy,block_ddl(combinable; empty = full write) - Optional quotas:
max_query_counts,max_bytes_transferred. One budget per grant across all its live sessions:cache.UsageRegistry(viashared.RegisterGrantUsage,shared.QuotaUsage,LimitGuard.WithUsage) sums the grant's sessions on this replica over a store baseline that excludes them; the heartbeat re-reads that baseline everystore.GrantUsageRefreshInterval(5 s), which is the cross-replica lag - Two kinds of group, never a bare "group":
user_groupsname sets of people,server_groupsname sets of database servers. A definition scopes on both βuser_group_uids(who may request it),server_group_uids(which databases it covers),approver_user_group_uids(who may resolve its holds). Empty on either axis means "everyone" / "every database". The pre-rename field namesgroup_uids/approver_group_uidsare removed outright and are now a 400, same as the per-databasedatabase_uids. - Grants bind to a server group, not to a database. A grant issued from a
scoped definition binds to whichever of its groups holds the target database
and then covers that group's current membership, and only that; the anchor
database_idis what an unbound grant covers and what a bound one falls back to if its group is deleted (ON DELETE SET NULLβ narrows, never widens). Membership is live and never snapshotted: adding a server to a group immediately widens every live grant bound to it, sessions already running included, and removing one narrows them β including the anchor. That is the first of two deliberate exceptions to the immutable-versioning rule below (the second is the approver lists), accepted because group membership is operational data β the admin UI warns about the blast radius at the point of edit. Onemax_query_countsand onemax_bytes_transferredbudget is consumed across the whole group, andpriorityranks group-bound grants against each other on the databases where their groups overlap. The auth path is one function,store.GetActiveGrant, which all five protocols share. - Optional per-statement time limit (
statement_timeout_secondson the definition). Three states, and0is not "omitted":NULLinherits the instance-wide default,0means explicitly no limit, overriding that default (the escape hatch a dump or ETL definition needs), and a positive value is the limit in seconds. See "Per-statement time limits" below - Optional approval holds: RE2 patterns on the definition that suspend a
matching statement mid-flight until a second human approves it. Self-approval
is always rejected; a hold has no timeout. Off by default
(
DBB_APPROVAL_ENABLED) β seedocs/approvals.md - Two approver kinds live on the fleet, not on the policy.
serversandserver_groupseach carryaccess_approver_user_group_uids(who may approve/deny grant requests for that database) andquery_approver_user_group_uids(who may release approval holds on statements against it). Neither implies the other β an org wanting overlap lists the same user group in both. Resolution is a fallback chain, in one place (store.ResolveServerApproverGroupsByServers, of which the per-serverstore.ResolveServerApproverGroupsis a thin wrapper β a second, SQL-shaped implementation of the chain is exactly the drift that would be an authorization bug): for a grant request, the server's list β the union of its server groups' lists β admins; for a hold, the definition'sapprover_user_group_uids(which wins outright when non-empty) β the server's β its groups' union β admins. Empty everywhere = admin-only = exactly the pre-feature behaviour. Self-approval is refused on every path, including both Slack transports. Each pending item reportsapprover_rolefor the caller (admin/definition_approver/server_approver/ empty) so the UI can say which hat they wear. The two listings (GET /api/v1/grant-requestsfor a non-admin,GET /api/v1/queries/pending) resolve the whole page in a fixed number of queries rather than walking the chain twice per row β same chain, same answers, asked once - Approver lists are live, never snapshotted: they are read at decision time, so an edit β or moving a server between groups β immediately changes who may decide requests already filed and statements already parked. That is the second deliberate exception to the immutable-versioning rule, alongside live server-group membership above, and for the same reason: a departed lead's replacement has to be effective now
- Definitions are immutably versioned: an edit archives the current row
(
archived_at) and inserts a successor sharing itslineage_uid, so a live grant's behaviour never changes under it β except for the scope it inherits from live server-group membership and the approvers it resolves off the server/server-group chain, both above. A slug resolves to the live row. Deactivating a definition is different from that archival β it withdraws the whole lineage and fails closed at auth time; hard deletion is refused (409) while anything references it. - A server row is editable; its protocol is not.
PUT /servers/{uid}takes host, port, database/service name, credentials,ssl_mode,listable, the tunnel and the name, and the admin UI'sservers/$uidpage offers all of them (the name in its own section, for its own warning and confirmation). Editing does not re-issue anything: every grant already covering the row reaches the new target on the next connect, sessions already open stay on the upstream they dialed, andGET /servers/{uid}/referencesis what the page counts that with β live grants (anchored or group-bound, under the auth path's own liveness predicate) and the server groups carrying the row. Same trade as live server-group membership, same answer: warn at the point of edit rather than make the row immutable.protocolis the exception, refused 409 once any grant or connection references the row β it is the one edit that makes the row a different server, and the history under its uid would silently re-label itself. A pristine row may still change protocol, so a create-dialog typo stays a one-click fix.redactUpdateForAuditreplaces the secrets with "changed" markers and the UI sends only the fields that actually moved, sodatabase.updatedreads as the edit that was made.
A grant bounds time (expires_at), volume (max_query_counts,
max_bytes_transferred) and shape (read_only, block_ddl, block_copy,
approval patterns). It also bounds a single statement's duration, which is
what stops one investigation session from saturating a production replica.
Resolution, per session at auth time: the grant definition's
statement_timeout_seconds when it has one (0 = no limit, overriding
everything below), otherwise the limits.statement_timeout store parameter
(Settings page), otherwise DBB_STATEMENT_TIMEOUT. One resolved value feeds
both layers, so they cannot disagree.
Layer 1 β the server-side setting, applied before the client is told it is
connected, at the same point the read-only pin is. It is not the enforcement;
it is how the client gets a real database error instead of a dropped socket. A
session that cannot be pinned fails, same rule as ErrUpstreamReadOnlyMode.
| Protocol | What is set | Notes |
|---|---|---|
| PostgreSQL | SET SESSION statement_timeout |
SQLSTATE 57014, session survives |
| MySQL | SET SESSION max_execution_time (ms) |
Covers SELECT only; the watchdog covers the rest |
| MariaDB | SET SESSION max_statement_time (s) |
Detected from the version banner β neither server accepts the other's name |
| MongoDB | maxTimeMS injected into each forwarded command |
No session knob exists. A client value at or below the limit is kept; a larger one (or 0) is clamped |
| Oracle | nothing | A statement time limit is a Resource Manager plan (DBA-level); CALL_TIMEOUT is an OCI client setting |
| SQL Server | nothing | The query timeout is a client concept |
Because the limit is hard, a statement that would unset or widen it is refused
with a clear error β PostgreSQL's SET/RESET statement_timeout and RESET ALL,
MySQL's SET max_execution_time / max_statement_time and an over-limit
/*+ MAX_EXECUTION_TIME(n) */ hint. The refusal runs through the same
validateStatement the grant controls do, so the simple and extended paths
cannot drift. SHOW statement_timeout stays allowed: reading the limit is the
opposite of bypassing it. On MongoDB an over-limit maxTimeMS is clamped, not
refused β it is an ordinary per-command option, not a SET.
Layer 2 β dbbat's watchdog, which is the actual enforcement. The per-session
LimitGuard carries a StatementClock marking when the oldest statement
still executing upstream was forwarded, and trips ErrStatementTimeout once
that passes limit + StatementTimeoutGrace (2s, a constant, not a setting). The
250ms poll means the kill lands within 2.25s of the limit. Time parked on an
approval hold does not count: the clock starts when the statement is actually
sent upstream, which a held statement has not been β and the server-side
settings agree by construction, having never seen it. The clock is kept honest
at every protocol boundary: PostgreSQL's extended protocol pops the pending
queue on all four Execute terminators (CommandComplete, ErrorResponse,
EmptyQueryResponse, PortalSuspended β a suspended portal is idle, not
executing) and, as a backstop, finishes at each ReadyForQuery any pending
entry whose batch the protocol has already closed (one RFQ answers one
forwarded Sync/simple Query, and the entry stamps the count it was queued
under), logging it as no completion message from upstream; on a termination,
the limit text lands on the oldest in-flight entry β the statement the
clock measured β and the others complete as aborted.
On a trip, in this order: cancel upstream, then close both sockets. Closing
alone is not enough β a PostgreSQL backend in a long sequential scan does not
notice a dead client until it next tries to send, and
client_connection_check_interval defaults to 0. Per protocol: PostgreSQL a
CancelRequest on a fresh connection through the same dial path (SSH /
Kubernetes tunnels included); MySQL KILL QUERY <upstream connection id>,
likewise on a fresh connection; SQL Server a TDS ATTENTION on the existing
connection; Oracle a break/reset marker exchange (unverified against a real
server β the socket close is the guarantee, see docs/oracle.md); MongoDB
nothing, because the injected maxTimeMS already is the cancel and killOp
needs privileges the proxied role usually lacks.
Every dbbat-initiated teardown is recorded rather than merely logged:
connections.termination_reason (statement_timeout, grant_expired,
quota_exceeded, grant_revoked, admin_terminated, instance_lost) written
in the same statement as disconnected_at, a chained connection.terminated
audit entry carrying the statement, the limit and the observed duration, a
connection stream event with state terminated, and the in-flight query row
completed with statement timeout: limit 30s, ran 32.1s, session terminated by dbbat. MCP agents get the same limit named in the tool error rather than an
opaque driver failure (docs/mcp.md). instance_lost is the odd one out β no
session wrote it, the crash reconcile did, so the column has no unexplained
NULLs on closed rows.
Ending one live session: POST /api/v1/connections/{uid}/terminate, admin
only, 202/404/409 (POST on a sub-path, never DELETE /connections/{uid} β
that reads as deleting the ledger row, which retention owns and the audit chain
protects). Terminating is not revoking: the grant is untouched and the user may
reconnect immediately.
The replica serving the API call is not necessarily the one serving the session
(connections.run_id says who is), so the request is a row β
terminate_requested_at / _by / terminate_reason, partial-indexed on
(run_id) β and every process polls for its own every
store.TerminationPollInterval (2s, on the instance-heartbeat goroutine). When
the API replica does own the session it signals cache.SessionRegistry
directly, so the local case stays instant. The registry is keyed by connection
uid, sits next to cache.RevocationRegistry, and its flag is attached to the
session's LimitGuard (WithTermination) exactly as revocation is β so
Check() returns ErrAdminTerminated and the existing onLimitViolation
teardown runs unchanged.
The poll has a second arm, and it fixes a bug rather than adding a feature.
DELETE /grants/{uid} only ever signalled the in-process RevocationRegistry,
so in a multi-replica deployment revoking a grant ended the sessions on the
replica that served the API call and left every other one running until it
expired (GetActiveGrant runs only at connect; LimitGuard compares
expires_at, never revoked_at). The second arm selects this run's live
sessions whose grant carries revoked_at, signals them through the same handle,
and records grant_revoked β the handle's reason is authoritative over the
sentinel, which is what keeps the two apart.
- User passwords: Argon2id hashed
- Database credentials: AES-256-GCM encrypted (AAD-bound to the database UID)
- API keys: Argon2id-hashed like passwords (
crypto.HashPassword), prefixdbb_with only the first 8 characters kept in clear askey_prefixfor lookup β a leaked store yields no usable key. The one transient exception: a freshly minted key sits AES-256-GCM-encrypted in a pending device-authorization row (crypto.DeviceAuthAAD) until the device polls for it. Keys cannot create/revoke other keys - Default admin:
admin/admin(must change on first login) - Roles can follow the directory: with
DBB_OIDC_ROLE_MAPPINGset, an OIDC login resolves the user's roles from the ID token's groups claim on every sign-in (internal/api/oauth_roles.go), so a demotion needs no human. The mapping owns only the roles it names β a role granted by hand in the UI is never revoked by a login β the default role is the floor, and the last admin is retained exactly asPATCH /users/:uidrefuses to strip it. Every change writes auser.roles_syncedaudit entry - Tamper-evident audit trail: every
audit_logentry, everyqueriesrow and everyquery_rowsrow carries an HMAC over its content plus the previous record's MAC, keyed by an HKDF subkey ofDBB_KEYthat is never stored in the database.audit_logis one chain;queriesis one chain per connection;query_rowsis one chain per query, positioned byrow_numberβ an ordering, not a dense sequence, because dropped or unencodable rows leave gaps. Each scope is chosen soDBB_RETENTION_QUERIES_DELETE_AFTERnever severs a chain by deleting what it is meant to delete, and each stamps its final head when it finishes: the session's on the connection row at close (query_chain_mac), the capture's on the query row at the flush barrier (row_chain_mac). A session whose process crashed is sealed by the reconcile instead, from the stored statements, in the same transaction that writesdisconnected_atβ so it seals whatever survived at reconcile time, not at the crash. A session that is still open is sealed by a third writer,Store.RefreshOpenChainStamps, which rides the reclaim tick and re-stamps the sessions this run owns (run_id = s.runID, guarded bydisconnected_at IS NULLso it can never overwrite a close's final stamp). Its stamp is therefore a prefix, not a head, and verification follows: while a session is open the stamp is checked against the statement at thechain_seqit names β a stamp that is merely behind is not a break, one that outruns the survivors is β and it goes back to exact the moment the session closes. So a live session's tail is protected up to the last sweep (bounded byInstanceReclaimInterval, not by how long the session lasts); statements newer than that sweep are still not. Each stamp also has a sealed copy inaudit_logβ the session'sconnection.closedentry forquery_chain_mac, a batchedquery.rows_sealedentry (β€1s, β€500 seals) forrow_chain_macβ and verification compares the two, so clearing a stamp together with every record it protects is a break rather than a session that logged nothing (internal/store/chain_sealed.go). Both stamps are keyed MACs over the head, not copies of it: a verbatim head is readable out of the table it came from, so copying it after a trailing deletion would need no key.query_chain_macadditionally carries a format version (query_chain_stamp_version) inside its MAC β0is the unkeyed stamp an early revision of the feature wrote, which cannot be re-sealed because the key never enters the database; sealing the version is what stops a1row from being relabelled0to get the weaker rule. A0row is a break ("its tail cannot be verified"), not a weaker pass, with no opt-out anywhere β CLI or REST: tolerating it was a standing downgrade path, since replacing a sealed stamp with a raw head MAC and version0needs no key. 0.24 ships the chain, the keyed stamp and the version column together, so only a store written by a pre-0.24 development build can hold a0row, and such a store stays unverifiable. The query walk enumerates stamped connections, not only connections found inqueries, so a session whose statements are deleted in full is judged instead of skipped (deleting all but one was always caught). Zero survivors under a keyed stamp is a break unless retention can account for it: the store is told its ownDBB_RETENTION_QUERIES_DELETE_AFTER(store.Options.QueryRetention) and excuses only a session that connected before the cutoff, since every statement runs at or afterconnected_atβ with retention off, the default, nothing is excused, and an excused session is counted as emptied by retention (chains_emptied_by_retention), a count kept disjoint fromchains_with_retention_truncated_prefix("lost its oldest statements, some survive") because aDBB_RETENTION_CONNECTIONS_DELETE_AFTERlonger than the statement window puts every closed session between the two windows in the emptied state by design, and one number would bury the other. The same rule, exported asstore.StatementsPastRetention, is what feedsstatements_retainedonGET /api/v1/connections/{uid}so the UI can say "past retention" instead of "no queries". Raising or disabling retention moves that cutoff backwards, so previously reaped sessions can start reading as breaks; lowering it never does. Verify withdbbat audit verify [--queries|--rows], or over REST with the admin-onlyGET /api/v1/audit/verify,GET /api/v1/audit/verify/queriesandGET /api/v1/audit/verify/rows(the last narrows with?connection=or?query=, which cannot be combined) β which return counts, the head MAC and the first break, never the key or a record's content, and are cached because a walk is O(rows). The endpoint is not equivalent to the CLI: it is served by the process under audit. Seedocs/audit-chain.md - Sessions are evidenced, not chained.
connectionscarries no MAC, and deliberately: it is a table retention deletes from, so a chain over it would report a truncated prefix after every sweep. Instead every session writes two chainedaudit_logentries βconnection.openedatCreateConnection,connection.closedfrom whichever writer closes it (CloseConnectionor the reconcile, recorded asclosed_by) β carrying the row's immutable identity (connection uid, user, database, source IP,connected_at, instance/run, grant) plus, on open, the target it actually reached βtarget_host,target_port,target_database(the SERVICE_NAME on Oracle), read from theserversrow inrecordConnectionOpenedso no proxy call site can forget it β and, on close,disconnected_atand the session's sealedquery_chain_mac. The target is there becausedatabase_idnames an editable row: without it the ledger would stop saying where a past session went the moment an admin corrected a host, which is precisely the property the old UI-level immutability was standing in for. It is immutable for the session, never for the row. The mutable counters stay out. That is what makesDELETE FROM connections(which cascades toqueriesandquery_rows) leave evidence β but only by comparison: no walk reports it, and every column of a connection row,connected_atincluded, is still unsealed. The write is never fatal to a session and never joins the caller's transaction (the chain append owns its own, with a retry a nested transaction could not run); the reconcile batches its entries throughStore.LogAuditEvents. Volume being what it is, the two event types are excluded from an unfilteredGET /api/v1/auditand reachable with?event_type=β seeinternal/store/connection_audit.go
- OpenAPI spec:
internal/api/openapi.yml - Swagger UI:
GET /api/docs - All endpoints versioned under
/api/v1/