Skip to content

Configuration reference ​

dbgateway reads one YAML file. Keep it in Git and change it through pull requests: role bindings, policies and approval rules are then reviewed like code, and every audit log entry records the version of the file that decided it.

Example ​

A trimmed version of examples/dbgateway.yaml:

yaml
server:
  public_url: https://dbgateway.example.com   # TLS is terminated in front of dbgateway
  mode: enforce                               # or shadow

auth:
  oidc:
    issuer: https://idp.example.com
    client_id_env: DBGW_OIDC_CLIENT_ID        # secrets: names of environment variables only
    client_secret_env: DBGW_OIDC_CLIENT_SECRET

databases:
  - name: prod-main
    labels: { env: prod }
    primary:
      host: prod-main.db.example.com
      dbname: app
      read_user: dbgw_reader                  # SELECT only
      password_env: DBGW_PROD_READER_PASSWORD
      write_user: dbgw_writer                 # runs approved writes only
      write_password_env: DBGW_PROD_WRITER_PASSWORD

groups:
  - { name: data-team, oidc_group: data-team }
  - { name: sre, oidc_group: sre }

role_bindings:
  - { group: data-team, databases: { labels: { env: prod } }, roles: [querier, writer] }
  - { group: sre, databases: "*", roles: [querier, writer, approver] }

data_classes:
  - { columns: ["public.users.email"], class: masked, semantic_type: contact }
  - { column_pattern: "public\\.[a-z_]+\\.(id|[a-z_]+_id|created_at)", class: public }
semantic_types:
  contact: { method: partial }

approvals:
  enabled: true
approval_rules:
  - name: default
    when: "true"
    steps: [{ role: approver }]

policies:
  - { name: deny-ddl, when: 'stmt.kind == "ddl"', action: deny }
  - { name: reads, when: 'stmt.kind == "select" && !stmt.is_write', action: allow }
  - { name: writes, when: stmt.is_write, action: approve, require: { reason: true } }

Loading and validating ​

  • --config path (or -c) selects the file; the default is $DBGW_CONFIG, else dbgateway.yaml.
  • --config env:NAME reads the YAML from an environment variable instead, for platforms where files cannot be mounted. If DBGW_CONFIG_YAML is set and DBGW_CONFIG is not, it is used automatically.
  • Secrets are never written in the file. Keys ending in _env name the environment variable that holds the secret (passwords, DSNs, tokens, keys). sslrootcert_env does the same for a PEM CA certificate; dbgateway validates it and writes it to a private temporary file.
  • Unknown keys are errors. Problems that do not stop dbgateway (an unset environment variable, a non-verify-full TLS mode on a prod database) are printed as warnings.
  • dbgw config validate checks types, compiles every CEL expression, rejects allow rules that could match a write, and prints the configuration version.
  • Durations accept Go syntax plus days: 90s, 30m, 12h, 7d, 1d12h. Sizes accept 512KiB, 1MiB, 1MB or a plain number of bytes.
  • Database selectors (databases: in role bindings, unmask, break_glass) are "*", a name or a list of names, or { labels: { key: value } }.

Sections ​

server ​

KeyTypeDefaultDescription
listenstring127.0.0.1:8443Listen address (plain HTTP; terminate TLS in front)
public_urlURLhttp://<listen>External URL. Plain http only for loopback hosts
modeenforce | shadowenforceShadow mode records read denials instead of enforcing them
metrics_listenhost:port(off)Separate listener serving Prometheus metrics at GET /metrics (operations.md). Must differ from listen; metrics are never served on listen. Not authenticated: a non-loopback address produces a warning

auth ​

See authentication.md. One of oidc, passkeys or dev_login is required.

KeyTypeDefaultDescription
oidc.issuerURLOIDC issuer (required with oidc)
oidc.client_id_env, oidc.client_secret_envenv nameClient credentials
oidc.groups_claimstringgroupsID token claim holding the IdP groups
oidc.scopeslist[openid, email, profile]Requested scopes
passkeysboolfalsePasskey sign-in and enrollment links, for running without an IdP. public_url must use a host name
agent_tokens.max_ttlduration1hLifetime of agent access tokens (at most 24h)
agent_tokens.refreshboolfalseIssue refresh tokens to agents
cli_token_ttlduration12hLifetime of dbgw login tokens
session_ttlduration1hLifetime of browser sessions
dev_loginboolfalsePassword-less login for local development; only with a loopback listen
allow_insecure_client_metadataboolfalseAllow http:// client metadata URLs on loopback (development)

store ​

The management database: users, sessions, tokens, approval requests, grants. Use PostgreSQL for several instances (ha.md).

KeyTypeDefaultDescription
driversqlite | postgressqlite
pathpathvar/dbgateway.dbSQLite file
dsn_envenv namePostgreSQL DSN (required with postgres)
sslrootcert_envenv namePEM CA of the management database, added to the DSN

audit ​

See masking-and-audit.md.

