Skip to content

Commit e131dfb

Browse 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.
1 parent 75f14d1 commit e131dfb

10 files changed

Lines changed: 423 additions & 12 deletions

File tree

‎agentkit/tools/builtin/sql_readonly.py‎

Lines changed: 86 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
a dedicated non-superuser role whose ``default_transaction_read_only`` is ``on``. The tool
88
refuses to run when that URL is absent and never falls back to the application's own
99
``DATABASE_URL``; each session additionally issues ``SET TRANSACTION READ ONLY`` and
10-
rejects a superuser connection before executing anything.
10+
rejects a superuser connection, a ``BYPASSRLS`` role and a role that inherits a privileged
11+
predefined role before executing anything.
1112
2. **Statement validation (defence in depth).** Only a single ``SELECT``/``WITH`` statement is
1213
accepted, comments are rejected, side-effecting and file-reading built-ins are denied, and
1314
the output is bounded in SQL so the server cannot compute an unbounded result.
@@ -107,6 +108,24 @@
107108
"dblink_disconnect",
108109
)
109110

111+
#: Predefined roles whose membership grants more than reading rows: server-side file access,
112+
#: program execution, backend control or monitoring. A role that inherits one of them can do
113+
#: things ``SELECT`` should not allow — ``pg_read_file`` is reachable through
114+
#: ``pg_read_server_files`` — so the connection is refused rather than trusted.
115+
DANGEROUS_ROLE_MEMBERSHIPS = (
116+
"pg_read_server_files",
117+
"pg_write_server_files",
118+
"pg_execute_server_program",
119+
"pg_signal_backend",
120+
"pg_monitor",
121+
"pg_maintain",
122+
)
123+
124+
#: A quoted identifier that spells an ordinary name. Those are re-exposed to the function scan
125+
#: (``SELECT "pg_read_file"('...')`` is a real call), while identifiers that contain anything
126+
#: else stay masked so their contents can never look like SQL structure.
127+
_PLAIN_IDENTIFIER_REGEX = re.compile(r"^[A-Za-z_][A-Za-z0-9_$]*$")
128+
110129
_KEYWORD_REGEX = re.compile(
111130
r"\b(" + "|".join(DISALLOWED_KEYWORDS) + r")\b",
112131
re.IGNORECASE,
@@ -240,8 +259,10 @@ def validate_sql_query(query: str) -> str:
240259
raise ValueError(f"Query contains prohibited SQL keyword(s): {', '.join(prohibited)}")
241260

242261
# Prohibited built-ins are function calls, not keywords, so they need their own scan. The
243-
# mask means the name only counts when it appears in SQL structure, never inside data.
244-
function_matches = _FUNCTION_REGEX.findall(structural)
262+
# name only counts when it appears in SQL structure, never inside data — but a quoted
263+
# identifier is structure: PostgreSQL resolves "pg_read_file" exactly like pg_read_file,
264+
# so plain identifiers are re-exposed here while everything else stays masked.
265+
function_matches = _FUNCTION_REGEX.findall(_mask_literals(cleaned, unquote_identifiers=True))
245266
if function_matches:
246267
prohibited_functions = sorted({m.lower() for m in function_matches})
247268
raise ValueError(
@@ -251,13 +272,22 @@ def validate_sql_query(query: str) -> str:
251272
return cleaned
252273

253274

254-
def _mask_literals(sql: str) -> str:
275+
def _mask_literals(sql: str, *, unquote_identifiers: bool = False) -> str:
255276
"""Replace string literals, quoted identifiers and dollar quotes with blanks.
256277
257278
Keeps every structural scan focused on SQL syntax instead of matching words that merely
258279
appear inside a quoted value or a quoted column name. The mask preserves string length so
259280
offsets computed on masked text remain valid for the original statement.
260281
282+
Args:
283+
sql: Statement to mask.
284+
unquote_identifiers: Re-expose plain quoted identifiers (``"name"`` → ``name``)
285+
instead of blanking them. Used only by the function scan: PostgreSQL resolves a
286+
quoted identifier to the same object as the bare name, so ``SELECT
287+
"pg_read_file"('...')`` is a real call to the built-in. Left off everywhere else,
288+
where an identifier spelled like a keyword (``SELECT "delete" FROM t``) must not
289+
be read as SQL structure.
290+
261291
Three PostgreSQL quoting forms are handled, because each one can otherwise smuggle a
262292
keyword or a statement separator past a naive scanner:
263293
@@ -287,6 +317,12 @@ def _mask_literals(sql: str) -> str:
287317

288318
if char == '"':
289319
end = _quoted_end(sql, index, '"', backslash_escapes=False)
320+
if unquote_identifiers and end - index >= 2 and sql[end - 1] == '"':
321+
identifier = sql[index + 1 : end - 1].replace('""', '"')
322+
if _PLAIN_IDENTIFIER_REGEX.match(identifier):
323+
masked.append(identifier + " " * (end - index - len(identifier)))
324+
index = end
325+
continue
290326
masked.append(" " * (end - index))
291327
index = end
292328
continue
@@ -428,14 +464,18 @@ async def _enforce_read_only_session(conn: AsyncConnection, *, strict: bool) ->
428464
``SET TRANSACTION READ ONLY`` is belt-and-braces on top of the role's
429465
``default_transaction_read_only``: even a misconfigured role cannot write through this
430466
connection. The role check is the runtime half of the isolation guarantee — a superuser
431-
URL accidentally configured as ``DATABASE_READONLY_URL`` is refused before any query runs.
467+
URL accidentally configured as ``DATABASE_READONLY_URL`` is refused before any query runs,
468+
and so is a role that *inherits* the privileges ``SELECT`` should not reach. Inherited
469+
membership is the case the provisioner cannot see in a deployment that reuses a
470+
pre-existing role, so it is checked here, per session, as well.
432471
433472
Args:
434473
conn: Connection about to run the query. Must be in a fresh transaction.
435474
strict: Whether this is the tool's own configured engine (subject to the role check).
436475
437476
Raises:
438-
ToolSecurityError: If a strict connection is a superuser.
477+
ToolSecurityError: If a strict connection cannot be verified, is a superuser, has
478+
``BYPASSRLS``, or is a member of a privileged predefined role.
439479
"""
440480
if conn.dialect.name != "postgresql":
441481
return
@@ -444,11 +484,30 @@ async def _enforce_read_only_session(conn: AsyncConnection, *, strict: bool) ->
444484
if not strict:
445485
return
446486

447-
is_superuser = (
487+
# One round trip: the attributes and any dangerous membership, resolved through
488+
# pg_has_role so indirect membership counts too. Roles that do not exist are skipped by
489+
# the join instead of raising, which keeps this portable across PostgreSQL versions.
490+
role_state = (
448491
await conn.execute(
449-
text("SELECT rolsuper FROM pg_roles WHERE rolname = current_user"),
492+
text(
493+
"SELECT r.rolsuper, r.rolbypassrls, "
494+
"ARRAY(SELECT g.rolname FROM pg_roles g "
495+
"WHERE g.rolname::text = ANY(:privileged) "
496+
"AND pg_has_role(current_user, g.oid, 'MEMBER')) "
497+
"FROM pg_roles r WHERE r.rolname = current_user"
498+
),
499+
{"privileged": list(DANGEROUS_ROLE_MEMBERSHIPS)},
500+
)
501+
).one_or_none()
502+
if role_state is None:
503+
logger.error("Refusing to run sql_readonly: current_user is absent from pg_roles.")
504+
raise ToolSecurityError(
505+
"The read-only SQL tool could not verify its database role. Point "
506+
"DATABASE_READONLY_URL at a dedicated non-superuser role.",
507+
tool_name="sql_readonly",
450508
)
451-
).scalar_one_or_none()
509+
510+
is_superuser, bypasses_rls, inherited = role_state
452511
if is_superuser is not False:
453512
logger.error(
454513
"Refusing to run sql_readonly: connected role is a superuser (rolsuper=%s).",
@@ -459,6 +518,24 @@ async def _enforce_read_only_session(conn: AsyncConnection, *, strict: bool) ->
459518
"DATABASE_READONLY_URL at a dedicated non-superuser role.",
460519
tool_name="sql_readonly",
461520
)
521+
if bypasses_rls:
522+
logger.error("Refusing to run sql_readonly: the role has BYPASSRLS.")
523+
raise ToolSecurityError(
524+
"The read-only SQL tool is configured with a role that has BYPASSRLS, so row-level "
525+
"security would not apply. Revoke the attribute or use a dedicated role.",
526+
tool_name="sql_readonly",
527+
)
528+
if inherited:
529+
logger.error(
530+
"Refusing to run sql_readonly: the role inherits privileged membership(s) %s.",
531+
inherited,
532+
)
533+
raise ToolSecurityError(
534+
"The read-only SQL tool is configured with a role that inherits "
535+
f"{', '.join(inherited)}. Revoke the membership (scripts/init_readonly_role.py "
536+
"does this) or use a dedicated role.",
537+
tool_name="sql_readonly",
538+
)
462539

463540

464541
async def _apply_statement_timeout(conn: AsyncConnection, timeout_s: float) -> None:

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ sequenceDiagram
113113
## 4. Security & Safety Guardrails
114114

115115
- **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.
117117
- **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.
118118
- **SSRF Protection**: `http_fetch` blocks IPv4/IPv6 private address spaces, loopback (`127.0.0.1`), link-local (`169.254.169.254`), and non-HTTP/HTTPS protocols.
119119
- **Untrusted Tool Outputs**: Tool outputs are always fed back as distinct tool-role messages, never interpolated into the system prompt, mitigating prompt injection.

‎docs/AUDIT.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,4 @@ fixed on top of the same stack rather than in a separate follow-up.
103103
| Finding | Severity | Branch | Resolution |
104104
|:---|:---:|:---|:---|
105105
| 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 |

‎docs/DECISIONS.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,3 +306,20 @@ This log records significant architectural, technical, and design decisions made
306306
- 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`.
307307
- 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.
308308
- 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.

‎docs/DEPLOY.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,15 @@ readable by anyone who can reach those ports.
275275
`POSTGRES_READONLY_USER` with `CONNECT`/`USAGE`/`SELECT` only and
276276
`default_transaction_read_only = on`. The `sql_readonly` tool connects with it and refuses to
277277
run when `DATABASE_READONLY_URL` is absent, so the agent never touches the application role.
278+
A role that already exists is *restricted*, not merely given a new password: the script
279+
revokes `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION` and `BYPASSRLS`, drops every
280+
inherited role membership (`pg_read_server_files` would otherwise allow `pg_read_file`) and
281+
revokes all non-`SELECT` object privileges before granting `SELECT` back. It then verifies
282+
the result and exits non-zero if anything remains, and it refuses a role that owns the
283+
database, because an owner can grant itself anything. At request time the tool independently
284+
refuses a superuser, a role with `BYPASSRLS`, or a role that is (directly or indirectly) a
285+
member of `pg_read_server_files`, `pg_write_server_files`, `pg_execute_server_program`,
286+
`pg_signal_backend`, `pg_monitor` or `pg_maintain`.
278287

279288
Verify the effective configuration before starting the stack:
280289

‎docs/PROGRESS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,3 +483,9 @@ This document tracks execution progress across all backlog tasks, including pull
483483
- **PR**: stacked on `fix/real-infra-redis-auth` — PR #84
484484
- **Commits**: 1
485485
- **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

Comments
 (0)