Skip to content

Latest commit

Β 

History

History
696 lines (623 loc) Β· 60.4 KB

CLAUDE.md

File metadata and controls

696 lines (623 loc) Β· 60.4 KB

DBBat - Database Observability Proxy

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.

Semantic Versioning

This project uses Conventional Commits and release-please for automated releases.

PR Title Format

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 endpoint
  • fix(proxy): handle connection timeout gracefully
  • chore(deps): update go dependencies
  • feat!: redesign authentication flow (breaking change)

Technical Stack

  • Language: Go
  • Storage: PostgreSQL
  • ORM: uptrace/bun with 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) β€” see docs/mysql.md
    • MongoDB wire protocol (hand-rolled OP_MSG; BSON via go.mongodb.org/mongo-driver/v2) β€” see docs/mongodb.md
    • Microsoft SQL Server TDS (hand-rolled) β€” see docs/mssql.md
  • Tunnels (via_uid): a server row with protocol ssh or kubernetes is a dial path, never a grantable target. SSH opens a direct-tcpip channel to any host:port; Kubernetes opens a pods/portforward stream to a pod's own port (host = <pod> or svc/<name>, port = container port) β€” a database merely routable from the cluster network is out of scope. See docs/kubernetes.md
  • API: gin-gonic/gin with 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, queries and query_rows are HMAC-chained with a key HKDF-derived from DBB_KEY; dbbat audit verify walks the chains (docs/audit-chain.md)
  • MCP (AI agents): Streamable-HTTP endpoint at /api/v1/mcp via github.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)

Project Structure

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

Make Commands

# 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 artifacts

Development Sessions

Never 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

Follow-up Tasks β†’ specs/todos/

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). NN is a two-digit execution order within that date, so a plain ls of specs/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 last NN of 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.

CLI Commands

./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

Environment Variables

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.

Testing

Unit Tests

make test  # Uses testcontainers-go for PostgreSQL

Protocol Integration Tests

Behind //go:build integration, so make test neither compiles nor runs them.

make test-integration-mongodb   # and -mysql, -postgresql, -mssql, plus test-e2e-oracle

make 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.

E2E Tests

make test-e2e  # Builds app, starts server in test mode, runs Playwright

⚠️ Locally, never run make 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

Website showcase media (make showcase)

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 pull

scripts/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.

Creating Migrations

Add files to internal/migrations/sql/:

YYYYMMDDHHMMSS_description.up.sql
YYYYMMDDHHMMSS_description.down.sql

Use --bun:split directive to split multiple statements.

Core Concepts

Connection Flow

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).

Access Control

  • Every grant is an instance of a grant definition and carries no shape of its own: POST /api/v1/grants assigns a definition to a user + database, and a grant request approval materializes the same thing. The grant row holds who/where/when, revocation and priority; everything below lives on the definition and is read through accessors on store.AccessGrant.
  • Time-windowed grants (starts_at, expires_at; the length is the definition's duration_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 (via shared.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 every store.GrantUsageRefreshInterval (5 s), which is the cross-replica lag
  • Two kinds of group, never a bare "group": user_groups name sets of people, server_groups name 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 names group_uids / approver_group_uids are removed outright and are now a 400, same as the per-database database_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_id is 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. One max_query_counts and one max_bytes_transferred budget is consumed across the whole group, and priority ranks 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_seconds on the definition). Three states, and 0 is not "omitted": NULL inherits the instance-wide default, 0 means 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) β€” see docs/approvals.md
  • Two approver kinds live on the fleet, not on the policy. servers and server_groups each carry access_approver_user_group_uids (who may approve/deny grant requests for that database) and query_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-server store.ResolveServerApproverGroups is 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's approver_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 reports approver_role for the caller (admin / definition_approver / server_approver / empty) so the UI can say which hat they wear. The two listings (GET /api/v1/grant-requests for 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 its lineage_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's servers/$uid page 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, and GET /servers/{uid}/references is 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. protocol is 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. redactUpdateForAudit replaces the secrets with "changed" markers and the UI sends only the fields that actually moved, so database.updated reads as the edit that was made.

Per-statement time limits

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.

Security

  • User passwords: Argon2id hashed
  • Database credentials: AES-256-GCM encrypted (AAD-bound to the database UID)
  • API keys: Argon2id-hashed like passwords (crypto.HashPassword), prefix dbb_ with only the first 8 characters kept in clear as key_prefix for 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_MAPPING set, 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 as PATCH /users/:uid refuses to strip it. Every change writes a user.roles_synced audit entry
  • Tamper-evident audit trail: every audit_log entry, every queries row and every query_rows row carries an HMAC over its content plus the previous record's MAC, keyed by an HKDF subkey of DBB_KEY that is never stored in the database. audit_log is one chain; queries is one chain per connection; query_rows is one chain per query, positioned by row_number β€” an ordering, not a dense sequence, because dropped or unencodable rows leave gaps. Each scope is chosen so DBB_RETENTION_QUERIES_DELETE_AFTER never 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 writes disconnected_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 by disconnected_at IS NULL so 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 the chain_seq it 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 by InstanceReclaimInterval, not by how long the session lasts); statements newer than that sweep are still not. Each stamp also has a sealed copy in audit_log β€” the session's connection.closed entry for query_chain_mac, a batched query.rows_sealed entry (≀1s, ≀500 seals) for row_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_mac additionally carries a format version (query_chain_stamp_version) inside its MAC β€” 0 is 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 a 1 row from being relabelled 0 to get the weaker rule. A 0 row 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 version 0 needs 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 a 0 row, and such a store stays unverifiable. The query walk enumerates stamped connections, not only connections found in queries, 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 own DBB_RETENTION_QUERIES_DELETE_AFTER (store.Options.QueryRetention) and excuses only a session that connected before the cutoff, since every statement runs at or after connected_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 from chains_with_retention_truncated_prefix ("lost its oldest statements, some survive") because a DBB_RETENTION_CONNECTIONS_DELETE_AFTER longer 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 as store.StatementsPastRetention, is what feeds statements_retained on GET /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 with dbbat audit verify [--queries|--rows], or over REST with the admin-only GET /api/v1/audit/verify, GET /api/v1/audit/verify/queries and GET /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. See docs/audit-chain.md
  • Sessions are evidenced, not chained. connections carries 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 chained audit_log entries β€” connection.opened at CreateConnection, connection.closed from whichever writer closes it (CloseConnection or the reconcile, recorded as closed_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 the servers row in recordConnectionOpened so no proxy call site can forget it β€” and, on close, disconnected_at and the session's sealed query_chain_mac. The target is there because database_id names 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 makes DELETE FROM connections (which cascades to queries and query_rows) leave evidence β€” but only by comparison: no walk reports it, and every column of a connection row, connected_at included, 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 through Store.LogAuditEvents. Volume being what it is, the two event types are excluded from an unfiltered GET /api/v1/audit and reachable with ?event_type= β€” see internal/store/connection_audit.go

API Documentation

  • OpenAPI spec: internal/api/openapi.yml
  • Swagger UI: GET /api/docs
  • All endpoints versioned under /api/v1/