sql-write-gate
写库前门禁 · Policy firewall for AI agents writing to databases.
Prevent Claude Code, Codex, Cursor and MCP agents from executing unsafe database operations.
Agent SQL ──► sql-write-gate ──► ALLOW / BLOCK / APPROVAL ──► Database
Deterministic policy engine (sqlglot AST + catalog + policy.yaml). No LLM. No API key.
非生产唯一边界 — Early gate prototype; not the sole production security boundary. 未列语法拒绝 — unsupported / ambiguous SQL → REJECT/BLOCK (fail closed), never silent ALLOW as read-only.
Install
pip install sql-write-gate
pip install 'sql-write-gate[postgres]' # optional: psycopg
pip install 'sql-write-gate[mysql]' # optional: pymysql
pip install 'sql-write-gate[mcp]' # optional: MCP server
From a clone:
pip install -e ".[dev]" # or: make install
pip install -e ".[postgres,mysql]"
make test # PG/MySQL live tests skip if no service
sql-write-gate check "DELETE FROM users"
# → BLOCKED rule=delete_without_where
Commands
sql-write-gate check "SQL" # evaluate SQL; no execute
sql-write-gate hook # PreToolUse: block raw psql/mysql/…
sql-write-gate mcp # MCP stdio (query_sql / write_sql)
sql-write-gate proxy --sql "..." # gate then execute if ALLOW
sql-write-gate approve <id> # human approve then write (once)
sql-write-gate resolve <id> --as succeeded|failed|rejected
sql-write-gate audit # TIME / SOURCE / OP / TABLE / VERDICT
sql-write-gate init # scaffold policy.yaml + catalog.json
What it does (current)
DROP/TRUNCATE/ALTER→ BLOCKDELETE/UPDATEwithoutWHERE→ BLOCK- Blast-radius COUNT vs
update_rows/delete_rows(dialect quoting; fail-closed on estimate error) - Schema / PII / restricted columns; PII
SELECT→ REQUIRE_APPROVAL (approve executes once) - Freshness partitions (
dt); range / NOT / OR / UPSERT SET expired → BLOCK - Nested / data-modifying CTE /
SELECT INTO→ REJECT (unsupported_sql) - Approval state machine (SQLite source of truth + JSONL mirror):
pending→executing→succeeded|failed|unknown(+rejected) - Atomic claim under
fcntl.flock+ SQLiteBEGIN IMMEDIATE(single-host; fail closed without flock) - Three-state execute outcomes;
unknown/executingnever auto-retried — useresolveorapprove --allow-unknown-retryafter manual DB verify - JSONL audit (redacts URL passwords; records execute failures / unknown)
- Adapters: DuckDB (default), PostgreSQL, MySQL, SQLite
Platform support matrix
| Surface | Linux / macOS | Windows |
|---|---|---|
pip install / CLI check / init / audit |
✅ | ✅ |
| DuckDB file backend | ✅ | ✅ |
SQLite sqlite:/// paths (incl. C:/…) |
✅ | ✅ |
| Postgres / MySQL URL adapters | ✅ | ✅ (drivers via extras) |
| PreToolUse hook / MCP stdio | ✅ | ✅ (same Python entrypoints) |
Concurrent approve (flock + SQLite claim) |
✅ | ❌ fail closed — ApprovalError if fcntl.flock unavailable (no silent unlock) |
Windows: install, CLI evaluate/execute on DuckDB/SQLite/URL backends work. Approval mutations require Unix fcntl flock (plus SQLite transactions); without flock they refuse rather than silently degrading.
Approval outcomes & crash recovery (v0.21)
| Status | Meaning | Default approve |
|---|---|---|
pending |
Queued; not executed | Claims → executes |
executing |
Claim held (in flight) | Refuse (no steal) |
succeeded |
DB write/query completed | Idempotent; no re-write |
failed |
Known not committed / never sent | May reclaim & retry |
unknown |
Timeout/disconnect/crash/indeterminate | Refuse — never auto-retry |
rejected |
Human rejected | Refuse |
Recovery rules:
- Process crash while
executing: after TTL (SQL_WRITE_GATE_EXECUTING_TTL_SEC, default 120s) →unknown(viaapprove --force-unknown-check/ next store access). Never silent re-claim that re-runs SQL. - Operator path for
unknown: verify target DB manually, then eithersql-write-gate resolve <id> --as succeeded|failed|rejected(no SQL), orsql-write-gate approve <id> --allow-unknown-retry(explicit re-exec; double-write risk).
- Default second
approveonsucceeded/unknowndoes not write again.
Database URLs
| Env / kwarg | Backend |
|---|---|
POSTGRES_URL or postgresql://… / postgres://… |
PostgreSQL |
MYSQL_URL or mysql://… / mysql+pymysql://… |
MySQL |
DATABASE_URL (scheme-detected) |
Postgres / MySQL / SQLite |
sqlite:/// / sqlite+aiosqlite:// |
SQLite (stdlib) |
file path / default seed/warehouse.duckdb |
DuckDB |
Priority: database= → database_url= → db_path= → POSTGRES_URL → MYSQL_URL → DATABASE_URL → DuckDB default.
Live integration tests (optional locally)
export POSTGRES_URL=postgresql://gate:gate@localhost:5432/writegate
export MYSQL_URL=mysql://gate:gate@127.0.0.1:3306/writegate
pip install -e ".[dev,postgres,mysql]"
make test
Without those services, live tests skip; CI runs Postgres + MySQL service containers.
Policy (default production)
| operation | rule |
|---|---|
| select | allow |
| insert | approval |
| update | approval |
| delete | block |
| ddl | block |
Limits: update_rows: 100, delete_rows: 50. Demo policy (examples/policy.demo.yaml) allows insert/update for walkthroughs.
Guards (any BLOCK wins, else any APPROVAL, else ALLOW):
destructive → schema → pii → freshness → blast_radius → environment
Decision model
ALLOW | BLOCK | REQUIRE_APPROVAL with risk, rule_id, reason, evidence.
Deployment model (trusted executor)
非生产唯一边界 — this gate is not the sole production security control.
| Concern | Where it lives |
|---|---|
DB credentials (DATABASE_URL / …) |
Trusted executor only |
policy.yaml / catalog |
Trusted executor (agents have no rewrite API) |
approve / resolve / reject |
Trusted executor with approval token |
check / hook / MCP query_sql/write_sql |
Agent-facing: evaluate / enqueue only |
Approval privilege (SQL_WRITE_GATE_APPROVAL_TOKEN)
- On the trusted executor, create a secret file (default
.logs/approval.key, or setSQL_WRITE_GATE_APPROVAL_KEY_FILE). - When calling
approve/resolve/reject, set envSQL_WRITE_GATE_APPROVAL_TOKENto that file's contents. - Missing key file, missing token, or wrong token → refuse (CLI exit non-zero). Correct token → 0.21 behavior.
- Agents must not receive the key file or token. They may still enqueue
REQUIRE_APPROVALvia normal write paths.
Target binding
Approval records store database_config_id (fingerprint). Approve reconnect binds trusted credentials only for the same target. Queue against DB A then change env to DB B → approve fail closed (will not write to B).
SQL support matrix
| Supported (gated) | Explicitly rejected (unsupported_sql BLOCK) |
|---|---|
Single-statement SELECT / INSERT / UPDATE / DELETE |
Multi-statement scripts (stmt1; stmt2) |
| DuckDB / PostgreSQL / MySQL / SQLite dialects via adapters | MERGE / COPY / REPLACE / raw Command |
| Simple CTEs over read-only SELECT | Data-modifying CTE / nested DML under any root |
UPSERT ON CONFLICT DO UPDATE (PII/restricted on SET cols) |
PostgreSQL SELECT … INTO |
| Catalog-backed schema / PII / freshness / blast-radius | Ambiguous or unlisted write-shaped SQL |
Anything dangerous or ambiguous not on the supported side → unsupported_sql BLOCK/REJECT (fail closed), never silent ALLOW.
Boundaries (non-goals)
- 非生产唯一边界 — combine with least-privilege DB roles, network isolation, and human workflows
- Not a distributed approval lock, MySQL wire-protocol proxy, or Web UI
- Not an enterprise DQ / lineage / ChatBI / multi-tenant platform
See CHANGELOG.md for version history (v0.1 → v0.22).
Backlog (post-0.22)
- Trusted-executor approval token + key file privilege separation (0.22)
- Approve target fingerprint fail-closed on DATABASE_URL swap (0.22)
- SQL support matrix + unsupported variant regressions (0.22)
- Three-state approve outcomes + unknown ≠ auto-retry (0.21)
- SQLite durable approval store + crash TTL → unknown (0.21)
- Multi-process single-write approve regressions (0.21)
- Real Postgres / MySQL CI services + persist/recheck integration tests (0.20)
- R1–R6 permanent regression (dangerous + safe paths) (0.20)
- Windows support matrix + flock fail-closed (0.20)
- Release gate: wheel install smoke; publish needs test+build on same tag (0.20)
- Deferred: distributed / multi-host approval lock
- Deferred: MySQL wire-protocol proxy
- Deferred: Web UI
许可
MIT。见 LICENSE.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sql_write_gate-0.22.0.tar.gz.
File metadata
- Download URL: sql_write_gate-0.22.0.tar.gz
- Upload date:
- Size: 86.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b07b48492457eb8d068f3b5a2415400e4c900752f09b832355b8dd8cc01db5d9
|
|
| MD5 |
4136047dc29a1d54303a6d8615261f76
|
|
| BLAKE2b-256 |
bbad89b05a98f66344e1e513feac6178366e69155b408c635423da20a7c0d381
|
Provenance
The following attestation bundles were made for sql_write_gate-0.22.0.tar.gz:
Publisher:
publish.yml on tangyf07/sql-write-gate
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sql_write_gate-0.22.0.tar.gz -
Subject digest:
b07b48492457eb8d068f3b5a2415400e4c900752f09b832355b8dd8cc01db5d9 - Sigstore transparency entry: 2738507976
- Sigstore integration time:
-
Permalink:
tangyf07/sql-write-gate@cd08baa86b287f8bf4011b19708fdd91502e082d -
Branch / Tag:
refs/tags/v0.22.0 - Owner: https://github.com/tangyf07
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@cd08baa86b287f8bf4011b19708fdd91502e082d -
Trigger Event:
push
-
Statement type:
File details
Details for the file sql_write_gate-0.22.0-py3-none-any.whl.
File metadata
- Download URL: sql_write_gate-0.22.0-py3-none-any.whl
- Upload date:
- Size: 72.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7220581d3ad664b0caef94befbe8e4906c665330fbc659f847ffd2b79ec67dde
|
|
| MD5 |
e5f3ef2bc76f67d630e14567926315dc
|
|
| BLAKE2b-256 |
e63d41e38d86eca90a1d1177db71212d22747e55acf9fb5c0424774a28a490cd
|
Provenance
The following attestation bundles were made for sql_write_gate-0.22.0-py3-none-any.whl:
Publisher:
publish.yml on tangyf07/sql-write-gate
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sql_write_gate-0.22.0-py3-none-any.whl -
Subject digest:
7220581d3ad664b0caef94befbe8e4906c665330fbc659f847ffd2b79ec67dde - Sigstore transparency entry: 2738508098
- Sigstore integration time:
-
Permalink:
tangyf07/sql-write-gate@cd08baa86b287f8bf4011b19708fdd91502e082d -
Branch / Tag:
refs/tags/v0.22.0 - Owner: https://github.com/tangyf07
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@cd08baa86b287f8bf4011b19708fdd91502e082d -
Trigger Event:
push
-
Statement type: