08 — Configuration
Shape
A single YAML file. Everything operational lives here. No per-environment forks of the binary; one binary, many configs.
# config.yaml — illustrative, not final schema
# Listener, state DB, TLS and OIDC settings are environment variables
# (GATEWAY_BIND, METRICS_BIND, STATE_DB_URL, STATE_DB_POOL_SIZE, TLS_*, OIDC_*,
# SESSION_TTL_HOURS) — see website/docs/deployment/config-reference.md.
gateway:
env: production # rejects inline literal secrets; default: development
servers:
- name: prod
kind: postgres
host: prod-rw.db.internal
port: 5432
tls: required
databases:
- name: app
role: mcp_gateway_prod_app_ro
password: vault:secret/prod/db/app_ro_password
description: "Main customer-facing app DB"
sql_capture: redacted
pool:
max_connections: 5
idle_timeout_s: 300
- name: billing
role: mcp_gateway_prod_billing_ro
password: vault:secret/prod/db/billing_ro_password
sql_capture: metadata_only
pool: { max_connections: 3 }
- name: staging
kind: postgres
host: staging.db.internal
port: 5432
tls: required
databases:
- name: app
role: mcp_gateway_staging_app_ro
password: ${FILE:/run/secrets/staging-app-ro-password}
# Optional write tier (postgres only). Present ⇒ `query_write` grants
# on this database run as this role; every read still runs as `role`.
write_role: mcp_gateway_staging_app_rw
write_password: ${FILE:/run/secrets/staging-app-rw-password}
- name: prod-cache # Redis, Dragonfly, Valkey or KeyDB
kind: redis
host: cache.db.internal
port: 6379
tls: verify_full
databases:
- name: "0" # logical DB index; grants address it as prod-cache/0
role: gateway_ro # ACL user, never `default`
password: ${FILE:/run/secrets/prod-cache-ro-password}
pool: { max_connections: 4 }
permissions:
- group: backend-engineers
grants:
- { server: staging, database: "*", action: query_read }
- { server: prod, database: "*", action: schema_read }
- group: oncall
grants:
- server: prod
database: "*"
action: query_read
constraints:
require_reason: true
statement_timeout_ms: 5000
row_limit: 1000
# Service-token group (spec 14). Each entry is the single permissions
# group a `service_accounts:` token acts as. Empty `grants:` is valid —
# it recognizes a group that authorizes nothing (authentication never
# implies authorization).
- group: svc-ci-bot
grants: [] # fill in the minimal grants this service needs
# Optional. Absent ⇒ /admin/v1/* returns 404, YAML-only permissions path.
admin:
enabled: true
group: db-admins # SSO group claim authorising admin calls
# Optional. Absent ⇒ pg (state DB) backs users/databases/grants.
permissions_store:
driver: pg # or 'mysql' — see boot-gate below
# Optional. Absent ⇒ no static bearer tokens accepted (OIDC sessions only).
# Headless-client credentials — name + one permissions group + secret ref.
# Full design: 14-service-tokens.md.
service_accounts:
- name: ci-bot
group: svc-ci-bot # must exist in permissions:; never the admin group
token: ${ENV:SERVICE_TOKEN_CI_BOT}
max_concurrent_requests: 64 # optional; replaces the per-identity cap (16) for this token
require_upstream: true # optional; refuse calls without x-dbmcp-run-id + x-dbmcp-on-behalf-of
logging:
hot_retention_days: 90
archive:
kind: s3
bucket: acme-db-mcp-audit
prefix: gateway/
region: us-east-1
stream:
- kind: otlp
endpoint: https://otel.internal:4317
Resolution order
- File at
--configflag, else$DB_MCP_GATEWAY_CONFIG. The binary has no default path — with neither set it exits. The published image setsDB_MCP_GATEWAY_CONFIG=/etc/gateway/config.yml. ${ENV:NAME}placeholders expanded from process env;${FILE:/path}placeholders read from disk (trailing newline stripped from${FILE:…}values; a${ENV:…}value is used byte for byte). A${ENV:…}ref whose variable is unset or empty aborts boot, as does a missing or empty file.vault:,aws-sm:,gcp-sm:references resolved from the named backend (when backend integrations land — until then, recognised refs also abort boot rather than silently failing at first DB connect).- Final config validated against the schema. Errors at this stage refuse to start the process — no half-loaded state. Every validation error and every unresolved secret ref is reported in the one abort (each ref named by server, database and tier), not just the first.
Validation rules (non-exhaustive)
- Unknown keys fail boot — at the top level and in every section. A misspelled
permisions:is a boot error naming the line, never a silently ignored block. gateway.env: production⇒ inline literal secrets rejected: everyservers[].databases[].passwordandservice_accounts[].tokenmust be a${ENV:…}/${FILE:…}reference. The error names the field, never the value.gateway.envdefaults todevelopment, which tolerates literals (local dev, tests).- Zero and blank values that parse but mean nothing are rejected: blank server/database
nameorhost,port: 0, androw_limit: 0/statement_timeout_ms: 0in grant constraints (Postgres reads a zero statement timeout as no timeout). Env side:STATE_DB_POOL_SIZE=0and a pool larger than the concurrent-request ceiling abort boot;METRICS_BINDmay not equalGATEWAY_BIND. - Every
permissions[*].groupmust be non-blank. The gateway never checks whether any IdP user is in the group — groups can be defined ahead of population, and no warning is logged. - Every
permissions[*].grants[*].server/databasemust exist inservers, or be the literal"*". - Server and database names may not be
*(reserved for the grant wildcard). pool:(on a server and/or a database:max_connections> 0,min_connections≥ 0,idle_timeout_s> 0) —min_connectionsabovemax_connectionsat the same level fails boot. Each field resolves database → server → built-in default.tls_ca_fileis valid only withtls: verify_fulland must be readable at boot.- Target TLS: on Postgres,
tls: required(the default) encrypts but does not verify the server certificate (sslmode=require); on Mongo it verifies chain and hostname. On Redis,tlsis therediss://equivalent over rustls (the client is built from the structured fields, never a URL string), and like Mongo bothrequiredandverify_fullverify chain and hostname; there is no client-certificate (mTLS) option.tls: verify_fullverifies chain and hostname on all three (Postgressslmode=verify-full), againsttls_ca_file(which replaces the system roots) or the system roots — the setting to use for Postgres in production.tls: insecureis plaintext (plain TCP on Redis). Boot logs one warning per unverified or plaintext server, naming it. write_roleandwrite_passwordcome as a pair, onpostgresdatabases only;write_rolefollows the role-name and superuser rules below and must differ fromrole(the read role must not hold write privileges). Ingateway.env: production,write_passwordmust be a secret reference likepassword.- Every database a YAML
query_writegrant matches — wildcards expanded against the configured databases — must declare awrite_role; otherwise boot fails naming the group, database and server. (A DB-backedquery_writegrant on such a database is refused at request time withforbidden.) - On a
redisserver, every databasenameis the logical DB index in canonical decimal form ("0","1", … — not"00"or"+0", so one index has one grant address); anything else fails boot naming the database and server.auth_databasehas no Redis meaning (ACL users are server-wide) and fails boot.portdefaults to6379forkind: redis(5432for every other kind).write_roleon a Redis database fails boot like on Mongo: it is read-only through the gateway.defaultis refused in any letter case. A non-zero DB index needs+selecton the ACL user (the connection selects the index at connect time). Ofpool:,max_connectionsandidle_timeout_sapply;min_connectionsis ignored on Redis (no connection is opened ahead of use). service_accounts[].max_concurrent_requests, when set, must be ≥ 1;require_upstreamdefaults tofalse.- Role names must match
^[a-zA-Z_][a-zA-Z0-9_]*$. Catch typos before they become connection failures. - A database's
rolemust not be the stock superuser account its backend ships with (postgresfor Postgres,rootfor MySQL,safor MSSQL,root/adminfor Mongo,defaultfor Redis — the ACL user every Redis-protocol server starts with, holding+@all ~* &*unless restricted). YugabyteDB YSQL shipsyugabyteas its superuser; it is declaredkind: postgres, so onlypostgresis caught by name — provision a least-privilege role anyway. Matched case-insensitively on the name only — a superuser renamed toappstill passes; the real least-privilege guarantee lives target-side. Rejected at boot so the "never run as DB superuser" rule (see 05-credentials.md) can't be defeated by a config typo. - Every server's
kindmust have a query adapter wired (todaypostgres,mongoandredis). YugabyteDB (YSQL) is apostgrestarget, not a kind of its own. Amysql/mssqltarget is rejected at boot rather than parsing clean and failing every query at runtime — these kinds are reserved for the roadmap adapters and only become valid when their adapters land. MCP_PATH(env-driven for now, folded into YAML with #16) must not collide with a path the gateway already mounts. Reserved exact paths:/healthz,/readyz,/metrics,/auth/login,/auth/callback,/auth/logout,/authorize,/token,/revoke,/register. Reserved route families (the path and anything under<prefix>/…):/admin(owned by the admin API — reserved unconditionally so togglingadmin.enabledcan't turn a working config into a boot panic) and/.well-known(RFC 8414/9728 discovery metadata). Segment-based match:/adminyor/tokensare fine. Overlap surfaces as a typed boot error naming the offending path, not an axum router panic.admin.enableddefaults tofalse— absent or false leaves/admin/v1/*unmounted (404). Whenenabled: true,admin.groupis required and must be non-empty/non-whitespace, else boot aborts (every authenticated caller would otherwise be an admin); when disabled it is optional and ignored. Full surface in 12-dynamic-permissions.md.- Auth env (until #16 folds it into YAML):
OIDC_ISSUERandOIDC_CLIENT_IDare required (absent or blank aborts boot).SESSION_TTL_HOURSmust be a whole number in1..=168,REFRESH_TTL_DAYSin1..=366; anything else —0, out of range, overflow, non-numeric — aborts boot with the variable named.SESSION_SIGNING_KEYmust be at least 32 bytes and not the committed dev default, unlessALLOW_INSECURE_SIGNING_KEY=true, which is accepted only with a loopbackOIDC_ISSUER(local dev against a mock or local IdP) and a loopbackGATEWAY_BIND, and logs aWARNat boot; with any other issuer or bind it aborts boot.ALLOW_INSECURE_SIGNING_KEYandTLS_DISABLEDshare one strict boolean parser:true/false,1/0oryes/no(ASCII case-insensitive; empty reads asfalse), anything else aborts boot naming the variable.SESSION_CACHE_TTL_SECONDSabove300is clamped to300with aWARN. permissions_store.driver: mysqlcombined withadmin.enabled: trueis rejected at boot — admin handlers are pg-only today. Usedriver: pg(the default when the block is absent) for the admin path, ormysqlwith YAML grants only.
YAML parser
Config YAML is parsed only through config::yaml::non_leaking_options — never serde_saphyr::from_str. A config file is mostly credentials, so a parse failure is a disclosure risk.
Crate: serde-saphyr, the serde front-end for saphyr (yaml-rust2 successor).
| Candidate | Status | Verdict |
|---|---|---|
serde_yaml | archived Mar 2024 | rejected — no fixes, and it parses every boot |
serde_yml | archived | rejected — the popular fork is dead too |
serde_yaml_ng | ~1 yr idle | rejected — less audit surface than what it replaces |
serde_norway | ~1 yr idle | rejected — same |
serde-saphyr | 1.0, active | chosen |
The ecosystem never migrated off serde_yaml; it still outpulls every fork combined. Swapping to an idle fork trades a scrutinised frozen crate for an unscrutinised quiet one.
Parse errors never quote the file
A parse error carries a position and the schema's expectations, never the file's content. Both come from the gateway's own types:
Error: /etc/gateway/config.yml:3:11: invalid configuration (expected one of postgres, mysql, mssql, mongo, redis)
Three independent controls enforce this. Each has been observed to fail alone.
| Control | Without it |
|---|---|
Snippet rendering disabled (non_leaking_options) | Parser attaches a window of surrounding source — discloses neighbouring credentials even when the error is elsewhere |
Error stores no parser text — only position + the text after expected one of | The offending scalar rides along in the message |
Parse has no #[source] | main returns anyhow::Result; anyhow prints every source() link under Caused by:, so a "suppressed" message still reaches the terminal |
The third was missed originally: suppressing at Display is not sufficient, the chain must be severed. Re-attaching a #[source] reopens it, so a test asserts the chain has no second link.
Extraction is an allowlist, not a redaction. serde puts the input token before expected one of and the schema's alternatives after it, so copying only the tail is safe by construction — a redaction rule would have to track the parser's phrasing, whereas this can only fail closed by finding no marker.
Operators lose nothing: :line:column points at the offending value in a file they already have, and the list names what the field accepts.
Hot reload
SIGHUP re-reads the file (and, with TLS on, the cert + key). The reload runs the boot path — parse, validate, resolve every secret ref, build the service-token store — and only then publishes, past a point where nothing can fail, the service tokens, the config snapshot and the logging.stream sinks, invalidates every cached grant, and retires the target pool of each (server, database) whose connection settings (host, port, tls, tls_ca_file, role, auth_database, password ref, pool) changed or that was removed: pools no request holds close at once; the rest close when their last request lets go, checked by a sweep every 10 s and bounded by the 5-minute snapshot lifetime. Any failure before the swap keeps the running config whole and logs the error — never half-applies. Each request reads one snapshot, so a request in flight finishes on the config it started with; retired pools serve their in-flight queries and close, new ones open lazily. A database with an inline literal password is always retired (the literal is never compared).
The publication is not one atomic swap: each piece is its own pointer, stored in that order — service tokens, config snapshot, sinks, then the grant-cache invalidation and pool retirement. A request that lands between two stores sees a mix, and the order makes every mix fail closed:
- Tokens before config. A service account the new file removes stops authenticating before the config that removed it is visible, so no request authenticates with it against a config that no longer lists it. An account the new file adds (or moves to another group) authenticates a moment early and is evaluated against the old config's grants for the group the new file assigns it. For a moved account that can be broader than what it held before, for that window; a group the new file introduces grants nothing yet, so the request is
forbidden(and audited). Removing access is the direction that never lags. - Config before the grant cache. Until the invalidation lands, a request may still be served from a grant cached under the previous config — the same staleness any cached grant has between two reloads, bounded by that one step.
- Sinks after config. An audit row written in the window goes to the previous
logging.streamsinks; the state-DB row, which is the audit of record, is unaffected.
Outcomes count in config_reloads_total{result="ok"|"error"}. A SIGHUP with TLS off reloads the config too; the handler is always installed, so the signal never terminates the process.
Fixed at boot — a reload that changes them is refused whole (restart instead):
- the admin API: whether it is mounted, its
group,session_max_age_secs; - the admin API's known-server list (wildcard grants and server checks in
/admin/v1/*) — while the admin API is mounted, renaming, adding or removing a server is refused; reorderingservers:is not a change; permissions_store.driver.
Env-driven settings (listeners, state DB, TLS paths, OIDC) are read once at boot.
Operator CLI
The binary is its own operator tool (reference: deployment/cli). Every mode below runs without booting — no state DB, listener or Sentry stream — and exits 0 success, 1 a negative answer, 2 usage, 3 could not run.
--check [--no-secrets]validates without booting: parse, validate, and (unless--no-secrets) resolve every secret ref, reporting every error; warnings for unverified/plaintext target TLS, constraints no tool under their action reads (row_limitonschema_read,row_limit/statement_timeout_msonhistory_read), and set env vars that share a gateway prefix but are not read (typos); and the per-replica connection budget (read + write tiers + Postgres cancel pools per server; state DB request + background + listener pools). Messages carry field and object names, never values. A hand-written JSON Schema (website/static/config.schema.json) mirrors the keys; a test pins it to the parser through a fixture that uses every key.--healthcheckGETs the local/healthz(fromGATEWAY_BIND; TLS unverified on loopback, no credential sent) and exits0/1— the healthcheck for the distroless image.login,grants list|apply,sessions revoke,audit query|exportare clients of the audited admin API (spec 12) and hold no privilege of their own.loginis the gateway's own OAuth flow run as a native app (RFC 8252: DCR with a loopback redirect, PKCE S256); the session token is stored in a0600file and a group- or world-readable one is refused.mint-service-token <name>replaces the shell script's logic (spec 14);bin/mint-service-tokenis a wrapper.rolesprints the provisioning SQL for each configured database's read and write roles and never connects;doctorconnects to each database'sconnect_nameas each configured Postgres role and reports superuser/admin attributes, write orCREATEprivileges on the read role, and in-scope relations it cannot read, plusmax_connectionsagainst the budget. Doctor runs catalog reads, as unnamed statements, in a rolled-backREAD ONLYtransaction. Neither grants anything (MUST #3).
What is not in config
- Anything user-facing. No UI strings, no branding, no email templates (this isn't that kind of product).
- Per-user permissions. Users get permissions through groups, period.
- DB schemas. The gateway reads the DB's own schema; it doesn't maintain a separate model.