KeyTypeDefaultDescription
outputfile | stdout | postgresfilePrimary output. postgres requires store.driver: postgres
dirpathvar/auditDirectory of daily files (file)
retentionduration365dEntries older than this are deleted, after a checkpoint
log_raw_sqlboolfalseRecord SQL with literal values
no_fsyncboolfalseSkip fsync after each entry (faster, less durable)
dsn_envenv namestore.dsn_envAudit database for postgres
otlp.endpointhost:portAlso forward entries as OpenTelemetry logs over gRPC (best effort)
otlp.insecureboolfalsePlaintext gRPC
otlp.headers_envenv namegRPC metadata as key=value,... (URL-encoded values)

sql ​

KeyTypeDefaultDescription
allowed_functionslist[]Functions added to the built-in allowlist, optionally schema-qualified (public.business_days)

masking ​

KeyTypeDefaultDescription
hmac_key_envenv nameKey of the hmac method; without it hmac falls back to redact

databases ​

A list. MySQL specifics are in mysql.md, IAM authentication in operations.md.

KeyTypeDefaultDescription
namestringUnique name used by callers
typepostgres | mysqlpostgres
labelsmapUsed by selectors and CEL (database.labels.env). env: prod changes the default class for agents
primaryendpointRequired
replicaendpointUsed by require.replica
limits.max_rowsint1000Rows returned per query
limits.max_bytessize1MiBBytes returned per query
limits.statement_timeoutduration10s
limits.lock_timeoutduration2s
search_pathlist[public]Schemas for unqualified names. MySQL: the default database only
default_class{human, agent}Class of unclassified columns on this database
docsmapDescriptions and example queries for agents and people writing SQL; see docs
backup.schemastringPostgreSQL only. Save the rows approved UPDATE/DELETE statements change into new tables in this schema; see Backups and restore
backup.requiredboolfalseDeny UPDATE, DELETE and MERGE statements that cannot be backed up
backup.retentiondurationkeepDrop backup tables older than this (at least 1h), checked hourly and audited
session_identityboolfalsePostgreSQL only. Set dbgateway.user, dbgateway.kind, dbgateway.agent, dbgateway.groups and dbgateway.request_id for every transaction, for row-level security

Endpoint keys:

KeyTypeDefaultDescription
hoststringRequired
portint5432 / 3306
dbnamestringpostgresRequired for MySQL (the replica inherits it)
authpassword | aws_iam | gcp_iampasswordIAM methods need TLS and no password; MySQL supports password only
regionstringAWS SDK defaultaws_iam only
read_userstringRequired. Grant it read access only
password_envenv namePassword of read_user
write_userstringRuns approved writes; without it, writes to the database are denied
write_password_envenv namePassword of write_user
sslmodestringverify-fullPostgreSQL modes; for MySQL disable, require or verify-full
sslrootcertpathCA file
sslrootcert_envenv nameCA as PEM in an environment variable (exclusive with sslrootcert)

docs ​

Knowledge about the schema that names alone do not tell: what the database is for, what tables and columns mean, units and allowed values, and example queries known to be right. Agents get it from list_databases and search_objects (MCP), people from dbgw dbs, dbgw search and the SQL editor's schema list. It lives in the configuration so that it is reviewed and versioned like everything else.

yaml
databases:
  - name: prod-main
    docs:
      description: Core OLTP database of the shop. Amounts are in JPY, tax included.
      tables:
        public.orders:
          description: One row per checkout. status is pending, paid or refunded.
          columns:
            amount: Total in JPY, tax included.
      examples:
        - title: Daily revenue
          description: Paid orders only, by UTC day.
          sql: |
            SELECT date_trunc('day', created_at) AS day, sum(amount) AS revenue
            FROM orders WHERE status = 'paid' GROUP BY 1 ORDER BY 1
KeyTypeDescription
descriptionstringAbout the database. Returned by list_databases
tablesmapKey: schema.table (MySQL: database.table), also for views. Matched case-insensitively
tables.*.descriptionstringAbout the table
tables.*.columnsmapColumn name to its description
exampleslistExample queries: title (required, unique per database), sql (required), description
  • Database comments are kept. search_objects returns the configured text as description and the database's own COMMENT as comment (detail full, as before). Nothing is merged or overwritten, so you can see where each came from; agents are told to prefer description when the two disagree.
  • Examples are attached to tables. dbgateway analyzes each example with the same SQL analyzer as execute_sql, against the live catalog, and returns it from search_objects whenever one of the tables it references (after resolving search_path, aliases, CTEs and views) is in the result. An example that cannot be analyzed — a typo, a table that no longer exists, a statement dbgateway refuses — is never shown, and a warning is logged once. Examples are shown, not run: they go through the usual checks when an agent executes them.
  • Same visibility as the schema. Docs are returned only to callers with search access (viewer, implied by querier) on the database, exactly like table and column names. A database the caller cannot search, or that does not exist, looks the same.
  • Metadata only. Descriptions do not change classification or masking: a masked column with a description is still masked. Docs are shown verbatim to everyone who can search the database, so never put data values (customer names, e-mail addresses, secrets) in them.
  • Keys are validated like the rest of the file: unknown keys, unqualified table names, empty entries and duplicate example titles are errors. dbgw config validate does not connect to the database, so whether examples reference existing tables is checked at run time (the warning above).

groups ​

KeyTypeDescription
namestringUnique group name
oidc_groupstringIdP group (OIDC claim or SCIM) that makes someone a member
memberslist of e-mailsStatic members, for environments without an IdP

role_bindings ​

See policies.md.

KeyTypeDescription
group / userstringExactly one: a group name or an e-mail address
databasesselectorRequired
roleslistviewer, querier, writer, approver, admin
expires_attimestampThe binding stops applying at this time (JIT)

default_class ​

{ human: <class>, agent: <class> }, each public, masked or no_ai. Overridden per database. When neither is set: masked for agents on env: prod databases, public otherwise.

data_classes ​

KeyTypeDescription
columnslistschema.table.column names (exclusive with column_pattern)
column_patternregexpMust match the whole schema.table.column
classpublic | masked | no_ai
semantic_typestringA key of semantic_types

Exact columns win over patterns; patterns are tried in order.

semantic_types ​

A map from name to { method: redact | partial | hmac }. See masking methods.

policies ​

KeyTypeDescription
namestringUnique
whenCELBoolean condition
actionallow | approve | deny
require.reasonboolReject generic reasons
require.step_upboolSatisfied by approvers' step-up on approve; denies reads
require.max_rowsintLower row limit for this rule
require.replicaboolRun reads on the replica
message, hintstringReturned on deny

Without policies, defaults apply (policies.md).

quotas ​

Limits on how much one person (with their agents) may read over time; see quotas.md. Every matching quota applies.

KeyTypeDescription
namestringUnique; rule quota:<name> and the key of the counters
whenCELOptional condition over principal, database, stmt and columns; empty matches every read. An evaluation error matches
queries_per_minuteintQueries in the current minute
queries_per_hourintQueries in the last hour
rows_per_hourintRows returned in the last hour
rows_per_dayintRows returned in the last 24 hours
hintstringAdded to the hint of a denial

At least one limit is required. Usage is kept in the management database (shared by all instances with store.driver: postgres).

scim ​

See scim.md.

KeyTypeDefaultDescription
enabledboolfalseServe /scim/v2
token_envenv nameBearer token the IdP presents (required when enabled; use 32+ characters)

pii_detection ​

See masking-and-audit.md.

KeyTypeDefaultDescription
enabledboolfalseScan values returned to agents
detectorslistallemail, phone_jp, credit_card, my_number
actionmask | denymaskMask the detected spans, or withhold the whole result

approvals ​

See approvals.md.

KeyTypeDefaultDescription
enabledboolfalseWithout it every write is denied
default_max_affected_rationumber2.0Affected-rows limit = estimate × ratio (at least 1)
step_up_max_ageduration5mHow recent step-up must be to approve or elevate (at most 1h)

risk ​

KeyTypeDescription
high, mediumlist of CELEvaluated high first; no match means low. Cannot reference risk

approval_rules ​

KeyTypeDefaultDescription
namestringUnique
whenCELCondition; may use risk
steps[].role / steps[].groupstringExactly one: approver or admin, or a group name
steps[].countint1Distinct people needed for the step
expire_afterduration1hTime to finish all steps (at most 7d)
max_affected_rowsintFixed affected-rows limit

unmask ​

KeyTypeDescription
user / groupstringExactly one
databasesselectorRequired
expires_attimestampOptional end of the grant

Applies to people only.

break_glass ​

KeyTypeDefaultDescription
max_durationduration1hLongest elevation (at most 24h)
databasesselectorRequired. Where approvers may elevate

Requires approvals.enabled.

notifications ​

Routes and their settings; see notifications.md. Every matching route is used.

KeyTypeDescription
eventslistapproval_requested, approval_decided, execution_finished, query_denied, break_glass_used, anomaly_detected, config_changed
whenCELOptional condition over database (name, labels) and event (type, status, risk); an evaluation error does not match
to.slackstring#channel, a channel ID, or requester (direct message)
to.mentionapproversMention the people who can act, in a channel message
to.webhook_envenv nameWebhook URL that receives the event as JSON

Top-level settings that go with them:

KeyTypeDefaultDescription
slack.app_token_envenv nameSLACK_APP_TOKENApp-level token (Socket Mode)
slack.bot_token_envenv nameSLACK_BOT_TOKENBot token
anomaly.denials_per_10mint10Denials per requester in ten minutes before anomaly_detected
anomaly.rows_per_hourint100000Rows returned to one requester in an hour before anomaly_detected (to enforce a limit, use quotas)
notifications_languageen | jaenLanguage of notification messages
notifications_webhook_secret_envenv nameHMAC-SHA256 key that signs webhook bodies (X-Dbgw-Signature)

auditors ​

A list of { user: <e-mail> } or { group: <name> }. They may use the audit log and user screens, as may anyone with admin on any database (masking-and-audit.md).

console ​

The SQL editor; see console.md.

KeyTypeDefaultDescription
historybooltrueKeep each person's executed SQL (as typed)
history_retentionduration30dHow long history is kept
exportbooltrueAllow CSV and JSON export
export_max_rowsint10000Rows per export (at most 1,000,000)

Released under the Apache License 2.0.