Skip to content

FEAT-001 — Controlled writes: write policy, human approval and undo #170

Done

Description

@jmmana

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, UPDATE and DELETE. No UPDATE ... FROM, no MERGE, never DDL.
  • Row filters are ANDed into UPDATE and DELETE predicates and enforced on INSERT values.
  • MCP tools, disabled unless writes is 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 a change_id.
    • apply_write(change_id) asks the person through MCP elicitation when the client supports it; otherwise it is refused unless the policy explicitly sets approval: none. It re-runs in a transaction and rolls back if the row count differs from the proposal or exceeds max_rows. Before-images go to a local ledger.
    • undo(change_id) restores the before-images and refuses on drift (rows changed since) unless force=true.
  • Engine notes:
    • SQL Server: OUTPUT deleted.*, inserted.*. Tables with enabled triggers reject OUTPUT without INTO (error 334), so use OUTPUT ... INTO @t and read the table variable.
    • PostgreSQL 18: RETURNING OLD.*, NEW.*. Earlier versions: SELECT ... FOR UPDATE with the same predicate in the same transaction.
    • MySQL 8: SELECT ... FOR UPDATE in the same transaction.

Security impact

  • Writes are off unless writes is 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

  • WritePolicy in Policy and schema/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_write and undo with 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 INTO another table, triggers).
  • Demo: an agent deletes rows and undo restores 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.json
  • docs/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)

  1. A1. sqlguardllm does not currently hold a DB connection in Guard; execution lives in the host app or in mcp_server.py. The propose_write / apply_write tools therefore need an injected "executor" (connection factory), not a URL stored in the policy. I did not see mcp_server.py in the excerpts, so its current shape is assumed.
  2. A2. check_statements() currently returns WRITE_OPERATION for any non-query statement. I assume check() stays exactly as is, and writes go only through the new check_write(), so that read-only callers can never reach write code paths.
  3. A3. The ledger is local SQLite (stdlib sqlite3), so no new dependency.
  4. A4. New violation codes are additive; the stability promise ("codes never change within a major version") allows adding codes.
  5. A5. Tables are identified using the existing TableName / parse_table_entry / find helpers, including default_schema handling.

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 question

Per-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:

  1. Parse (same try/except as _analyze: SqlglotError, TypeError, ValueError, RecursionError become PARSE_ERROR; never raise on untrusted input).
  2. Exactly one statement. Root must be exp.Insert, exp.Update or exp.Delete. Anything else (including Merge, DDL, Command) becomes WRITE_NOT_ALLOWED, regardless of policy.
  3. Reject unsupported shapes in v1, each with WRITE_NOT_ALLOWED:
    • UPDATE ... FROM, multi-table DELETE/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, INTO clauses supplied by the caller. The guard adds its own capture clause; user-supplied ones are rejected (corpus item "OUTPUT INTO another table").
    • INSERT ... SELECT, INSERT ... DEFAULT VALUES pending a decision (open question 3). Safest v1 is INSERT ... VALUES only.
    • Locking hints, TOP/LIMIT/ORDER BY on the write (open question).
  4. Table resolution: the single target must resolve via find(...) to a table in writes.tables with the requested operation enabled (WRITE_NOT_ALLOWED).
  5. Columns: every SET target and every INSERT column list entry must be in the allowed set (WRITE_COLUMN_NOT_ALLOWED). INSERT without 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 the WHERE/SET expressions (reuse check_columns-style logic on the predicate and on SET right-hand sides, so a write cannot become a read oracle for hidden columns).
  6. Functions and subqueries in SET/VALUES/WHERE: run check_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).
  7. require_where: for UPDATE/DELETE, missing WHERE becomes MISSING_WHERE. A tautological WHERE 1=1 still passes this syntactic check; the real backstop is max_rows plus the row-filter predicate, which is why max_rows is enforced from the actual affected count, not syntax.
  8. Row filters for the target table: compile the existing filter template with the context, then AND it into the WHERE as (user_where) AND (filter). The user predicate must be parenthesized so that OR cannot escape the filter. This reuses compile_filter / the same context-binding and MISSING_CONTEXT / INVALID_CONTEXT behavior.
  9. INSERT values: 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.
  10. 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 to OUTPUT ... INTO @t with a table variable, then SELECT from it. The trigger check can be a metadata query in the execution layer (sys.triggers), or the layer can always use the INTO @t form on tsql (simpler, one code path, slightly more verbose). Suggest always using INTO @t to avoid a metadata race.
  • postgres >= 18: RETURNING OLD.*, NEW.*.
  • postgres < 18 and mysql: SELECT ... FOR UPDATE with the same predicate in the same transaction, then the write. This needs the executor to know the server version (assumption A6: executor exposes a server_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, via finally) -> if count > max_rows, return TOO_MANY_ROWS, no change_id issued. Otherwise store a pending proposal (sql hash, rewritten sql, expected count, context fingerprint, expiry) and return change_id.
  • apply_write(change_id): look up proposal, check not expired/not already applied, request approval (MCP elicitation if client supports it; else refuse unless approval: none). Re-run check_write on the stored SQL with the current context (do not trust stored rewritten SQL blindly), execute in a transaction, compare count to the proposal and to max_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 unless force=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

  1. added
    type:feature
    area:core
    area:security
    size:l
    on Nov 30, 2026
  2. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    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.

  3. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    /warcodex proveedor=claude cuenta="Warlock"

  4. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: esperará a que terminen #171 antes de empezar.

  5. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex no puede empezar todavía: falta información en el issue.

    • ¿Cuál es el objetivo? Describe el cambio y su motivo en pocas líneas (un solo resultado).
    • ¿Cómo sabremos que terminó? Añade criterios de aceptación como casillas - [ ] ..., cada una verificable con un comando o una prueba.
    • ¿En qué archivos relevantes hay que trabajar y qué pruebas deben seguir pasando?

    Edita el issue (usa la plantilla de WarCodex) y lo reviso de nuevo automáticamente.

  6. added
    p1
    and removed on Nov 30, 2026
  7. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: gracias, el issue ya está completo. Encolado, posición null.

  8. 22 remaining items

  9. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    All acceptance criteria are met, each with merged PRs and green checks:

    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 apply refuse, INSERT undo is not supported yet. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:securityp1size:ltype:featurewarcodex:listo

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions