Skip to main content

12 — Dynamic permissions + multi-DB targets

Status: spec. Tracks issue #46. Locks the surface before #47–#60 land code.

Why​

The shipped design (see 06-permissions, 08-config) puts all grants in YAML in git, reviewed by PR, hot-reloaded on SIGHUP. That works for one install run by the team that owns the repo. It does not work for external deployers who never touch our git history and need their own audit trail for who-granted-what.

Sebby's direction (2026-06-10 / 2026-06-11): keep YAML as the simple path. Add a second path — an SSO-gated admin API writing into the state DB — for installs that need runtime permissions management. No UI; that non-negotiable stands.

Same direction also asks for multi-database query targets (Postgres + MongoDB initially; Redis followed), dispatched by db_type on the grant.

What changes​

AreaBeforeAfter
Permission sourceYAML onlyYAML or DB-backed, via the same authz engine
Permission write auditGit history (review trail in the PR)Git history or synchronous permissions_audit row
Permission managementPRPR or POST /admin/v1/* (SSO-gated to an admin group)
Query targetPostgres onlyPostgres, MongoDB or Redis, dispatched on db_type
Permission storage backendn/aPostgres first; MySQL as a second backend behind the same trait

Two sources, one engine​

A request (user, groups, server, db, action) resolves grants from:

  1. YAML — same shape as today (06-permissions).
  2. DB — rows in the state DB, loaded by (user_id, database_id).

The resolver concatenates both grant sets and hands them to the existing constraint-merge engine. Most-restrictive value wins, unchanged — see 06-permissions §Evaluation. YAML and DB are interchangeable inputs. There is no priority order between them; the merge is symmetric.

┌──────────────────┐
│ YAML grants │
└────────┬─────────┘
│
(user, groups, ▼
server, db, action) ──▶ ┌──────────┐ ──▶ ┌──────────────────┐ ──▶ allow + constraints
│ resolver │ │ constraint-merge │
└──────────┘ └──────────────────┘
▲
┌────────┴─────────┐
│ DB grants │
└──────────────────┘

Why merge symmetrically (not "DB overrides YAML")​

If DB overrides YAML, an attacker who compromises the admin API can widen a grant — the YAML's intent is silently lost. With symmetric merge under most-restrictive, the worst an admin-API attacker can do is narrow access (denial of service) or add grants the YAML didn't have. The YAML still floors what its existing grants allow. Defense in depth.

The same logic justifies not having a priority field on grants. A grant either applies or it doesn't; the merge step picks the safest combination. No precedence game.

Storage backends​

Postgres first. MySQL is a second backend behind the same PermissionsRepo trait. No MongoDB for the permissions store — it'd add a third schema dialect for no gain (we already have pg, are adding mysql, and mongo's flexible schema is a liability for an authz store where the schema is the contract).

Config switch — a top-level permissions_store: block beside permissions: (the YAML grants, which always apply):

permissions_store:
driver: pg # pg | mysql | none
driverGrants come fromAdmin API
absent / pgYAML and the permissions_* tables in the state DB (the default — an absent block still reads the store)allowed
mysqlYAML and a MySQL store; DSN from the PERMISSIONS_DB_DSN env var, never YAMLrefused at boot
noneYAML only — the store is never read: no grant query, no LISTEN connection, the resolver cache answers emptyrefused at boot (nothing to edit)

The driver is fixed at boot; a reload that changes it is refused. driver: none is the explicit YAML-only mode the dogfood install uses.

The MySQL store is read-only-provisioned. The gateway only reads it; the operator fills it with their own tooling. Boot rejects driver: mysql together with admin.enabled: true, so there is no audited write path to MySQL and none is planned — the permissions_audit table its 0002 migration created stays unwritten. With no admin commit there is no cross-replica notification either: a change made in MySQL is honoured within PERMISSIONS_CACHE_TTL_SECONDS (clamped to ≤ 300 s). Identity and routing columns (user_sub, server, db_name) use the case- and accent-sensitive utf8mb4_0900_as_cs collation (migrations-mysql/0004), so Alice and alice are two subjects, as they are in Postgres.

db_type names the target engine a permissions_databases row registers — postgres, mysql, mongo or redis (mongo added by migrations/0013 / migrations-mysql/0005, redis by migrations/0021_permissions_db_type_redis.sql / migrations-mysql/0006_db_type_redis.sql) — not the store the row lives in. A YugabyteDB target registers as postgres.

permissions_audit table​

Mirrors the query audit invariant from non-negotiable #4: synchronous, write fails → request fails. No best-effort audit, ever, including for permissions changes.

ColumnTypeNotes
idbigserial PK
tstimestamptzserver time
actor_iduuidthe acting admin's permissions_users.id; deliberately not a foreign key, so an append-only audit row outlives any cleanup of the row it names
actor_emailtextdenormalized for forensics; mirrors query audit
actiontextcreate | update | delete
target_typetextuser | database | grant
target_iduuidrow id of the changed entity
beforejsonbfull row before, or null for create
afterjsonbfull row after, or null for delete
request_idtextmatches the request id in 07-logging-retention

Never logged: target-DB connection strings, role passwords, role secrets. before/after redact any field that could carry a secret — same rule as query audit (non-negotiable #1).

Indexes: (ts), (actor_id, ts), (target_type, target_id, ts).

Retention: the hourly audit pruner deletes permissions_audit rows whose ts is older than AUDIT_RETENTION_DAYS (default 90), with the same cutoff, batching and advisory lock as query audit (07 §Retention pruning). A change trail needed longer than that must be exported before it ages out. The same run hard-deletes grants revoked, and users and databases soft-deleted, longer ago than the same cutoff (grants first; a parent a grant still references is skipped with a WARN), so a deleted subject's email and grants leave the state DB on that horizon; live rows are never touched. The MySQL store is never written by the gateway and is not pruned.

Admin API​

Surface: /admin/v1/{users,databases,grants} plus the read routes explain, permissions/{export,diff}, audit/calls and openapi.json. SSO-gated to a configured admin group. No UI ever.

admin:
enabled: true # default false
group: db-mcp-gateway-admins # SSO group claim required

If admin.enabled is false, the entire /admin/* route is 404. Belt-and-suspenders for installs that want YAML-only.

Endpoints​

All endpoints require a valid SSO JWT with the admin group claim. Every write commits a permissions_audit row before the response goes out.

List endpoints are paginated. GET /admin/v1/{users,databases,grants} accept ?limit= and ?offset=. limit defaults to 100 and is clamped to a maximum of 1000 — an oversized ask is clamped, not rejected, matching how the gateway treats every other caller-supplied bound. A non-numeric value is a client mistake and returns invalid_request (400). Ordering is stable and total (created_at, id for users and grants; (server, db_name) for databases), so a walk over a stable dataset returns rows in deterministic order and visits each one exactly once. Concurrent inserts, deletes, or updates between page requests can shift rows in or out of a later offset window — this is offset-pagination semantics, not a snapshot. Callers that need snapshot guarantees should either walk the pages inside a single admin batch (no writes in-flight) or fall back to a full re-read on the tail. Without pagination an install's entire permissions table loaded into memory and serialized into one response.

Pagination deliberately does not apply to the resolver's read: authz::loader loads a subject's complete live grant set in one query (live user ⋈ live grants ⟕ live databases, keyed on user_sub), and a windowed read would silently drop authority. A specific grant whose database is soft-deleted drops inside that query.

MethodPathPurpose
POST/admin/v1/usersRegister a user (SSO subject + email + cached groups). A service:* subject is rejected (400) — a service token's authority is its YAML group only (14)
GET/admin/v1/usersList users
GET/admin/v1/users/:idFetch one user
PATCH/admin/v1/users/:idUpdate (e.g. refresh group cache)
DELETE/admin/v1/users/:idSoft-delete; its live grants are revoked in the same transaction, one delete audit row per grant
POST/admin/v1/users/:id/revoke-sessionsRevoke every live session and delete every refresh chain of the user's user_sub; their bearers are 401 on the next call. One permissions_audit row (update on the user, payload {user_sub, live_sessions, refresh_tokens} before → zeros after) in the revoke's transaction; session-cache tombstones only after commit. Takes the per-subject advisory lock shared with code redemption, refresh rotation and logout, so a rotation in flight is waited out and its new session and refresh token are revoked too. Returns {revoked_sessions, revoked_refresh_tokens}
POST/admin/v1/databasesRegister a logical (server, db_name, db_type)
GET/admin/v1/databasesList
GET/admin/v1/databases/:idFetch one
PATCH/admin/v1/databases/:idUpdate (rename, change type — both audited)
DELETE/admin/v1/databases/:idSoft-delete; its specific grants are revoked in the same transaction, one delete audit row per grant (wildcards name the server and stay)
POST/admin/v1/grantsCreate a grant
GET/admin/v1/grantsList, filterable by user / database
GET/admin/v1/grants/:idFetch one
PATCH/admin/v1/grants/:idUpdate action, constraints and/or expires_at — constraints merge per key (see §PATCH merges per key); expires_at: null clears the expiry
DELETE/admin/v1/grants/:idRevoke
POST/admin/v1/grants/batchApply 1–500 grant upsert / delete changes in one transaction, all or nothing, one permissions_audit row per applied change (§Batch apply)
POST/admin/v1/explainWhy a (user | group, server, database, action) is allowed or denied: the matching grants and the merged constraints (§Explain)
GET/admin/v1/permissions/exportEffective permissions, YAML ∪ DB, as one document
POST/admin/v1/permissions/diffDiff a desired document (the export's shape) against the effective one — read-only
GET/admin/v1/audit/callsaudit_calls rows as NDJSON, filtered; statement text only with include_sql=true
GET/admin/v1/openapi.jsonOpenAPI 3.1 document of this surface, held equal to the mounted routes by a test (src/transport/admin/openapi_tests.rs)

Reads that disclose grants or audit history are audited too. explain, permissions/export, permissions/diff and audit/calls each write one audit_calls row (tool = admin.explain / admin.permissions_export / admin.permissions_diff / admin.audit_calls, the admin as user_sub, outcome: success; for audit/calls the row's params holds the requested filters and include_sql, so a read that disclosed statements and bound values is told apart from a metadata-only one) before the response goes out; if that write fails the read is refused with audit_unavailable (503) and nothing is returned (non-negotiable #4). A request rejected as invalid reads nothing and writes no row. The plain CRUD GETs are not audited, as before.

What the API never returns​

  • Connection strings.
  • Role passwords or secrets.
  • Other users' SSO tokens or session state.
  • Audit rows for other organizations (single-tenant assumption — see 02-architecture).

The databases endpoints register a logical db reference; the connection string for that db still lives in YAML/secrets and is loaded by the gateway at boot. The admin API can't accept a DSN field. This keeps non-negotiable #1 intact even if the admin DB is compromised: there is no credential on the DB side to leak.

Request shapes​

POST /admin/v1/grants:

{
"user_id": "uuid-of-user",
"database_id": "uuid-of-database",
"db_name_wildcard": false,
"action": "query_read",
"constraints": {
"row_limit": 1000,
"statement_timeout_ms": 5000,
"require_reason": true
}
}

db_name_wildcard: true + database_id: null + server is the db_name = "*" form (see §Wildcard). server must name a server the gateway config declares; "*" or an undeclared name is invalid_request (400).

expires_at (optional, RFC 3339) on POST /admin/v1/grants and on a batch upsert must be in the future; omit it for a grant that never expires. Stored in permissions_grants.expires_at (nullable; pg 0023 as TIMESTAMPTZ, mysql 0007 then 0008 as UTC DATETIME(6), so both stores accept any year — a TIMESTAMP would stop at 2038). From that instant on — the instant itself included — evaluation ignores the grant; the row stays live (not revoked), so GET /admin/v1/grants keeps listing it with expired: true until an admin deletes it. The check runs at evaluation time, not load time, so a cached grant set cannot outlive an expiry. YAML grants have no expiry.

Explain​

POST /admin/v1/explain takes exactly one of user (an SSO subject) or group, plus server, database, action. For a user, the group claims assumed are groups from the body or, absent, the groups cached on the user's permissions_users row; the user's live DB grants are loaded with the resolver's own query. The answer comes from authz::matching_grants + authz::decide — the functions every tool call's evaluate_effective runs — so it is the decision a real call would get: decision (allow / deny), merged constraints, every matched grant with its source (yaml with its subject, or db with grant_id), expired DB grants that would have matched, and target_declared (whether the config declares that database). A group question sees no DB grant and no user: block. Explain never reads a live session, so it is a simulation for the groups it assumed: groups_source is stored (the groups on the user's permissions_users row, as POST /admin/v1/users, PATCH /admin/v1/users/:id or an admin's first audited write last set them — not necessarily the user's current SSO claims), none (no permissions_users row, no groups), assumed (from the body) or group, and an SSO session whose current claims differ from the stored ones can be decided differently.

Batch apply​

POST /admin/v1/grants/batch body: {"changes": [{"op": "upsert", …CreateGrant fields…}, {"op": "delete", "id": …}]}. Every change is validated before the transaction opens; then one audited transaction applies them in order. An upsert is keyed by (user_id, target, action): the oldest live grant with that key is updated in place (constraints and expires_at replaced; audited update), otherwise one is created (audited create); an upsert that would change nothing writes and audits nothing (op: unchanged). Any failure — a validation error (message prefixed changes[i]: ), a dead reference, a missing delete target, an audit write — rolls back every change. A batch touching one user invalidates that user's cached grants; several, every cache entry. Its body may be up to 1 MiB — 500 changes outgrow the 64 KiB every other admin body gets, save permissions/diff's 16 MiB (500 maximal upserts, pretty-printed, take about 310 KiB).

Export and diff​

The export lists every YAML grant (source: yaml, its subject {group} or {user}) then every live DB grant (source: db, grant_id, subject: {user: <sub>}, expires_at / expired when set). A profile appears as its name; its constraints are already folded in. POST /admin/v1/permissions/diff accepts that document back (export-only keys are ignored) and compares by (subject, server, database, action): add (desired only), remove (effective only), change (both, bodies differ), unchanged (count). It changes nothing — its one write is its own audit_calls row (admin.permissions_diff), committed before the response like every audited admin read; apply a diff with grants/batch or a YAML PR. Export and diff share one size contract: diff takes a body of up to 16 MiB (grants/batch takes 1 MiB; the other admin routes keep 64 KiB), whatever its grant count, so an export — unedited or edited — posts back while it fits the body limit; a store whose export passes 16 MiB needs a scoped comparison, not offered yet.

Audit stream​

GET /admin/v1/audit/calls filters on user (user_sub or user_email), server, db, tool, outcome (a spec 03 code; unknown → 400), since (inclusive) / until (exclusive), newest first, limit default 1000, clamped to 1–10 000; an unknown parameter is 400. Each line is one JSON object; sql / sql_truncated / params appear only with include_sql=true (still admin-only). The read's own audit row commits before the first byte; an error after streaming began ends the body with one {"error": …} line. Rows are read in keyset batches of up to 200 rows or 1 MiB of lines plus one row (each query reads a candidate window that starts at 16 rows and grows to twice what the previous batch sent, so the state DB sizes about what it returns; the query itself stops after the row that crosses 1 MiB, sizing each row by an upper bound on its JSON line read from stored lengths — text counted at its worst-case escaping, params and groups at their text form — so the state DB sends nothing the next batch re-reads and compressible values cannot inflate a batch), and each batch's state-DB connection is back in the pool before its lines are sent, so a client that stops reading holds no connection the audit write path needs.

Validation + error semantics​

The grants handlers validate at the API layer before the DB CHECKs would catch it, so client-correctable mistakes surface as stable invalid_request (400) rather than internal (500):

RuleTriggerResponse
XOR targetboth, neither, or mismatched database_id / (server, db_name_wildcard: true)invalid_request (400) at handler, never reaches DB CHECK
Action parseunknown action stringinvalid_request (400) before any SQL runs
Dead referenceuser_id or database_id missing or soft-deleted — checked by the insert itself (INSERT … SELECT … WHERE deleted_at IS NULL, both rows held FOR SHARE until commit)invalid_request (400), stable invalid grant reference message; DB error text never echoed (non-negotiable #1)
Wildcard serverserver is "*" or not declared in configinvalid_request (400)
Past expiryexpires_at at or before now on POST, PATCH or a batch upsertinvalid_request (400); nothing written
Zero boundconstraints.row_limit or constraints.statement_timeout_ms is 0 on POST, or set to 0 by PATCH (a zero would disable the bound, not tighten it)invalid_request (400); nothing written
Body too largea body past its route's byte bound: 1 MiB for grants/batch, 16 MiB for permissions/diff, 64 KiB elsewherepayload_too_large (413); nothing read or written
Stale preconditionPATCH expected_updated_at differs from the locked row's updated_atconflict (409); nothing written
Deadlock / serialization abort (40P01 / 40001)concurrent admin writes Postgres had to abortconflict (409); safe to retry
CHECK violation (23514)belt-and-suspenders for a future migration adding a CHECK the handler doesn't pre-validateinvalid_request (400)
UNIQUE violation (23505)on /databases: registering a (server, db_name) pair that already exists, or PATCHing one onto anotherinvalid_request (400), message names the pair from the caller's own input; DB error text never echoed
Anything elsepool exhaustion, encoder bug, audit failureinternal (500), body carries request_id only; underlying error stays in gateway logs

The (server, db_name) UNIQUE index is partial (WHERE deleted_at IS NULL), so a soft-deleted pair does not occupy it — the same pair can be registered again after a DELETE.

Locked writes​

Every admin mutation runs one shape (src/transport/admin/audited_tx.rs): begin → lock the acting admin's permissions_users row, inserting it from the session snapshot only if absent (ON CONFLICT DO NOTHING, then SELECT … FOR UPDATE) → lock the target row (SELECT … FOR UPDATE) → mutate → write permissions_audit → queue NOTIFY → commit → invalidate this replica's cache. Locking the actor row first gives every admin write one lock order; a mutation of the actor's own user row skips the actor step (that row plays both parts). The actor step never rewrites an existing row: an unaudited email/groups refresh there would break that row's audit chain and bump its updated_at under another admin's precondition (a spurious 409). Because the target is locked before before is read, concurrent writes serialise and the audit chain is continuous: after[n] == before[n+1]. PATCH bodies may carry expected_updated_at (the value last read); a mismatch is 409.

PATCH merges per key​

constraints on PATCH /admin/v1/grants/:id is a per-key patch onto the stored object, never a replacement: an absent key keeps its value, null clears it (require_reason clears to false), a value sets it. A PATCH naming only row_limit therefore keeps require_reason and statement_timeout_ms — no admin call can loosen a constraint it did not name. Proven by src/authz/patch_proptests.rs.

PATCH cannot change the target​

PATCH /admin/v1/grants/:id accepts action, constraints, expires_at and expected_updated_at only. The XOR target (Specific vs Wildcard) is the grant's identity — re-targeting is DELETE + POST. Bodies carrying database_id / server / db_name_wildcard are rejected at the parse layer (deny_unknown_fields → 400).

Cache invalidation​

The resolver caches each subject's DB grant set (PermissionsCache, keyed on user_sub). A cold miss is one store query; concurrent misses for one subject share it (single flight); a load overtaken by an invalidation of that subject is not cached (per-subject revision) and is retried at most three times; expired idle entries are swept on insert.

An admin commit both drops this replica's affected entries and, inside the same transaction, NOTIFYs channel dbmcp_permissions; every replica's listener applies it on commit and never on rollback. The listener keeps running through the shutdown drain, so requests still in flight on a stopping replica see revokes until they finish. A connection can die without an error — a NAT or firewall dropping an idle flow — so the listener proves liveness: every 5 s it NOTIFYs a second channel, dbmcp_permissions_ping, that the same connection listens on, and 15 s without hearing anything counts as a lost connection. The ping goes out on another connection, because only a notification from elsewhere proves that a change from elsewhere arrives. Every 5 s the listener also runs a SELECT 1 on its own connection: a pooler such as pgcat in session mode hands over a notification only with the answer to a request, so behind one a change arrives within 5 s instead of at once (pooler contract). Notifications sent while the listener is unsubscribed are lost, so on a lost connection — announced or silent — it flushes the whole grant cache at once, then again every 5 s until LISTEN is re-established, however long reconnecting (with backoff) takes; resubscribing flushes once more and is logged (permissions listener recovered; grant cache flushed). From the moment a drop is noticed until LISTEN is back, no grant is served from a load older than that 5 s beat. The bound on a revoke reaching every replica is the notification latency while the listener is connected (plus up to 5 s behind a pooler that relays only answers). On a lost connection there are two separate windows. The detection window: a revoke committed before the drop is noticed takes effect at the flush that noticing triggers — at once for an announced drop, up to 15 s after a silent one. The stale-cache window: once the drop is noticed, a replica keeps reloading grants between flushes, so a revoke committed just after such a reload is served until the next flush, up to 5 s later, for as long as reconnecting takes. The TTL (PERMISSIONS_CACHE_TTL_SECONDS, default 60 s, clamped ≤ 300 s) bounds only what nothing announces, such as a MySQL store edited outside the gateway.

SurfaceScopeWhy
/admin/v1/grants (POST/PATCH/DELETE)The grant's userA grant only ever affects the one user it targets.
/admin/v1/users (POST/PATCH/DELETE)The mutated row's user_subA group change flips constraint-merge results; a re-POST of an existing subject is an upsert and changes it too; a soft-delete (and its grant cascade) must stop landing decisions immediately.
/admin/v1/databases (PATCH/DELETE)Every subjectA rename or soft-delete changes what every specific grant on the row resolves to.
/admin/v1/databases (POST)NoneA new row has no grants, and wildcards resolve against config databases, never these rows.
RuleBehavior
Post-commitLocal invalidation runs after commit, so a concurrent reader cannot re-warm with the pre-commit state; the NOTIFY is transactional for the same reason.
Detached from the requestLocal invalidation runs on a tokio::spawned task (PermissionsCache::spawn_apply), so a client disconnect between commit and invalidate cannot strand a stale entry.
user_sub-keyedGrants reference users by row id; the handler resolves user_sub inside the transaction.
Service identitiesA service:<name> identity never reads the store — its authority is exactly its YAML group, so a DB grant seeded for it is inert.
YAML-only installs (driver: none)No store, no admin API → nothing to invalidate.

Wildcard grants​

db_name = "*" is a per-grant flag for "applies to every database the gateway config declares on server" — not every permissions_databases row registered for it. Registering or deleting a database row never changes what a wildcard covers; changing the config's databases does. Intended for dev/superuser grants; the audience Sebby flagged as "us devs and other like us".

Rules​

  1. Explicit denies always beat wildcard allows. (We don't have explicit denies today; absence is the deny — see 06-permissions §Evaluation. Wildcards do not change this.)
  2. A wildcard grant never widens permissions on a database the user has a more-specific grant on — the per-database grant's constraints intersect with the wildcard's, most-restrictive wins.
  3. Wildcards still go through the same constraint engine. A wildcard row_limit: 100 does not become unlimited just because it matches every db; it caps every db.

Tested with proptest in #55. The property: for any pair of (wildcard_grant, specific_grant) on overlapping databases, the merged result is never more permissive than the specific grant alone.

Reserved "*" sentinel on /admin/v1/databases​

"*" is only meaningful as the wildcard marker on grants (grant.server == "*" / grant.database == "*", expressed on the API as db_name_wildcard: true + database_id: null). A permissions_databases row whose server or db_name is literally "*" would let every Specific-target grant pointing at it silently behave as a wildcard — an authz escalation an admin registering a database "*" would not expect or intend.

To keep the sentinel from ever reaching the store, POST and PATCH on /admin/v1/databases reject any request where the trimmed server or db_name equals "*":

Body fieldValue (after trim())Response
server"*"400 invalid_request, message names the field and points at the wildcard-grant alternative
db_name"*"Same
Eitherwhitespace-only400 invalid_request, <field> must be non-empty
Eitherany other string containing * (e.g. prod-*-shard)Accepted — only the bare sentinel is magic to the evaluator

The rejection runs before any INSERT/UPDATE against permissions_databases, so a rejected request leaves the store and permissions_audit unchanged (verified end-to-end in tests/it_db/admin_databases_e2e.rs).

Declared servers only on /admin/v1/databases​

POST and PATCH on /admin/v1/databases (a PATCH only when it sets server) require the trimmed server to name a server declared in the gateway's boot config — the same set a wildcard grant's server is checked against; a SIGHUP reload does not change it. An undeclared server is 400 invalid_request (server must name a server declared in the gateway config). A row on an undeclared server would otherwise sit dormant until a later config change silently armed every specific grant on it. The same holds for the database: the resulting (server, db_name) must be a database the live config declares on that server (checked against the current config, so a reload that adds one makes it registrable at once); otherwise 400 invalid_request (db_name `x` is not a database the gateway config declares on server `y` ); a PATCH checks the pair it would produce after locking the row and before writing anything. Like the sentinel check, the refusal happens before the transaction opens, so no permissions_databases row and no permissions_audit entry is written (verified in tests/it_db/transport_wave2_admin_databases.rs).

The supported way to grant access to every database on a server is db_name_wildcard: true + database_id: null on POST /admin/v1/grants (see Request shapes above), not a permissions_databases row literally named "*".

DbAdapter trait​

Polymorphic query execution. CLAUDE.md convention: trait when the second impl arrives. Mongo is that second impl, so it lands now.

#[async_trait]
pub trait DbAdapter: Send + Sync + std::fmt::Debug {
/// Run one query under the gateway timeout + row cap (`run_query`).
async fn execute(&self, query: ExecQuery<'_>) -> Result<ExecResult, ExecError>;
/// Catalog: one row per column (pg) or per collection (mongo).
async fn describe_schema(&self, query: SchemaQuery<'_>) -> Result<ExecResult, ExecError>;
/// Up to `row_limit` rows of one table / collection (`sample_table`).
async fn sample(&self, query: SampleQuery<'_>) -> Result<ExecResult, ExecError>;
/// The plan as one JSON cell, without running the statement.
async fn explain(&self, query: ExplainQuery<'_>) -> Result<ExecResult, ExecError>;
/// Size, row estimate, vacuum/analyze and index stats per table.
async fn table_stats(&self, query: TableStatsQuery<'_>) -> Result<ExecResult, ExecError>;
/// The gateway's own non-idle backends on this database.
async fn db_activity(&self, query: ActivityQuery) -> Result<ExecResult, ExecError>;
/// Cancel what the gateway runs for `request_id`; `Ok(false)` if nothing was.
async fn cancel_request(&self, request_id: Uuid) -> Result<bool, ExecError>;
/// The target rejected the credentials; the registry replaces this adapter.
fn is_stale(&self) -> bool;
}

Source of truth: src/exec/adapter.rs. One adapter per (server, database); the registry (src/exec/registry.rs) builds it from server.kind and hands tools an Arc<dyn DbAdapter>. ExecQuery carries the raw query text (sql: SQL for pg, a JSON command document for mongo, a JSON argv array for redis), the grant's statement_timeout_ms and row_limit, the Access tier the SQL guard decided, dry_run and the gateway request_id. Identity never reaches the adapter: authz and audit run in the tool layer before and after it. The adapter is responsible for backend-specific read-only enforcement before any I/O.

Every implementation bounds each call by effective_timeout_ms (the grant value clamped to the 30 s ceiling) — pushed to the server where the backend has a server-side limit, and always also as a tokio::time::timeout — and reports truncation through ExecResult.truncated. An operation a backend cannot serve returns ExecError::NotImplemented { adapter, op }, which the tools answer as unsupported_backend (03). ExecError's Display never carries a connection string, host, password or role name.

Postgres adapter​

Existing pg execution moves behind DbAdapter with no behavior change. Read-only enforcement stays at the role level (per-DB ro_* roles in the target DB) + statement classification at the gateway. See 05-credentials.

One role per tier. A database that accepts writes declares write_role + write_password beside its read role, and the adapter keeps two pools keyed (server, database, read|write). Every read — a query_write caller's SELECT included — runs as role in a READ ONLY transaction; only a data write under query_write runs as write_role. A YAML query_write grant whose databases (wildcards expanded against the configured ones) lack a write_role fails boot (08-config); a DB-backed query_write grant on such a database is refused at request time with forbidden. The read tier never reaches a write-capable role.

Introspection (table_stats, db_activity, cancel_query — 03) runs on the read pool. The adapter tags every backend with the gateway request_id through application_name, which is how db_activity names requests and cancel_query finds one; the tool, not the adapter, checks that the request is the caller's own.

Mongo adapter​

Read-only enforcement is the interesting part. Mongo doesn't have a single "READ ONLY" role flag we can rely on the same way as a Postgres role; some "read" commands can write ($out, $merge in aggregation pipelines, $function server-side JS with side effects). The adapter rejects:

  • Any command containing $out, $merge, $function, $accumulator or $where, at any depth (pipeline stage, filter, projection, $lookup sub-pipeline). All $where is rejected: purity of arbitrary JS cannot be checked.
  • Any command outside the allowed set: find, aggregate, count, distinct, listCollections, listIndexes (src/exec/mongo/rejector/mod.rs, ALLOWED_COMMANDS).
  • Write commands explicitly: insert, update, delete, findAndModify, bulkWrite, createIndex, drop.
  • Any top-level key outside the command's own allow-list (src/exec/mongo/rejector/mod.rs, allowed_fields). The lists hold shape and read options only (filter, sort, projection, pipeline, cursor, limit, collation, …), so no $-prefixed key ($db would re-target the command at another database, $readPreference re-routes it), no session or transaction field (lsid, txnNumber, autocommit, startTransaction), no writeConcern, and no cursor-lifetime knob (tailable, awaitData, noCursorTimeout) reaches the driver. Before this, a $db key was forwarded and the server (8.0) refused the duplicate $db itself — safe by the server's grace, not the gateway's.

The connection still uses a least-privilege mongo role (read-only on the target DB) — defense in depth, same posture as the pg ro_* roles.

describe_schema and sample_table work on Mongo too: describe_schema is listCollections + listIndexes (collections with their indexes; schema is ignored, table names one collection) and sample_table is a find with the sample limit. Mongo writes stay out of scope (10); write_role on a Mongo database fails boot.

Timeouts via maxTimeMS. Row caps via a server-side limit of row_limit + 1 (find limit/batchSize, a trailing $limit stage on aggregate with a batch one larger, so the reply that fills the cap also closes the server cursor) plus the gateway's row and byte budget at the adapter. A reply missing its documented field, or a document that cannot be rendered, is a typed error — never a fabricated null. A NaN or infinite double, which JSON has no number for, renders as Extended JSON {"$numberDouble":"NaN"} ("Infinity", "-Infinity") at any depth, a code-with-scope value's $scope included. Cancellation: killOp on client disconnect or timeout, best-effort and requires an opt-in privilege; the cancel keeps the stopped call's connection permit and caller slot for at most 3 s, then gives up (src/exec/mongo/cancel.rs) — see config-reference.md §Mongo for the full contract (statement_timeout_ms is the guaranteed bound either way, same as pg's belt-and-suspenders tokio::time::timeout).

Audit row shape matches pg's: same audit_calls columns, with db_type = 'mongo' and the command document in sql exactly as sent — stored verbatim like SQL; there is no redaction policy (07-logging-retention).

Redis adapter​

kind: redis covers every RESP server — Redis, Dragonfly, Valkey, KeyDB; Redis and Dragonfly are CI-tested. The database is the logical DB index (name: "0"), the role is an ACL username, and the stock default user is refused at boot like postgres / root (08-config). The client (redis 1.8.1, tokio-rustls-comp only) is built from the structured config fields, never from a URL, so no connection string exists to leak. tls: required and verify_full both verify chain and hostname over rustls; insecure is plain TCP.

Read-only is enforced twice, as on Mongo:

  • Gateway allowlist. sql is a JSON argv array; the command name must be on a deny-by-default, case-insensitive list of read commands (strings, hashes, lists, sets, sorted sets, stream ranges, SCAN family — full list in 03 §Redis payload). Everything else — writes, KEYS, SORT, scripts and functions, MONITOR / SUBSCRIBE, blocking pops, WAIT, SELECT / AUTH / HELLO / MULTI, server administration, module commands — is forbidden_sql before any network call (src/exec/redis/rejector/mod.rs). query_write never lifts it; write_role on a Redis database fails boot.
  • Target ACL. The ACL user holds +@read -keys on the key patterns the agent may read and nothing else — the same posture as the pg ro_* roles, and the only key scoping there is. ACL key patterns do not filter SCAN / DBSIZE, so key names outside the pattern stay visible unless the user also gets -scan -dbsize (06; recipe in config-reference §Redis).

A malformed argv (not a non-empty array of strings/numbers, a SCAN-family call missing its cursor or an option value, a bad COUNT) is invalid_arguments at the argument edge, before the intent row; an unlisted command or option is forbidden_sql. Messages name the command or option, never an argument value.

Limits: Redis has no per-command server timeout, so effective_timeout_ms is a tokio::time::timeout alone, with no slack. A connection is reused only after a complete reply or a server error reply; a command the deadline, a client disconnect or an I/O error cuts off closes its connection. SCAN / HSCAN / SSCAN / ZSCAN take MATCH and COUNT (TYPE on SCAN only; NOVALUES refused), every COUNT clamped to 1,000 and COUNT 1000 appended when absent; row_limit and MAX_RESULT_BYTES truncate the reply with truncated: true. The pool is per (server, database), sized by max_connections / idle_timeout_s (min_connections ignored — nothing is pre-opened); each caller holds its own connection, so a slow command never head-of-line-blocks another caller behind one multiplexed connection. A connection the server closed while idle fails that call unavailable, without retry.

Bounded before sending (cap = row_limit + 1; full table in 03 §Redis payload): range commands (LRANGE, ZRANGE and its BYSCORE / BYLEX / REV forms, XRANGE, LPOS, *RANDMEMBER / HRANDFIELD) have their stop index, LIMIT or COUNT clamped to the cap, resolving negative indices with LLEN / ZCARD first; HGETALL / HKEYS / HVALS / SMEMBERS run as an internal HSCAN / SSCAN loop stopping at the cap or the byte budget; SUNION / SINTER / SDIFF are refused forbidden_sql when an SCARD precheck says the result could pass row_limit; GET / HGET / GETRANGE / SUBSTR are prechecked with STRLEN / HSTRLEN so a value over 32 MiB is never fetched; MGET / HMGET fetch at most the cap's worth of keys whose summed length fits 32 MiB. A key growing between precheck and read is left to the client timeout. Pool saturation is unavailable after the 5 s acquire wait, outside the statement budget, as on Postgres.

Errors: a refused TLS handshake (wrong CA, hostname mismatch, CA outside the roots — refused before AUTH is sent, test-proven) → unavailable; WRONGPASS / NOAUTH at connect → unavailable and the adapter is marked stale (reopened with a freshly resolved password); any other connect failure → unavailable, not stale; connect-time server text is never passed through. Command errors: NOPERM → permission_denied; other error replies → syntax_error with the ACL username replaced by <role>; I/O → unavailable; an unparseable reply → internal.

execute is the whole surface: describe_schema, sample, explain, table_stats, db_activity and cancel_request return NotImplemented — an audited unsupported_backend. cancel_query answers it after authz and the reason check but before the ownership lookup, so the answer is the same for any request_id. There is no in-flight cancel on Redis — the timeout and the closed connection are the bound.

Audit: db_type = 'redis', and sql holds the JSON argv exactly as the agent sent it. Intent and completion rows are written synchronously as for every target.

Phasing​

PhaseIssuesShip outcome
Design#46 (this doc)Surface locked
Storage#47, #48State DB has permission tables; pg repo works
Resolver#49, #50DB grants flow through the existing authz engine
Audit#51permissions_audit table + sync writer
Admin API#52, #53, #54CRUD endpoints, SSO-gated, audited
Wildcard#55db_name = "*"
Multi-DB#56, #57, #58DbAdapter trait, mongo adapter, mongo queries; redis adapter followed
Backends#59MySQL permission store
Docs#60Operator + developer docs

Each phase is independently shippable. The gateway stays YAML-only and pg-only until the relevant phase is complete. No flag-flip surprise.

Open questions​

  1. Admin bootstrap. How does the first admin get created when admin.enabled: true is first turned on and no users exist? Proposal: a one-shot CLI subcommand (gateway admin bootstrap <sso-email>) inserts the first user with the admin group, runs against the state DB directly, audits to permissions_audit with actor_id = NULL and request_id = "bootstrap".
  2. API versioning. /admin/v1/* — bake v1 into the URL now to avoid future churn. Confirmed default.
  3. YAML ↔ DB import/export. Out of scope for this milestone. Operators can write a one-off script against the public CRUD if they need to migrate. Revisit if the ask is real.
  4. Mongo and Redis write grants. Out of scope; Redis writes would need a write-capable ACL user and a write allowlist. query_write for mongo would mean lifting the rejector for $out/$merge etc; that's a future spec doc, not this one.

See also​