Repository navigation
Description
Parent epic: #165
Priority: P1
Objetivo
Agents increasingly need to change data (update a status, insert a record). sqlguardllm rejects every write, so teams either give agents raw write access or none. Existing "undo for agents" projects target PostgreSQL, MySQL or SQLite; none covers SQL Server.
Problem
Agents increasingly need to change data (update a status, insert a record). sqlguardllm rejects every write, so teams either give agents raw write access or none. Existing "undo for agents" projects target PostgreSQL, MySQL or SQLite; none covers SQL Server.
Proposal
from sqlguardllm import Guard, Policy, WritePolicy
policy = Policy(
dialect="tsql",
tables={"orders", "customers"},
row_filters={"orders": "tenant_id = {user.tenant_id}"},
writes=WritePolicy(
tables={"orders": {"update": ["status", "notes"], "insert": True, "delete": False}},
max_rows=50,
require_where=True,
),
)
result = guard.check_write("UPDATE orders SET status = 'cancelled' WHERE id = 42", context)
# result.sql (sketch):
# UPDATE orders SET status = 'cancelled'
# OUTPUT deleted.*, inserted.*
# WHERE id = 42 AND tenant_id = 7- v1 scope: single-table
INSERT,UPDATEandDELETE. NoUPDATE ... FROM, noMERGE, never DDL. - Row filters are ANDed into
UPDATEandDELETEpredicates and enforced onINSERTvalues. - MCP tools, disabled unless
writesis configured:propose_write(sql)validates, runs inside a transaction that is always rolled back, and returns the exact affected-row count, a before/after preview of the first rows, and achange_id.apply_write(change_id)asks the person through MCP elicitation when the client supports it; otherwise it is refused unless the policy explicitly setsapproval: none. It re-runs in a transaction and rolls back if the row count differs from the proposal or exceedsmax_rows. Before-images go to a local ledger.undo(change_id)restores the before-images and refuses on drift (rows changed since) unlessforce=true.
- Engine notes:
- SQL Server:
OUTPUT deleted.*, inserted.*. Tables with enabled triggers rejectOUTPUTwithoutINTO(error 334), so useOUTPUT ... INTO @tand read the table variable. - PostgreSQL 18:
RETURNING OLD.*, NEW.*. Earlier versions:SELECT ... FOR UPDATEwith the same predicate in the same transaction. - MySQL 8:
SELECT ... FOR UPDATEin the same transaction.
- SQL Server:
Security impact
- Writes are off unless
writesis set; the read-only default is unchanged. DDL is never allowed. - Recommend a separate database credential for writes.
- The ledger holds row data: restrictive file permissions, retention setting and a purge command.
- Any capture failure or row-count mismatch rolls back (fail closed).
Criterios de aceptación
-
WritePolicyinPolicyandschema/policy.schema.json;check_write()with stable violation codes (write_not_allowed,write_column_not_allowed,missing_where,too_many_rows). - Row filters applied to writes, with tests.
- MCP tools
propose_write,apply_writeandundowith elicitation; off unless configured. - Engine tests: SQL Server (including a table with a trigger), PostgreSQL 16 and 18, MySQL 8.
- Threat model and corpus updated (writes hidden in CTEs,
OUTPUT INTOanother table, triggers). - Demo: an agent deletes rows and
undorestores them.
Archivos relevantes
Pruebas que deben seguir pasando: uv run ruff check src tests, uv run ruff format --check src tests, uv run mypy, uv run pytest (incluye el corpus adversarial). No tocar los PR #155 y #156, las versiones de los paquetes ni .github/workflows/release.yml.
Archivos:
src/sqlguardllm/rules/writes.py(new) ·src/sqlguardllm/ledger.py(new)src/sqlguardllm/policy.py·guard.py·mcp_server.py·schema/policy.schema.jsondocs/WRITES.md(new)
Size
L
Claude API proposal (AGENTS.md)
Workflow run: https://github.com/jmmana/sqlguardllm/actions/runs/46437743446 · model claude-sonnet-5-5 · see manifest in the run artifact. Review against the code; model output is not validation evidence. Do not publish or reference unreleased third-party vulnerabilities.
proposal.md
Proposal: Controlled writes (FEAT-001, #170)
Scope note: this is a suggestion for a maintainer to review. Issue and file text were treated as reference material only. I have not run anything against the repo or any engine.
Goal
Let a deployment opt in to narrow, auditable single-table writes (INSERT, UPDATE, DELETE) without weakening the read-only default. Every write must be validated against a WritePolicy, previewed in a rolled-back transaction, approved, applied with a row-count check, and reversible from a local before-image ledger.
The issue is size L, so the suggestion is to land it as three reviewable PRs (see "Staging"). The first is the part that carries the security argument: static validation and rewriting in check_write().
Assumptions (please confirm or correct)
- A1.
sqlguardllmdoes not currently hold a DB connection inGuard; execution lives in the host app or inmcp_server.py. Thepropose_write/apply_writetools therefore need an injected "executor" (connection factory), not a URL stored in the policy. I did not seemcp_server.pyin the excerpts, so its current shape is assumed. - A2.
check_statements()currently returnsWRITE_OPERATIONfor any non-query statement. I assumecheck()stays exactly as is, and writes go only through the newcheck_write(), so that read-only callers can never reach write code paths. - A3. The ledger is local SQLite (stdlib
sqlite3), so no new dependency. - A4. New violation codes are additive; the stability promise ("codes never change within a major version") allows adding codes.
- A5. Tables are identified using the existing
TableName/parse_table_entry/findhelpers, includingdefault_schemahandling.
Files to change
| File | Change |
|---|---|
src/sqlguardllm/policy.py |
Add frozen WritePolicy; add Policy.writes: WritePolicy | None = None; validate in __post_init__; accept in from_dict (nested dict -> WritePolicy). |
src/sqlguardllm/result.py |
Add ViolationCode members: WRITE_NOT_ALLOWED, WRITE_COLUMN_NOT_ALLOWED, MISSING_WHERE, TOO_MANY_ROWS. Add WriteCheckResult. |
src/sqlguardllm/_compiled.py |
Add compiled write rules (normalized TableName -> allowed ops/columns). |
src/sqlguardllm/guard.py |
_compile handles policy.writes; add Guard.check_write(). check() is untouched. |
src/sqlguardllm/rules/writes.py (new) |
Statement-shape validation, column checks, WHERE requirement, row-filter AND-ing, INSERT value enforcement, per-dialect capture SQL. |
src/sqlguardllm/ledger.py (new) |
Local ledger: before-images, change records, retention, purge. |
src/sqlguardllm/mcp_server.py |
Register propose_write / apply_write / undo only when writes is configured. |
src/sqlguardllm/messages.py |
en/es messages for the new codes. |
schema/policy.schema.json |
Add writes object. |
docs/WRITES.md (new), docs/THREAT_MODEL.md |
Describe writes, add threat-model rows. |
tests/..., tests/corpus/... |
See Tests. |
Proposed implementation
1. WritePolicy (policy.py)
@dataclass(frozen=True)
class WritePolicy:
tables: Mapping[str, TableWriteRules] # or plain mapping validated on init
max_rows: int = 50
require_where: bool = True
approval: Literal["required", "none"] = "required" # name is an open questionPer-table rules: update: Collection[str] (allowed columns, empty or absent means no update), insert: bool, delete: bool. Validation mirrors existing style (PolicyError, reject bool-as-int, non-empty strings). Write tables must also be in Policy.tables when that allowlist is set, as with row_filters. Default is secure: delete defaults to False, insert to False.
approval is the only knob that weakens the human-in-the-loop, so it should be spelled out and never default to "none". Making max_rows default to 50 rather than reusing the read max_rows avoids accidentally inheriting 1000.
2. Guard.check_write(sql, context)
Pipeline, fail closed at every step:
- Parse (same try/except as
_analyze:SqlglotError,TypeError,ValueError,RecursionErrorbecomePARSE_ERROR; never raise on untrusted input). - Exactly one statement. Root must be
exp.Insert,exp.Updateorexp.Delete. Anything else (includingMerge, DDL,Command) becomesWRITE_NOT_ALLOWED, regardless of policy. - Reject unsupported shapes in v1, each with
WRITE_NOT_ALLOWED:UPDATE ... FROM, multi-tableDELETE/UPDATE, joins in the write target.- Any
exp.With/ CTE attached to the statement (the issue's corpus item "writes hidden in CTEs"). Simplest safe rule: reject CTEs on write statements entirely in v1. OUTPUT,RETURNING,INTOclauses supplied by the caller. The guard adds its own capture clause; user-supplied ones are rejected (corpus item "OUTPUT INTOanother table").INSERT ... SELECT,INSERT ... DEFAULT VALUESpending a decision (open question 3). Safest v1 isINSERT ... VALUESonly.- Locking hints,
TOP/LIMIT/ORDER BYon the write (open question).
- Table resolution: the single target must resolve via
find(...)to a table inwrites.tableswith the requested operation enabled (WRITE_NOT_ALLOWED). - Columns: every
SETtarget and everyINSERTcolumn list entry must be in the allowed set (WRITE_COLUMN_NOT_ALLOWED).INSERTwithout an explicit column list is rejected (needs a schema to be safe). Also check that hidden/masked columns from the read policy cannot be written or used in theWHERE/SETexpressions (reusecheck_columns-style logic on the predicate and onSETright-hand sides, so a write cannot become a read oracle for hidden columns). - Functions and subqueries in
SET/VALUES/WHERE: runcheck_functions. Subqueries inside a write expression should be run through the existing read pipeline (_analyze) so table allowlist, hidden columns and row filters apply to them. If that proves too invasive for the first PR, reject subqueries in write statements (conservative; see open questions). require_where: forUPDATE/DELETE, missingWHEREbecomesMISSING_WHERE. A tautologicalWHERE 1=1still passes this syntactic check; the real backstop ismax_rowsplus the row-filter predicate, which is whymax_rowsis enforced from the actual affected count, not syntax.- Row filters for the target table: compile the existing filter template with the context, then
ANDit into theWHEREas(user_where) AND (filter). The user predicate must be parenthesized so thatORcannot escape the filter. This reusescompile_filter/ the same context-binding andMISSING_CONTEXT/INVALID_CONTEXTbehavior. INSERTvalues: for each filtered column that the filter pins by equality (e.g.tenant_id = {user.tenant_id}), require the inserted value to equal the bound context value, or inject it. See open question 2 for non-equality filters, which should be rejected in v1.- Capture clause generation per output dialect (below), then generate SQL via
sql(dialect=output_dialect).
WriteCheckResult: ok, sql (rewritten, capture-bearing), operation, table, violations, plus applied_filters for parity with CheckResult. too_many_rows is never produced by check_write() itself (it needs execution); it is raised by the propose/apply layer.
3. Engine capture strategy (rules/writes.py)
Keep this behind a small per-dialect function so unsupported dialects fail closed:
- tsql:
OUTPUT deleted.*, inserted.*. Because error 334 occurs when the target has enabled triggers, detect and fall back toOUTPUT ... INTO @twith a table variable, thenSELECTfrom it. The trigger check can be a metadata query in the execution layer (sys.triggers), or the layer can always use theINTO @tform on tsql (simpler, one code path, slightly more verbose). Suggest always usingINTO @tto avoid a metadata race. - postgres >= 18:
RETURNING OLD.*, NEW.*. - postgres < 18 and mysql:
SELECT ... FOR UPDATEwith the same predicate in the same transaction, then the write. This needs the executor to know the server version (assumption A6: executor exposes aserver_version). - Any other dialect:
WRITE_NOT_ALLOWED("dialect not supported for writes"). Writes only enabled for dialects with a tested capture path.
INSERT has no before-image; for undo it records the inserted keys (needs PK knowledge, see open question 4).
4. Execution layer: propose / apply / undo
Put engine interaction in a small WriteExecutor protocol (begin, execute, fetch, rollback, commit, server_version) injected by the host/MCP server. Guard stays connection-free.
propose_write(sql):check_write-> open transaction -> execute rewritten SQL with capture -> read affected count and the first N before/after rows -> always rollback (including on exception, viafinally) -> if count >max_rows, returnTOO_MANY_ROWS, nochange_idissued. Otherwise store a pending proposal (sql hash, rewritten sql, expected count, context fingerprint, expiry) and returnchange_id.apply_write(change_id): look up proposal, check not expired/not already applied, request approval (MCP elicitation if client supports it; else refuse unlessapproval: none). Re-runcheck_writeon the stored SQL with the current context (do not trust stored rewritten SQL blindly), execute in a transaction, compare count to the proposal and tomax_rows, mismatch means rollback. Persist before-images to the ledger before commit; if the ledger write fails, rollback (fail closed). Commit last.undo(change_id): restore before-images in a transaction keyed by PK; drift check compares current row values with the recorded after-image; refuse on drift unlessforce=true; refuse a second undo of the same change.
Ledger design: SQLite file, created with 0600 permissions (and parent dir 0700) on POSIX; configurable retention (days) with opportunistic purge on open plus a sqlguardllm ledger purge CLI subcommand. Store sql text, table, op, timestamp, role/user id, before/after row images. Document that it contains row data and should be treated like the database itself.
Note a TOCTOU gap worth documenting: between propose and apply the data can change; the row-count equ
Activity
docs: define controlled write transaction and approval invariants (#170)
jmmana commentedon Nov 30, 2026
Draft #178 records the controlled-write transaction, approval, and undo invariants. Baseline on main f4144e6: Ruff lint and format checks, mypy, and pytest passed locally; environment-dependent tests skipped normally. These results are baseline only. No write implementation or engine acceptance tests yet. CI is running for the draft. The repository mandates a Claude API proposal/review for coding; no paid service was used. This issue remains open.
jmmana commentedon Nov 30, 2026
/warcodex proveedor=claude cuenta="Warlock"
jmmana commentedon Nov 30, 2026
WarCodex: esperará a que terminen #171 antes de empezar.
jmmana commentedon Nov 30, 2026
WarCodex no puede empezar todavía: falta información en el issue.
- [ ] ..., cada una verificable con un comando o una prueba.Edita el issue (usa la plantilla de WarCodex) y lo reviso de nuevo automáticamente.
jmmana commentedon Nov 30, 2026
WarCodex: gracias, el issue ya está completo. Encolado, posición null.
22 remaining items
fix(write-runtime): named binds instead of ? so PostgreSQL, MySQL and…
test(engines): a realistic SQL Server trigger; document the NOCOUNT l…
test(engines): controlled writes on SQL Server, PostgreSQL and MySQL (#…
Controlled writes demo, its test, and a PostgreSQL 18 write job (#170) (
docs(threat-model): the write execution layer now exists (#170) (#199)
jmmana commentedon Nov 30, 2026
All acceptance criteria are met, each with merged PRs and green checks:
WritePolicyinPolicyandschema/policy.schema.json;check_write()withwrite_not_allowed,write_column_not_allowed,missing_where,too_many_rows(FEAT-001 — Controlled writes: write policy, human approval and undo (#170) #188).propose_write,apply_write,undowith elicitation; registered only withwritesand a separate write database (FEAT-001 — MCP tools propose_write, apply_write and undo with human approval (#170) #196). A decline, cancel, error, malformed answer or a client without elicitation refuses and changes nothing.?binds), fixed in test(engines): controlled writes on SQL Server, PostgreSQL and MySQL (#170) #197.OUTPUT ... INTOanother table, whole-row references, filter-column moves, triggers) are intests/test_writes.py,tests/test_writes_hardening.pyand the engine tests rather than intests/corpus/*.yaml, whose format is forcheck().examples/writes_demo.py(an agent deletes rows, a client that cannot ask is refused, approval, thenundorestores them), run by the test-suite. It is a runnable script and a text transcript, not a video.Three Claude Sonnet 5.5 security reviews drove fixes before merge (undo could write columns the policy does not allow, a tampered ledger, a propose that ran DML, approval waived or faked through a fallback path). Known limits, documented in docs/WRITES.md and the threat model: the ledger holds row data (DELETE images include hidden columns), SQLite has no row lock, a trigger that alters the driver's row count makes
applyrefuse, INSERT undo is not supported yet. Closing.docs: define controlled write transaction and approval invariants (#170…
FEAT-001 — Controlled writes: write policy, human approval and undo (#…
FEAT-001 — write runtime and signed ledger: propose, apply, undo (#170)…
FEAT-001 — MCP tools propose_write, apply_write and undo with human a…
test(engines): controlled writes on SQL Server, PostgreSQL and MySQL (#…
Controlled writes demo, its test, and a PostgreSQL 18 write job (#170) (
docs(threat-model): the write execution layer now exists (#170) (#199)