Architecture · All ADRs
ADR 0012 — Database Security Gateway: analyze, authorize per table, rewrite the AST, execute only regenerated SQL
Architecture decision record — status: Accepted.
Status: Accepted
Context#
EPIC 17 lets agents query PostgreSQL, MySQL, SQL Server, MongoDB, Redis, Snowflake and BigQuery without ever holding database credentials, under the same pipeline as every other action (Authenticate → Identify → Authorize → Assess Risk → Inspect → Approve → Acquire Scoped Credentials → Execute → Sanitize → Audit → Observe). The hard problem is that a SQL string is code: string-level checks (regexes, keyword lists) are bypassed by comments, quoting, case, CTEs, subqueries and dialect quirks, and the parser the gateway uses is never exactly the database's parser.
Decision#
- Parse, model, and execute only what was modeled.
@gebsecure/dbgateway(pure, no I/O) tokenizes the query with a dialect-aware lexer, parses it withnode-sql-parserusing the engine's grammar, and reduces it to a normalized statement model (type/verb/classification, tables with read/write access, columns read/written, output-column lineage, predicates, joins, CTEs, subqueries, functions, limit). Policies are evaluated against the model, the AST is rewritten, and the SQL that runs is regenerated from the AST (sqlify). Comments, whitespace and anything the parser ignored never reach the database. The regenerated SQL is re-parsed and compared (statement type, tables, columns, functions, literal multiset, row-filter placement); any difference fails closed. This catches generator bugs (e.g. MySQL1e3regenerated as an identifier) and parser/database disagreement. - Refuse constructs with parser-differential risk at the lexer: MySQL executable comments (
/*! */), optimizer hints, nested comments, escape-string and dollar-quoted literals, backslash escapes where the grammar's handling is uncertain, control characters,"x"-vs-identifier ambiguity (normalized: SQL Server and Snowflake treat"x"as an identifier; the gateway forcesQUOTED_IDENTIFIER ONand pins MySQL'ssql_mode/PostgreSQL'sstandard_conforming_stringsso the server lexes exactly as analyzed). Unparseable input and multi-statement input fail closed (multi-statement only with an explicit connection policy flag; each statement is then analyzed and rewritten separately). - Identifier folding is applied before parsing exactly as the engine does it (PostgreSQL → lower, Snowflake → upper) so the regenerated, quoted SQL keeps the original meaning; table/column controls compare case-insensitively (over-blocking is preferred to bypass).
- Placeholders are rebound by identity, not position. Positional
?are rewritten to unique markers (numeric sentinels for MySQL,:Nfor Snowflake,@__gs_pNfor BigQuery) before parsing and mapped back after regeneration, so clause reordering by the generator cannot shift parameter values. Row-filter values are always bound parameters — never spliced into SQL text. PostgreSQL parameters are renumbered densely after rewriting. - Authorization uses the existing engine, once per table. Action
db:<engine>/<verb>(e.g.db:postgres/select,db:mongodb/delete,db:redis/read) — the/<verb>form makesaction.category(read/write/delete/admin) work in GSL and the existingblock-destructive-sqltemplate apply. Resourcedb:<connection>/<database>/<schema>/<table>. Contextquery.{statementType, verb, classification, tables, columns, hasWhere, limit, joins, functions, predicates, fingerprint…}; volatile estimates under__inspection.db(excluded from approval snapshots). The primary table (first written, else first read) gets the real decision (risk, limits, approvals, audit); every other table is checked with a side-effect-free dry run, so a join, subquery, CTE or UNION cannot reach a table a policy forbids. Delegation, risk thresholds, taint and simulations apply unchanged. - Connection policy (data-plane guard rails) is stored per connection: access mode (read_only by default), database/schema/table allow/deny with wildcards and read/write scoping, blocked and masked columns, row filters bound to principal attributes, destructive handling (
deny/approval/allowfor DDL, admin statements, unbounded writes and estimated mass writes), injection handling, comment and multi-statement switches, and cost limits. - Row-level rules by AST rewriting. For every scope (top level, subqueries, CTE bodies, set-operation branches, UPDATE/DELETE targets) that reads a filtered table,
<qualifier>.<column> = <param>is AND-ed — parenthesized — into that scope's WHERE; inserts are stamped (agent-supplied values replaced); updates of the filter column, INSERT … SELECT into filtered tables and upserts are refused; every matched table must have received its filter or the query is refused. MongoDB gets$andfilters / a leading$match(+$unsetof blocked fields); Redis gets a mandatory key prefix. - Column controls: blocked columns deny any reference (including through
*, aliases, functions, subqueries); masked columns may only be projected directly and are masked in results by output lineage (aliases and expressions included), then inbound DLP runs over the whole result set (path-aware) and prompt-injection inspection treats results as untrusted tool output. - Execution in the trusted runtime (not the connector sandbox): official drivers (
pg+pg-cursor,mysql2,mssql/tedious,mongodb,ioredis) connect to an address validated by the ADR-0011 rules (validateUrl: DNS resolved once, private/metadata ranges blocked unless allowed, environment deny lists) while TLS uses the configured hostname (SNI +checkServerIdentity). Mongo usesdirectConnection+ a pinnedlookup(no topology discovery); Redis disables reconnects/offline queue. Reads run in READ ONLY transactions that are always rolled back (SQL Server: rolled-back transaction), so a misclassified statement still cannot write. Every query has a server-side timeout plus a client deadline, a row cap (injected LIMIT/TOP plus streaming cut-off) and a byte cap. Snowflake (SQL API v2: key-pair JWT, PAT or OAuth) and BigQuery (jobs.query; service-account JWT bearer exchanged at a fixed token endpoint) go through the credential broker (brokerHttp), so host allow-listing, SSRF rules, circuit breaker and credential injection apply. - Cost assessment runs only if a dry-run authorization would not deny: PostgreSQL/MySQL
EXPLAIN (FORMAT JSON), SQL ServerSHOWPLAN_XML(parameters declared as typed, unassigned variables — no values in text), BigQuerydryRunbytes (andmaximumBytesBilled), SnowflakeEXPLAIN USING JSONbytes, MongoDBcountDocuments(capped), RedisDBSIZEfor keyspace scans. Estimation failure on a write fails closed. - Approvals bind the exact query. The approval snapshot contains the literal-free fingerprint and structure, plus
execution.queryHash = H(engine, connection, query text, params); a retry withapprovalIdexecutes only a byte-identical query, once. - Audit without data. Every attempt (including parse failures, denials and approval mismatches) is recorded in
db_queries(RLS) and as adatabase.queryaudit event with the literal-free fingerprint, hashes, tables, decision, estimates, counts and a scrubbed error code — never raw literals, parameter values, result data or credentials. Credential use is audited by the vault (secret.use, connectordb:<engine>).
Alternatives considered#
- Regex/keyword filtering — trivially bypassed; rejected.
- libpg_query / pgsql-parser (the real PostgreSQL parser via WASM) — exact for PostgreSQL only; would need a second stack per engine. The round-trip verification makes node-sql-parser's imperfections fail closed instead of failing open; libpg_query remains a drop-in candidate for the PostgreSQL analyzer.
- pgsql-ast-parser — PostgreSQL only, smaller grammar coverage.
- Database-native enforcement only (RLS, column privileges, read-only roles) — necessary but not sufficient: it cannot express per-agent policies, approvals or audit. Customers should still use least-privilege database roles; the gateway's read-only transactions are an additional native layer.
- Executing the original text after checks — allows comment/lexer differentials; rejected in favor of regenerated SQL.
Consequences#
- (+) Table/column/row policies hold under quoting, case, comments, CTEs, subqueries, unions and schema qualification; agents never see credentials; every attempt is auditable without storing data.
- (−) Unsupported syntax fails closed: e.g.
SELECT … FOR UPDATEandDELETE … USING(PostgreSQL grammar gaps),DELETEin Snowflake, BigQueryDELETEregeneration, SQL ServerMERGE, MySQL exponent literals. These are reported as "unsupported syntax" denials. - (−) One database connection per query (no pooling) — simpler isolation and credential freshness at the cost of connection setup latency.
- (−) Snowflake/BigQuery do not offer read-only transactions over their HTTP APIs: use read-only roles for read-only connections.