You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit e131dfb
Browse filesBrowse the repository at this point in the historyBrowse files
fix(sql): restrict a reused read-only role instead of trusting it
Provisioning changed only the password of a role that already existed, so
an existing SUPERUSER, CREATEDB, CREATEROLE, REPLICATION or BYPASSRLS
role kept those attributes, and a member of pg_read_server_files kept the
ability to call pg_read_file, no matter what the SELECT-only grant says.
An existing role is now treated as untrusted input: restriction_statements()
revokes those attributes and every privilege on the database, the public
schema, tables, sequences and functions; _revoke_memberships() drops each
direct membership; only then are CONNECT/USAGE/SELECT granted back. A role
that owns the database is refused (an owner can grant itself anything) and
_assert_restricted() verifies the outcome, raising ReadonlyRoleConfigError
instead of reporting a privileged role as provisioned.
The tool no longer trusts the provisioner alone. _enforce_read_only_session
checks rolsuper, rolbypassrls and membership of the privileged predefined
roles in one round trip (pg_has_role, so indirect membership counts) and
refuses before the query runs. The statement lexer re-exposes plain quoted
identifiers to the function denylist, because PostgreSQL resolves
SELECT "pg_read_file"(...) to the same built-in; keyword scans keep masking
identifiers so SELECT "delete" FROM t stays valid.
Verified against the live stack: the new real test grants CREATEDB plus
pg_read_server_files and provisioning strips both, and the full real-infra
suite passes.
Closes AUDIT-20; recorded in ADR-020.
Copy file name to clipboardExpand all lines: docs/ARCHITECTURE.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -113,7 +113,7 @@ sequenceDiagram
113
113
## 4. Security & Safety Guardrails
114
114
115
115
-**AST Calculator**: Only safe AST node evaluations are allowed. `eval()` and `exec()` are strictly banned.
116
-
-**Read-Only SQL**: The `sql_readonly` tool connects with a dedicated non-superuser role (`DATABASE_READONLY_URL`) whose sessions default to `default_transaction_read_only`, and every session issues `SET TRANSACTION READ ONLY`; a superuser connection is refused, and a missing URL fails closed instead of borrowing the application role. On top of that, a statement lexer accepts only a single `SELECT`/`WITH` statement and rejects DDL/DML, multi-statement injection, comment trickery, and privileged built-ins such as `pg_read_file`, `setval` or `query_to_xml`. Output is bounded in SQL: an existing `LIMIT ALL`/oversized `LIMIT` is clamped to the configured maximum.
116
+
-**Read-Only SQL**: The `sql_readonly` tool connects with a dedicated non-superuser role (`DATABASE_READONLY_URL`) whose sessions default to `default_transaction_read_only`, and every session issues `SET TRANSACTION READ ONLY`; a superuser connection, a role with `BYPASSRLS` and a role that inherits a privileged predefined role (`pg_read_server_files`, `pg_execute_server_program`, `pg_signal_backend`, …) are all refused, and a missing URL fails closed instead of borrowing the application role. The provisioning script strips those privileges from a reused role and verifies the result. On top of that, a statement lexer accepts only a single `SELECT`/`WITH` statement and rejects DDL/DML, multi-statement injection, comment trickery, and privileged built-ins such as `pg_read_file`, `setval` or `query_to_xml` — including when the name is written as a quoted identifier (`SELECT "pg_read_file"(…)`). Output is bounded in SQL: an existing `LIMIT ALL`/oversized `LIMIT` is clamped to the configured maximum.
117
117
-**Path Traversal Protection**: `read_file` validates resolved canonical paths against a configured root directory (`FILE_TOOL_BASE_DIR`). Symlink escapes outside base dir are rejected.
-**Untrusted Tool Outputs**: Tool outputs are always fed back as distinct tool-role messages, never interpolated into the system prompt, mitigating prompt injection.
Copy file name to clipboardExpand all lines: docs/AUDIT.md
+1Lines changed: 1 addition & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -103,3 +103,4 @@ fixed on top of the same stack rather than in a separate follow-up.
103
103
| Finding | Severity | Branch | Resolution |
104
104
|:---|:---:|:---|:---|
105
105
| AUDIT-19 Datastore credentials interpolated into URLs | High/Deployment |`fix/pg-url-credentials`| Credentials configured as components and percent-encoded by `URL.create()`; an explicit URL still wins |
106
+
| AUDIT-20 Reused read-only role keeps inherited privileges | High |`fix/readonly-role-privileges`| Provisioning revokes attributes, memberships and non-`SELECT` grants and verifies the result; the tool also refuses `BYPASSRLS` and privileged memberships per session |
Copy file name to clipboardExpand all lines: docs/DECISIONS.md
+17Lines changed: 17 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -306,3 +306,20 @@ This log records significant architectural, technical, and design decisions made
306
306
- A deployment that pins a full URL is unaffected, and the compose stack no longer depends on shell-style nested interpolation, which is easier to reason about and to render with `docker compose config`.
307
307
- The `.env.example` and README no longer teach a hand-built URL containing a password, so the unsafe pattern is not the first thing a new deployment copies.
308
308
- This supersedes the last consequence of ADR-018: the credential guard no longer demands a password inside `REDIS_URL`, because a credential-less URL plus `REDIS_PASSWORD` is the documented, tested form.
309
+
310
+
---
311
+
312
+
## ADR-020: A Reused Read-Only Role Is Restricted and Verified
313
+
314
+
-**Date**: 2026-10-26
315
+
-**Status**: Accepted
316
+
-**Context**: `scripts/init_readonly_role.py` created the role or, when it already existed, only changed its password: `ALTER ROLE %I WITH LOGIN PASSWORD %L`. Everything the role had accumulated stayed in place. A role that was a `SUPERUSER`, held `CREATEDB`, owned `INSERT`/`CREATE` grants, or was a member of `pg_read_server_files` therefore kept far more than the `SELECT`-only contract the docs promise. Membership is the sharpest case: `SELECT "pg_read_file"('/etc/passwd')` passes the statement lexer (it is a legitimate read of a privileged built-in, and the masker blanks quoted identifiers) and only the role's privileges stand between the agent and the host filesystem. `_enforce_read_only_session` rejected superusers and nothing else.
317
+
-**Decision**:
318
+
- Provisioning treats an existing role as untrusted input. `restriction_statements()` revokes `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION` and `BYPASSRLS`, then revokes all privileges on the database, the `public` schema, all tables, sequences and functions; `_revoke_memberships()` drops every direct membership; only then are `CONNECT`, `USAGE` and `SELECT` granted back.
319
+
- The script refuses a role that owns the target database, because an owner can grant itself anything, and it verifies the outcome with `_assert_restricted()`, raising `ReadonlyRoleConfigError` instead of reporting a role as provisioned when it is not.
320
+
- The tool checks the same properties per session, in one round trip: `rolsuper`, `rolbypassrls`, and membership in `pg_read_server_files`, `pg_write_server_files`, `pg_execute_server_program`, `pg_signal_backend`, `pg_monitor` or `pg_maintain`, resolved through `pg_has_role` so indirect membership counts. Any hit is a `ToolSecurityError` before the query runs.
321
+
- The statement lexer re-exposes plain quoted identifiers to the function denylist (and only there), because PostgreSQL resolves `"pg_read_file"` to the same function as `pg_read_file`. Keyword scans keep masking identifiers, so `SELECT "delete" FROM t` stays valid.
322
+
-**Consequences**:
323
+
- Re-running the provisioner is safe and now converges a pre-existing role to read-only instead of inheriting its history.
324
+
- A deployment that cannot restrict its role fails loudly at provisioning time, and one that skips provisioning still fails closed at query time.
325
+
-`REVOKE ALL … ON ALL FUNCTIONS` also drops function `EXECUTE` grants the role may have relied on; the tool only needs `SELECT`, and a function call in a projection still works through `PUBLIC` execute grants.
Copy file name to clipboardExpand all lines: docs/PROGRESS.md
+6Lines changed: 6 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -483,3 +483,9 @@ This document tracks execution progress across all backlog tasks, including pull
483
483
-**PR**: stacked on `fix/real-infra-redis-auth` — PR #84
484
484
-**Commits**: 1
485
485
- **Notes**: Compose built `DATABASE_URL` and `DATABASE_READONLY_URL` by pasting `${POSTGRES_PASSWORD}` and `${POSTGRES_READONLY_PASSWORD}` into a URL, and `REDIS_URL` the same way. The documented generator is `openssl rand -base64 24`, which emits `/`, `+` and `=`: an RFC 3986 parser ends the authority at the first `/`, so the rest of the password becomes the path, and SQLAlchemy's `make_url` truncates the secret at an `@`. Credentials are now configured as components (`POSTGRES_HOST`/`PORT`/`USER`/`PASSWORD`/`DB` plus `POSTGRES_READONLY_*`), and `build_postgres_url()` renders the URL through SQLAlchemy's `URL.create()` so every component is escaped; `resolve_postgres_url()` is the single precedence rule — an explicit `DATABASE_URL`/`DATABASE_READONLY_URL` wins verbatim, then the components, then the documented development default. `Settings` applies it in its validator and `scripts/check_deploy_credentials.py` calls the same functions, so the guard audits exactly the URLs the application uses (and no longer demands a password inside `REDIS_URL`, since `REDIS_PASSWORD` supplies it). Compose passes components only and fixes the datastore host/port to the service names, so a host-side `.env` pointing at `localhost` cannot leak into a container. `.env.example`, README, `docs/DEPLOY.md` (including the SSM-generated `.env`) and `docs/SPEC.md` describe the component form instead of hand-built URLs. Covered by `tests/unit/test_database_url_components.py` (escaping and round-trip, precedence, dotenv input, guard parity, compose and `.env.example` shape). Recorded in ADR-019.
486
+
487
+
### AUDIT-20: Reused Read-Only Role Keeps Its Privileges
488
+
-**Status**: Done
489
+
-**PR**: stacked on `fix/pg-url-credentials` — PR #84
490
+
-**Commits**: 1
491
+
- **Notes**: `scripts/init_readonly_role.py` changed only the password of a role that already existed, so a pre-existing `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION` or `BYPASSRLS` role — or one that was a member of `pg_read_server_files` — kept everything the documented `SELECT`-only contract says it does not have. Provisioning now restricts first: `restriction_statements()` revokes those attributes and all privileges on the database, the `public` schema, tables, sequences and functions, `_revoke_memberships()` drops every direct membership, and only then are `CONNECT`/`USAGE`/`SELECT` granted back. It refuses a role that owns the target database (an owner can grant itself anything) and `_assert_restricted()` verifies the outcome, raising `ReadonlyRoleConfigError` rather than reporting a privileged role as provisioned. The tool checks the same properties per session in one round trip — `rolsuper`, `rolbypassrls` and membership of `pg_read_server_files`, `pg_write_server_files`, `pg_execute_server_program`, `pg_signal_backend`, `pg_monitor` or `pg_maintain`, resolved through `pg_has_role` so indirect membership counts — and refuses before the query runs. The statement lexer also re-exposes plain quoted identifiers to the function denylist, because PostgreSQL resolves `SELECT "pg_read_file"(…)` to the same built-in; keyword scans keep masking identifiers so `SELECT "delete" FROM t` stays valid. Covered by `tests/unit/test_readonly_role_provisioning.py`, new payloads in `tests/unit/test_sql_isolation.py`, and `tests/real/test_sql_isolation_real.py::test_reused_role_has_its_privileges_stripped`, which grants `CREATEDB` plus `pg_read_server_files` to the role and asserts provisioning strips both. Recorded in ADR-020.
0 commit comments