From 232b8337151287ca39d22d2c884ad0c8512bfe67 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Thu, 8 Oct 2026 00:33:27 -0700 Subject: [PATCH 01/11] QA: agent-middleware gateway/migrations/ Audit fix by Muse Code fleet instance qa5-am-gateway-migrations (Grok Bot reviews before PR). --- .../migrations/versions/022_refresh_tokens.py | 4 +- .../versions/023_human_approval_gate.py | 6 +- .../versions/024_human_approval_hardening.py | 57 +++-- gateway/tests/test_sqlite_boolean_defaults.py | 237 ++++++++++++++++++ 4 files changed, 276 insertions(+), 28 deletions(-) create mode 100644 gateway/tests/test_sqlite_boolean_defaults.py diff --git a/gateway/migrations/versions/022_refresh_tokens.py b/gateway/migrations/versions/022_refresh_tokens.py index a39a7c013..7dc7d2aca 100644 --- a/gateway/migrations/versions/022_refresh_tokens.py +++ b/gateway/migrations/versions/022_refresh_tokens.py @@ -23,7 +23,9 @@ def upgrade() -> None: "refresh_tokens", sa.Column("jti", sa.String(length=64), nullable=False), sa.Column("wallet_id", sa.String(length=50), nullable=False), - sa.Column("revoked", sa.Boolean(), nullable=False, server_default="false"), + # sa.false() renders as 0 on SQLite and false on PostgreSQL. The string + # "false" is stored as text on SQLite and reads back as true. + sa.Column("revoked", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("expires_at", sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]), diff --git a/gateway/migrations/versions/023_human_approval_gate.py b/gateway/migrations/versions/023_human_approval_gate.py index 6a2fdb051..36d17c27f 100644 --- a/gateway/migrations/versions/023_human_approval_gate.py +++ b/gateway/migrations/versions/023_human_approval_gate.py @@ -28,11 +28,13 @@ def upgrade() -> None: op.add_column( "permits", + # sa.false() renders as 0 on SQLite and false on PostgreSQL. The string + # "false" is stored as text on SQLite and reads back as true. sa.Column( "requires_human_approval", sa.Boolean(), nullable=False, - server_default="false", + server_default=sa.false(), ), ) @@ -46,7 +48,7 @@ def upgrade() -> None: sa.Column( "status", sa.String(length=16), nullable=False, server_default="pending" ), - sa.Column("simulated", sa.Boolean(), nullable=False, server_default="false"), + sa.Column("simulated", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("sentinel_action_id", sa.String(length=64), nullable=True), sa.Column("requested_at", sa.DateTime(), nullable=False), sa.Column("expires_at", sa.DateTime(), nullable=False), diff --git a/gateway/migrations/versions/024_human_approval_hardening.py b/gateway/migrations/versions/024_human_approval_hardening.py index 6b2080f08..81716c57f 100644 --- a/gateway/migrations/versions/024_human_approval_hardening.py +++ b/gateway/migrations/versions/024_human_approval_hardening.py @@ -8,14 +8,16 @@ reloaded approval reject an invoke that reused the same idempotency key with different arguments or a different current price. -2. Repair ``permits.requires_human_approval`` on SQLite. Migration 023 added - the column with ``server_default="false"`` — a plain string that SQLite - stores as the *text* ``'false'`` and then reads back through SQLAlchemy's - non-native Boolean as ``True`` (``bool("false")``). Every permit that - existed before 023 therefore reports ``requires_human_approval=True`` and - fails signature verification (the flag enters the signed payload only when - true). Postgres parses ``'false'`` as boolean false, so it is unaffected; - the repair runs on SQLite only, normalizing any non-0/1 value back to 0. +2. Repair text booleans on SQLite. Migrations 022 and 023 added + ``refresh_tokens.revoked``, ``permits.requires_human_approval``, and + ``human_approvals.simulated`` with the string server default ``"false"``. + SQLite stores that as the text ``'false'``. SQLAlchemy then reads any + non-empty text as true, so a live refresh token looks revoked, a permit + looks like it requires human approval (and fails signature verification, + because the flag enters the signed payload only when true), and a real + approval looks simulated. Postgres parses ``'false'`` as boolean false, so + it is unaffected. The repair runs on SQLite only and rewrites the known + text values in the correct direction. Unexpected text is left alone. Revision ID: 024_human_approval_hardening Revises: 023_human_approval_gate @@ -40,25 +42,30 @@ def upgrade() -> None: bind = op.get_bind() if bind.dialect.name == "sqlite": - # Existing rows backfilled by 023 hold the text 'false'. Repair only - # the known text booleans, in the correct direction, so an unexpected - # value is never silently downgraded to "approval not required" (that - # would remove a control rather than restore one). 023's server_default - # can only produce 'false', but the 'true' side is handled defensively. - op.execute( - sa.text( - "UPDATE permits SET requires_human_approval = 0 " - "WHERE typeof(requires_human_approval) = 'text' " - "AND lower(requires_human_approval) IN ('false', 'f', '0', 'no')" + # Rows created under the old string default hold the text 'false'. + # Repair only the known text booleans, in the correct direction, so an + # unexpected value is never silently turned into "not set". The old + # server default can only produce 'false', but the 'true' side is + # handled so a real true is not left as text. + for table, column in ( + ("permits", "requires_human_approval"), + ("human_approvals", "simulated"), + ("refresh_tokens", "revoked"), + ): + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 0 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('false', 'f', '0', 'no')" + ) ) - ) - op.execute( - sa.text( - "UPDATE permits SET requires_human_approval = 1 " - "WHERE typeof(requires_human_approval) = 'text' " - "AND lower(requires_human_approval) IN ('true', 't', '1', 'yes')" + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 1 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('true', 't', '1', 'yes')" + ) ) - ) def downgrade() -> None: diff --git a/gateway/tests/test_sqlite_boolean_defaults.py b/gateway/tests/test_sqlite_boolean_defaults.py new file mode 100644 index 000000000..f68415170 --- /dev/null +++ b/gateway/tests/test_sqlite_boolean_defaults.py @@ -0,0 +1,237 @@ +"""SQLite boolean columns created as false must stay false. + +refresh_tokens.revoked, permits.requires_human_approval, and +human_approvals.simulated are read through SQLAlchemy. On SQLite the text +value 'false' is read as true. These tests cover a fresh upgrade, where an +omitted column must store an integer false, and an upgrade through 024, +where text 'false' becomes false and text 'true' stays true. +""" + +from __future__ import annotations + +import asyncio +import sqlite3 + +from alembic import command +from alembic.config import Config +from sqlalchemy import Boolean, Column, MetaData, String, Table, create_engine, select + + +def _upgrade(monkeypatch, db_path, revision: str) -> None: + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + command.upgrade(Config("alembic.ini"), revision) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def _seed_wallet_and_key(db_path) -> None: + connection = sqlite3.connect(db_path) + connection.execute( + """ + INSERT INTO wallets ( + wallet_id, wallet_type, owner_key, balance, lifetime_credits, + lifetime_debits, daily_spent, auto_refill, status + ) VALUES ('w-bool', 'agent', '', 0, 0, 0, 0, 0, 'active') + """ + ) + connection.execute( + """ + INSERT INTO signing_keys (key_id, alg, public_key_b64, status) + VALUES ('k-bool', 'Ed25519', 'public', 'active') + """ + ) + connection.commit() + connection.close() + + +def _insert_permit(db_path, permit_id: str, *, approval_sql: str | None) -> None: + approval_column = "" + approval_value = "" + if approval_sql is not None: + approval_column = ", requires_human_approval" + approval_value = f", {approval_sql}" + connection = sqlite3.connect(db_path) + connection.execute( + f""" + INSERT INTO permits ( + permit_id, issuer_wallet_id, subject_wallet_id, scopes_json, + allowed_tools_json, max_credits, expires_at, nonce, status, + signature, key_id, issued_at{approval_column} + ) VALUES ( + ?, 'w-bool', 'w-bool', '[]', '[]', 10, '2030-01-01 00:00:00', + ?, 'active', 'sig', 'k-bool', '2026-01-01 00:00:00'{approval_value} + ) + """, + (permit_id, f"nonce-{permit_id}"), + ) + connection.commit() + connection.close() + + +def _read_bool(db_path, table: str, column: str, key_column: str, key: str): + engine = create_engine(f"sqlite:///{db_path}") + reflected = Table( + table, + MetaData(), + Column(key_column, String, primary_key=True), + Column(column, Boolean), + ) + with engine.connect() as connection: + value = connection.execute( + select(reflected.c[column]).where(reflected.c[key_column] == key) + ).scalar_one() + engine.dispose() + return value + + +def _typeof(db_path, table: str, column: str, key_column: str, key: str) -> str: + connection = sqlite3.connect(db_path) + row = connection.execute( + f"SELECT typeof({column}) FROM {table} WHERE {key_column} = ?", + (key,), + ).fetchone() + connection.close() + return row[0] + + +def test_024_repairs_every_text_false_boolean(tmp_path, monkeypatch): + """Text 'false' on the three string-default booleans must become false.""" + db_path = tmp_path / "boolean-repair.db" + _upgrade(monkeypatch, db_path, "023_human_approval_gate") + _seed_wallet_and_key(db_path) + _insert_permit(db_path, "p-text", approval_sql="'false'") + _insert_permit(db_path, "p-true", approval_sql="'true'") + connection = sqlite3.connect(db_path) + connection.execute( + """ + INSERT INTO refresh_tokens (jti, wallet_id, revoked, created_at, expires_at) + VALUES ('j-text', 'w-bool', 'false', '2026-01-01', '2026-02-01') + """ + ) + connection.execute( + """ + INSERT INTO refresh_tokens (jti, wallet_id, revoked, created_at, expires_at) + VALUES ('j-true', 'w-bool', 'true', '2026-01-01', '2026-02-01') + """ + ) + connection.execute( + """ + INSERT INTO human_approvals ( + approval_id, wallet_id, permit_id, tool, idempotency_key, + simulated, requested_at, expires_at + ) VALUES ( + 'a-text', 'w-bool', 'p-text', 'tool', 'idem-text', + 'false', '2026-01-01', '2026-02-01' + ) + """ + ) + connection.execute( + """ + INSERT INTO human_approvals ( + approval_id, wallet_id, permit_id, tool, idempotency_key, + simulated, requested_at, expires_at + ) VALUES ( + 'a-true', 'w-bool', 'p-true', 'tool', 'idem-true', + 'true', '2026-01-01', '2026-02-01' + ) + """ + ) + connection.commit() + connection.close() + + assert ( + _read_bool(db_path, "permits", "requires_human_approval", "permit_id", "p-text") + is True + ) + assert _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-text") is True + assert ( + _read_bool(db_path, "human_approvals", "simulated", "approval_id", "a-text") + is True + ) + + _upgrade(monkeypatch, db_path, "024_human_approval_hardening") + + assert ( + _read_bool(db_path, "permits", "requires_human_approval", "permit_id", "p-text") + is False + ) + assert _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-text") is False + assert ( + _read_bool(db_path, "human_approvals", "simulated", "approval_id", "a-text") + is False + ) + assert ( + _read_bool(db_path, "permits", "requires_human_approval", "permit_id", "p-true") + is True + ) + assert _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-true") is True + assert ( + _read_bool(db_path, "human_approvals", "simulated", "approval_id", "a-true") + is True + ) + assert ( + _typeof(db_path, "permits", "requires_human_approval", "permit_id", "p-text") + == "integer" + ) + assert _typeof(db_path, "refresh_tokens", "revoked", "jti", "j-text") == "integer" + assert ( + _typeof(db_path, "human_approvals", "simulated", "approval_id", "a-text") + == "integer" + ) + + +def test_head_omitted_boolean_defaults_read_as_false(tmp_path, monkeypatch): + """An omitted boolean must stay false after later migrations.""" + db_path = tmp_path / "boolean-default.db" + _upgrade(monkeypatch, db_path, "head") + _seed_wallet_and_key(db_path) + _insert_permit(db_path, "p-default", approval_sql=None) + connection = sqlite3.connect(db_path) + connection.execute( + """ + INSERT INTO refresh_tokens (jti, wallet_id, created_at, expires_at) + VALUES ('j-default', 'w-bool', '2026-01-01', '2026-02-01') + """ + ) + connection.execute( + """ + INSERT INTO human_approvals ( + approval_id, wallet_id, permit_id, tool, idempotency_key, + requested_at, expires_at + ) VALUES ( + 'a-default', 'w-bool', 'p-default', 'tool', 'idem-default', + '2026-01-01', '2026-02-01' + ) + """ + ) + connection.commit() + connection.close() + + reads = { + "requires_human_approval": _read_bool( + db_path, "permits", "requires_human_approval", "permit_id", "p-default" + ), + "allow_identical_repeats": _read_bool( + db_path, "permits", "allow_identical_repeats", "permit_id", "p-default" + ), + "revoked": _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-default"), + "simulated": _read_bool( + db_path, "human_approvals", "simulated", "approval_id", "a-default" + ), + } + assert reads == { + "requires_human_approval": False, + "allow_identical_repeats": False, + "revoked": False, + "simulated": False, + } + assert ( + _typeof(db_path, "permits", "requires_human_approval", "permit_id", "p-default") + == "integer" + ) + assert ( + _typeof(db_path, "refresh_tokens", "revoked", "jti", "j-default") == "integer" + ) + assert ( + _typeof(db_path, "human_approvals", "simulated", "approval_id", "a-default") + == "integer" + ) From 7a8b331c79285e2ec8e53002e107103c01a0d552 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:11:51 -0700 Subject: [PATCH 02/11] Fix legacy SQLite boolean defaults Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/docs/schema-045-rollout.md | 21 +++++ .../versions/045_sqlite_boolean_defaults.py | 50 ++++++++++++ .../test_sqlite_legacy_boolean_defaults.py | 81 +++++++++++++++++++ 3 files changed, 152 insertions(+) create mode 100644 gateway/docs/schema-045-rollout.md create mode 100644 gateway/migrations/versions/045_sqlite_boolean_defaults.py create mode 100644 gateway/tests/test_sqlite_legacy_boolean_defaults.py diff --git a/gateway/docs/schema-045-rollout.md b/gateway/docs/schema-045-rollout.md new file mode 100644 index 000000000..14c5fb0d6 --- /dev/null +++ b/gateway/docs/schema-045-rollout.md @@ -0,0 +1,21 @@ +# Schema 045: SQLite boolean defaults and rollback boundary + +Migration `045_sqlite_boolean_defaults` revises `044_receipt_resolutions`. +On SQLite it repairs legacy text booleans in refresh tokens, human approvals, +and permits, then replaces their text defaults with integer false defaults. +PostgreSQL schema and data are unchanged. + +## Compatibility release before migration + +Before an authorized rollout, confirm the database revision, back up the +database, and qualify a 045-capable recovery image. Rehearse the migration on +a copy of any SQLite database created before the corrected 022 and 023 +migrations, including existing rows and inserts that omit these columns. +The application requires its packaged Alembic head, so an older image cannot +restart after the database reaches 045. + +## Rollback after activation + +The downgrade retains corrected values and defaults. Recover with a +045-capable image and the database at 045. Returning to an older packaged +head requires a separately reviewed migration and compatibility plan. diff --git a/gateway/migrations/versions/045_sqlite_boolean_defaults.py b/gateway/migrations/versions/045_sqlite_boolean_defaults.py new file mode 100644 index 000000000..128d2c24a --- /dev/null +++ b/gateway/migrations/versions/045_sqlite_boolean_defaults.py @@ -0,0 +1,50 @@ +"""Repair legacy SQLite text booleans and replace their text defaults. + +Revision ID: 045_sqlite_boolean_defaults +Revises: 044_receipt_resolutions +""" + +from alembic import op +import sqlalchemy as sa + +revision: str = "045_sqlite_boolean_defaults" +down_revision: str = "044_receipt_resolutions" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + if op.get_bind().dialect.name != "sqlite": + return + + for table, column in ( + ("refresh_tokens", "revoked"), + ("human_approvals", "simulated"), + ("permits", "requires_human_approval"), + ): + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 0 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('false', 'f', '0', 'no')" + ) + ) + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 1 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('true', 't', '1', 'yes')" + ) + ) + with op.batch_alter_table(table) as batch_op: + batch_op.alter_column( + column, + existing_type=sa.Boolean(), + existing_nullable=False, + server_default=sa.false(), + ) + + +def downgrade() -> None: + # Corrected values and defaults must not be restored to text booleans. + pass diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py new file mode 100644 index 000000000..5aa97db84 --- /dev/null +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -0,0 +1,81 @@ +"""Legacy SQLite defaults remain safe after upgrading an existing database.""" + +import asyncio +import sqlite3 + +from alembic import command +from alembic.config import Config + + +_COLUMNS = ( + ("refresh_tokens", "revoked"), + ("human_approvals", "simulated"), + ("permits", "requires_human_approval"), +) + + +def _upgrade(monkeypatch, db_path, revision): + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + command.upgrade(Config("alembic.ini"), revision) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def _defaults(connection): + return { + (table, column): next( + row[4] + for row in connection.execute(f"PRAGMA table_info({table})") + if row[1] == column + ) + for table, column in _COLUMNS + } + + +def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): + db_path = tmp_path / "legacy-defaults.db" + _upgrade(monkeypatch, db_path, "023_human_approval_gate") + + # Reproduce the schema defaults emitted by the original 022 and 023. + with sqlite3.connect(db_path) as connection: + connection.execute("PRAGMA writable_schema = ON") + for table, column in _COLUMNS: + old = f"{column} BOOLEAN DEFAULT 0 NOT NULL" + new = f"{column} BOOLEAN DEFAULT 'false' NOT NULL" + connection.execute( + "UPDATE sqlite_master SET sql = replace(sql, ?, ?) " + "WHERE type = 'table' AND name = ?", + (old, new, table), + ) + assert connection.execute("SELECT changes()").fetchone()[0] == 1 + connection.execute("PRAGMA writable_schema = OFF") + schema_version = connection.execute("PRAGMA schema_version").fetchone()[0] + connection.execute(f"PRAGMA schema_version = {schema_version + 1}") + + _upgrade(monkeypatch, db_path, "044_receipt_resolutions") + with sqlite3.connect(db_path) as connection: + assert set(_defaults(connection).values()) == {"'false'"} + indexes = { + table: { + row[1:] for row in connection.execute(f"PRAGMA index_list({table})") + } + for table, _ in _COLUMNS + } + foreign_keys = { + table: { + row[2:] + for row in connection.execute(f"PRAGMA foreign_key_list({table})") + } + for table, _ in _COLUMNS + } + + _upgrade(monkeypatch, db_path, "head") + with sqlite3.connect(db_path) as connection: + assert set(_defaults(connection).values()) == {"0"} + for table, _ in _COLUMNS: + assert { + row[1:] for row in connection.execute(f"PRAGMA index_list({table})") + } == indexes[table] + assert { + row[2:] + for row in connection.execute(f"PRAGMA foreign_key_list({table})") + } == foreign_keys[table] From 206364d00a7e2d2a73fcea23753716ce2cbd7803 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:45:01 -0700 Subject: [PATCH 03/11] Test legacy SQLite boolean row repair Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- .../test_sqlite_legacy_boolean_defaults.py | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py index 5aa97db84..27448a067 100644 --- a/gateway/tests/test_sqlite_legacy_boolean_defaults.py +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -54,6 +54,47 @@ def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): _upgrade(monkeypatch, db_path, "044_receipt_resolutions") with sqlite3.connect(db_path) as connection: assert set(_defaults(connection).values()) == {"'false'"} + connection.execute( + "INSERT INTO wallets (wallet_id, wallet_type, owner_key, balance, " + "lifetime_credits, lifetime_debits, daily_spent, auto_refill, status) " + "VALUES ('w-legacy', 'agent', '', 0, 0, 0, 0, 0, 'active')" + ) + connection.execute( + "INSERT INTO signing_keys (key_id, alg, public_key_b64, status) " + "VALUES ('k-legacy', 'Ed25519', 'public', 'active')" + ) + connection.executemany( + "INSERT INTO permits (permit_id, issuer_wallet_id, subject_wallet_id, " + "scopes_json, allowed_tools_json, max_credits, expires_at, nonce, " + "status, signature, key_id) VALUES (?, 'w-legacy', 'w-legacy', " + "'[]', '[]', 1, '2030-01-01', ?, 'active', 'sig', 'k-legacy')", + (("p-default", "n-default"), ("p-true", "n-true")), + ) + connection.executemany( + "INSERT INTO refresh_tokens (jti, wallet_id, created_at, expires_at) " + "VALUES (?, 'w-legacy', '2026-01-01', '2026-02-01')", + (("j-default",), ("j-true",)), + ) + connection.executemany( + "INSERT INTO human_approvals (approval_id, wallet_id, permit_id, " + "tool, idempotency_key, requested_at, expires_at) " + "VALUES (?, 'w-legacy', ?, 'tool', ?, '2026-01-01', '2026-02-01')", + ( + ("a-default", "p-default", "idem-default"), + ("a-true", "p-true", "idem-true"), + ), + ) + for table, column, key in ( + ("refresh_tokens", "revoked", "jti"), + ("human_approvals", "simulated", "approval_id"), + ("permits", "requires_human_approval", "permit_id"), + ): + connection.execute( + f"UPDATE {table} SET {column} = 'true' WHERE {key} LIKE '%-true'" + ) + assert connection.execute( + f"SELECT {column}, typeof({column}) FROM {table} ORDER BY {key}" + ).fetchall() == [("false", "text"), ("true", "text")] indexes = { table: { row[1:] for row in connection.execute(f"PRAGMA index_list({table})") @@ -71,7 +112,14 @@ def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): _upgrade(monkeypatch, db_path, "head") with sqlite3.connect(db_path) as connection: assert set(_defaults(connection).values()) == {"0"} - for table, _ in _COLUMNS: + for table, column, key in ( + ("refresh_tokens", "revoked", "jti"), + ("human_approvals", "simulated", "approval_id"), + ("permits", "requires_human_approval", "permit_id"), + ): + assert connection.execute( + f"SELECT {column}, typeof({column}) FROM {table} ORDER BY {key}" + ).fetchall() == [(0, "integer"), (1, "integer")] assert { row[1:] for row in connection.execute(f"PRAGMA index_list({table})") } == indexes[table] From f992032e4b803bb8b9838dfbcc583b3cd943d5b7 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:30:38 -0700 Subject: [PATCH 04/11] Chain SQLite boolean repair after API key usage migration Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- .../{schema-045-rollout.md => schema-046-rollout.md} | 11 ++++++----- ...ean_defaults.py => 046_sqlite_boolean_defaults.py} | 8 ++++---- gateway/tests/test_sqlite_legacy_boolean_defaults.py | 7 +++++++ 3 files changed, 17 insertions(+), 9 deletions(-) rename gateway/docs/{schema-045-rollout.md => schema-046-rollout.md} (67%) rename gateway/migrations/versions/{045_sqlite_boolean_defaults.py => 046_sqlite_boolean_defaults.py} (88%) diff --git a/gateway/docs/schema-045-rollout.md b/gateway/docs/schema-046-rollout.md similarity index 67% rename from gateway/docs/schema-045-rollout.md rename to gateway/docs/schema-046-rollout.md index 14c5fb0d6..bbca92288 100644 --- a/gateway/docs/schema-045-rollout.md +++ b/gateway/docs/schema-046-rollout.md @@ -1,6 +1,7 @@ -# Schema 045: SQLite boolean defaults and rollback boundary +# Schema 046: SQLite boolean defaults and rollback boundary -Migration `045_sqlite_boolean_defaults` revises `044_receipt_resolutions`. +Migration `046_sqlite_boolean_defaults` revises `045_api_key_usage_events` +from PR #195. PR #61 must merge after PR #195. On SQLite it repairs legacy text booleans in refresh tokens, human approvals, and permits, then replaces their text defaults with integer false defaults. PostgreSQL schema and data are unchanged. @@ -8,14 +9,14 @@ PostgreSQL schema and data are unchanged. ## Compatibility release before migration Before an authorized rollout, confirm the database revision, back up the -database, and qualify a 045-capable recovery image. Rehearse the migration on +database, and qualify a 046-capable recovery image. Rehearse the migration on a copy of any SQLite database created before the corrected 022 and 023 migrations, including existing rows and inserts that omit these columns. The application requires its packaged Alembic head, so an older image cannot -restart after the database reaches 045. +restart after the database reaches 046. ## Rollback after activation The downgrade retains corrected values and defaults. Recover with a -045-capable image and the database at 045. Returning to an older packaged +046-capable image and the database at 046. Returning to an older packaged head requires a separately reviewed migration and compatibility plan. diff --git a/gateway/migrations/versions/045_sqlite_boolean_defaults.py b/gateway/migrations/versions/046_sqlite_boolean_defaults.py similarity index 88% rename from gateway/migrations/versions/045_sqlite_boolean_defaults.py rename to gateway/migrations/versions/046_sqlite_boolean_defaults.py index 128d2c24a..fdbb4b880 100644 --- a/gateway/migrations/versions/045_sqlite_boolean_defaults.py +++ b/gateway/migrations/versions/046_sqlite_boolean_defaults.py @@ -1,14 +1,14 @@ """Repair legacy SQLite text booleans and replace their text defaults. -Revision ID: 045_sqlite_boolean_defaults -Revises: 044_receipt_resolutions +Revision ID: 046_sqlite_boolean_defaults +Revises: 045_api_key_usage_events """ from alembic import op import sqlalchemy as sa -revision: str = "045_sqlite_boolean_defaults" -down_revision: str = "044_receipt_resolutions" +revision: str = "046_sqlite_boolean_defaults" +down_revision: str = "045_api_key_usage_events" branch_labels = None depends_on = None diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py index 27448a067..534eed1fc 100644 --- a/gateway/tests/test_sqlite_legacy_boolean_defaults.py +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -5,6 +5,7 @@ from alembic import command from alembic.config import Config +from alembic.script import ScriptDirectory _COLUMNS = ( @@ -32,6 +33,12 @@ def _defaults(connection): def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): + script = ScriptDirectory.from_config(Config("alembic.ini")) + assert script.get_heads() == ["046_sqlite_boolean_defaults"] + assert script.get_revision("046_sqlite_boolean_defaults").down_revision == ( + "045_api_key_usage_events" + ) + db_path = tmp_path / "legacy-defaults.db" _upgrade(monkeypatch, db_path, "023_human_approval_gate") From 89a595655ce510ead03e900fb981ec9846d1eb10 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:09:26 -0700 Subject: [PATCH 05/11] Chain SQLite boolean repair after approval gate migration Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/docs/schema-046-rollout.md | 22 ----------------- gateway/docs/schema-047-rollout.md | 24 +++++++++++++++++++ ...ults.py => 047_sqlite_boolean_defaults.py} | 12 +++++----- gateway/tests/test_action_migrations.py | 6 +++-- gateway/tests/test_migrations.py | 8 +++---- .../test_sqlite_legacy_boolean_defaults.py | 18 +++++++++++--- 6 files changed, 53 insertions(+), 37 deletions(-) delete mode 100644 gateway/docs/schema-046-rollout.md create mode 100644 gateway/docs/schema-047-rollout.md rename gateway/migrations/versions/{046_sqlite_boolean_defaults.py => 047_sqlite_boolean_defaults.py} (79%) diff --git a/gateway/docs/schema-046-rollout.md b/gateway/docs/schema-046-rollout.md deleted file mode 100644 index bbca92288..000000000 --- a/gateway/docs/schema-046-rollout.md +++ /dev/null @@ -1,22 +0,0 @@ -# Schema 046: SQLite boolean defaults and rollback boundary - -Migration `046_sqlite_boolean_defaults` revises `045_api_key_usage_events` -from PR #195. PR #61 must merge after PR #195. -On SQLite it repairs legacy text booleans in refresh tokens, human approvals, -and permits, then replaces their text defaults with integer false defaults. -PostgreSQL schema and data are unchanged. - -## Compatibility release before migration - -Before an authorized rollout, confirm the database revision, back up the -database, and qualify a 046-capable recovery image. Rehearse the migration on -a copy of any SQLite database created before the corrected 022 and 023 -migrations, including existing rows and inserts that omit these columns. -The application requires its packaged Alembic head, so an older image cannot -restart after the database reaches 046. - -## Rollback after activation - -The downgrade retains corrected values and defaults. Recover with a -046-capable image and the database at 046. Returning to an older packaged -head requires a separately reviewed migration and compatibility plan. diff --git a/gateway/docs/schema-047-rollout.md b/gateway/docs/schema-047-rollout.md new file mode 100644 index 000000000..bae3ed43b --- /dev/null +++ b/gateway/docs/schema-047-rollout.md @@ -0,0 +1,24 @@ +# Schema 047: SQLite boolean defaults and rollback boundary + +Migration `047_sqlite_boolean_defaults` revises +`045_approval_gate_approvals` from PR #216. PR #61 must merge after PR #216. +On SQLite it repairs legacy text booleans in refresh tokens, human approvals, +and permits, then replaces their text defaults with integer false defaults. +PostgreSQL schema and data are unchanged. + +## Compatibility release before migration + +Before an authorized rollout, confirm the database revision, back up the +database, and qualify a 047-capable recovery image. Rehearse the migration on +a copy of any SQLite database created before the corrected 022 and 023 +migrations, including existing rows and inserts that omit these columns. +The application requires its packaged Alembic head, so an older image cannot +restart after the database reaches 047. + +## Rollback after activation + +SQLite downgrade raises `sqlite_boolean_defaults_downgrade_unsupported` +instead of marking a database downgraded while retaining corrected values +and defaults. Recover with a 047-capable image and the database at 047. +Returning to an older packaged head requires a separately reviewed migration +and compatibility plan. diff --git a/gateway/migrations/versions/046_sqlite_boolean_defaults.py b/gateway/migrations/versions/047_sqlite_boolean_defaults.py similarity index 79% rename from gateway/migrations/versions/046_sqlite_boolean_defaults.py rename to gateway/migrations/versions/047_sqlite_boolean_defaults.py index fdbb4b880..caae34c35 100644 --- a/gateway/migrations/versions/046_sqlite_boolean_defaults.py +++ b/gateway/migrations/versions/047_sqlite_boolean_defaults.py @@ -1,14 +1,14 @@ """Repair legacy SQLite text booleans and replace their text defaults. -Revision ID: 046_sqlite_boolean_defaults -Revises: 045_api_key_usage_events +Revision ID: 047_sqlite_boolean_defaults +Revises: 045_approval_gate_approvals """ from alembic import op import sqlalchemy as sa -revision: str = "046_sqlite_boolean_defaults" -down_revision: str = "045_api_key_usage_events" +revision: str = "047_sqlite_boolean_defaults" +down_revision: str = "045_approval_gate_approvals" branch_labels = None depends_on = None @@ -46,5 +46,5 @@ def upgrade() -> None: def downgrade() -> None: - # Corrected values and defaults must not be restored to text booleans. - pass + if op.get_bind().dialect.name == "sqlite": + raise RuntimeError("sqlite_boolean_defaults_downgrade_unsupported") diff --git a/gateway/tests/test_action_migrations.py b/gateway/tests/test_action_migrations.py index 70257346b..bab9e443e 100644 --- a/gateway/tests/test_action_migrations.py +++ b/gateway/tests/test_action_migrations.py @@ -89,7 +89,9 @@ def migrate(url, revision, direction="upgrade"): def test_action_migration_retains_legacy_and_blocks_authority_loss( tmp_path, start_revision, authority ): - head_revision = current_head_revision() + # Exercise the 042 downgrade without crossing the irreversible SQLite + # boolean repair in later migrations. + head_revision = "044_receipt_resolutions" path = tmp_path / "migration.sqlite" url = f"sqlite+aiosqlite:///{path}" result = migrate(url, "040_permit_repeat_window") @@ -121,7 +123,7 @@ def test_action_migration_retains_legacy_and_blocks_authority_loss( ("",), ("w",), ] - result = migrate(url, "head") + result = migrate(url, head_revision) assert result.returncode == 0, result.stderr with sqlite3.connect(path) as db: assert db.execute("SELECT version_num FROM alembic_version").fetchone() == ( diff --git a/gateway/tests/test_migrations.py b/gateway/tests/test_migrations.py index ce12ba793..1e3e1b2bc 100644 --- a/gateway/tests/test_migrations.py +++ b/gateway/tests/test_migrations.py @@ -784,7 +784,7 @@ def test_041_scrubs_legacy_plaintext_owner_keys_from_content_tables( Rows whose owner_key is a known wallet id (what the factory routers write now) keep their owner, and an already-blank row stays blank. The rows are - inserted at head and the scrub is exercised by stepping back to 040 and + inserted at 044 and the scrub is exercised by stepping back to 040 and forward again, which also pins that the downgrade is a no-op (the scrubbed values were credentials and are unrecoverable) and the upgrade idempotent. """ @@ -796,7 +796,7 @@ def test_041_scrubs_legacy_plaintext_owner_keys_from_content_tables( monkeypatch.setenv("DATABASE_URL", async_url) config = Config("alembic.ini") - command.upgrade(config, "head") + command.upgrade(config, "044_receipt_resolutions") asyncio.set_event_loop(asyncio.new_event_loop()) engine = create_engine(sync_url) @@ -872,7 +872,7 @@ def owners() -> tuple[dict, dict]: command.downgrade(config, "040_permit_repeat_window") asyncio.set_event_loop(asyncio.new_event_loop()) - command.upgrade(config, "head") + command.upgrade(config, "044_receipt_resolutions") asyncio.set_event_loop(asyncio.new_event_loop()) pipelines, campaigns = owners() @@ -883,6 +883,6 @@ def owners() -> tuple[dict, dict]: # Idempotent: a second pass changes nothing. command.downgrade(config, "040_permit_repeat_window") asyncio.set_event_loop(asyncio.new_event_loop()) - command.upgrade(config, "head") + command.upgrade(config, "044_receipt_resolutions") asyncio.set_event_loop(asyncio.new_event_loop()) assert owners() == (pipelines, campaigns) diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py index 534eed1fc..36177fdc6 100644 --- a/gateway/tests/test_sqlite_legacy_boolean_defaults.py +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -6,6 +6,7 @@ from alembic import command from alembic.config import Config from alembic.script import ScriptDirectory +import pytest _COLUMNS = ( @@ -34,9 +35,9 @@ def _defaults(connection): def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["046_sqlite_boolean_defaults"] - assert script.get_revision("046_sqlite_boolean_defaults").down_revision == ( - "045_api_key_usage_events" + assert script.get_heads() == ["047_sqlite_boolean_defaults"] + assert script.get_revision("047_sqlite_boolean_defaults").down_revision == ( + "045_approval_gate_approvals" ) db_path = tmp_path / "legacy-defaults.db" @@ -134,3 +135,14 @@ def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): row[2:] for row in connection.execute(f"PRAGMA foreign_key_list({table})") } == foreign_keys[table] + + with pytest.raises( + RuntimeError, match="sqlite_boolean_defaults_downgrade_unsupported" + ): + command.downgrade(Config("alembic.ini"), "045_approval_gate_approvals") + asyncio.set_event_loop(asyncio.new_event_loop()) + with sqlite3.connect(db_path) as connection: + assert connection.execute( + "SELECT version_num FROM alembic_version" + ).fetchone() == ("047_sqlite_boolean_defaults",) + assert set(_defaults(connection).values()) == {"0"} From 874515d5efed5dad3d2a0cf9c4b290e82a44603d Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:01:25 -0700 Subject: [PATCH 06/11] Rechain SQLite boolean migration after API key usage events Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/docs/schema-047-rollout.md | 2 +- gateway/migrations/versions/047_sqlite_boolean_defaults.py | 4 ++-- gateway/tests/test_api_key_usage_migration.py | 2 +- gateway/tests/test_sqlite_legacy_boolean_defaults.py | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/gateway/docs/schema-047-rollout.md b/gateway/docs/schema-047-rollout.md index bae3ed43b..415a3a647 100644 --- a/gateway/docs/schema-047-rollout.md +++ b/gateway/docs/schema-047-rollout.md @@ -1,7 +1,7 @@ # Schema 047: SQLite boolean defaults and rollback boundary Migration `047_sqlite_boolean_defaults` revises -`045_approval_gate_approvals` from PR #216. PR #61 must merge after PR #216. +`046_api_key_usage_events` from PR #195. PR #61 must merge after PR #195. On SQLite it repairs legacy text booleans in refresh tokens, human approvals, and permits, then replaces their text defaults with integer false defaults. PostgreSQL schema and data are unchanged. diff --git a/gateway/migrations/versions/047_sqlite_boolean_defaults.py b/gateway/migrations/versions/047_sqlite_boolean_defaults.py index caae34c35..0715c1f1d 100644 --- a/gateway/migrations/versions/047_sqlite_boolean_defaults.py +++ b/gateway/migrations/versions/047_sqlite_boolean_defaults.py @@ -1,14 +1,14 @@ """Repair legacy SQLite text booleans and replace their text defaults. Revision ID: 047_sqlite_boolean_defaults -Revises: 045_approval_gate_approvals +Revises: 046_api_key_usage_events """ from alembic import op import sqlalchemy as sa revision: str = "047_sqlite_boolean_defaults" -down_revision: str = "045_approval_gate_approvals" +down_revision: str = "046_api_key_usage_events" branch_labels = None depends_on = None diff --git a/gateway/tests/test_api_key_usage_migration.py b/gateway/tests/test_api_key_usage_migration.py index 8741c0251..b7fb8e372 100644 --- a/gateway/tests/test_api_key_usage_migration.py +++ b/gateway/tests/test_api_key_usage_migration.py @@ -10,7 +10,7 @@ def test_046_revision_and_daily_view(tmp_path, monkeypatch) -> None: script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["046_api_key_usage_events"] + assert script.get_heads() == ["047_sqlite_boolean_defaults"] assert script.get_revision("046_api_key_usage_events").down_revision == ( "045_approval_gate_approvals" ) diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py index 36177fdc6..686d5f8bb 100644 --- a/gateway/tests/test_sqlite_legacy_boolean_defaults.py +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -37,7 +37,7 @@ def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): script = ScriptDirectory.from_config(Config("alembic.ini")) assert script.get_heads() == ["047_sqlite_boolean_defaults"] assert script.get_revision("047_sqlite_boolean_defaults").down_revision == ( - "045_approval_gate_approvals" + "046_api_key_usage_events" ) db_path = tmp_path / "legacy-defaults.db" @@ -139,7 +139,7 @@ def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): with pytest.raises( RuntimeError, match="sqlite_boolean_defaults_downgrade_unsupported" ): - command.downgrade(Config("alembic.ini"), "045_approval_gate_approvals") + command.downgrade(Config("alembic.ini"), "046_api_key_usage_events") asyncio.set_event_loop(asyncio.new_event_loop()) with sqlite3.connect(db_path) as connection: assert connection.execute( From c96958b45ace26ab2796ceb8772f3b8c3a2935f7 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:56:56 -0700 Subject: [PATCH 07/11] feat(migrations): port agent-middleware-api 047-050 with the same revision ids Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/db/models.py | 15 ++ gateway/docs/schema-047-rollout.md | 36 +++++ gateway/docs/schema-048-rollout.md | 19 +++ gateway/docs/schema-049-rollout.md | 9 ++ gateway/docs/schema-050-rollout.md | 11 ++ .../versions/047_dispatch_reconcile_lease.py | 107 ++++++++++++++ gateway/migrations/versions/048_tenant_rls.py | 132 ++++++++++++++++++ .../versions/049_demo_key_attribution.py | 44 ++++++ .../versions/050_demo_key_first_used.py | 84 +++++++++++ .../tests/test_api_chain_port_migrations.py | 103 ++++++++++++++ gateway/tests/test_api_key_usage_migration.py | 2 +- 11 files changed, 561 insertions(+), 1 deletion(-) create mode 100644 gateway/docs/schema-047-rollout.md create mode 100644 gateway/docs/schema-048-rollout.md create mode 100644 gateway/docs/schema-049-rollout.md create mode 100644 gateway/docs/schema-050-rollout.md create mode 100644 gateway/migrations/versions/047_dispatch_reconcile_lease.py create mode 100644 gateway/migrations/versions/048_tenant_rls.py create mode 100644 gateway/migrations/versions/049_demo_key_attribution.py create mode 100644 gateway/migrations/versions/050_demo_key_first_used.py create mode 100644 gateway/tests/test_api_chain_port_migrations.py diff --git a/gateway/app/db/models.py b/gateway/app/db/models.py index 2ddc3e428..5e26cb410 100644 --- a/gateway/app/db/models.py +++ b/gateway/app/db/models.py @@ -1253,6 +1253,21 @@ class McpDispatchAttemptModel(SQLModel, table=True): completed_at: Optional[datetime] = Field( sa_type=NaiveUTCDateTime, default=None, index=True ) + # Provider-status reconciliation (047_dispatch_reconcile_lease, ported from + # the agent-middleware-api chain). Nothing in this service writes them yet; + # they are mapped so the model matches databases migrated by either chain. + reconcile_status: Optional[str] = Field(default=None, max_length=32, index=True) + reconcile_lease_owner: Optional[str] = Field(default=None, max_length=64) + reconcile_lease_expires_at: Optional[datetime] = Field( + sa_type=NaiveUTCDateTime, default=None, index=True + ) + reconcile_next_probe_at: Optional[datetime] = Field( + sa_type=NaiveUTCDateTime, default=None, index=True + ) + reconcile_probe_count: int = Field( + default=0, sa_column_kwargs={"server_default": "0"} + ) + reconciled_at: Optional[datetime] = Field(sa_type=NaiveUTCDateTime, default=None) model_config = {"arbitrary_types_allowed": True} diff --git a/gateway/docs/schema-047-rollout.md b/gateway/docs/schema-047-rollout.md new file mode 100644 index 000000000..549a5a3cf --- /dev/null +++ b/gateway/docs/schema-047-rollout.md @@ -0,0 +1,36 @@ +# Schema 047: dispatch reconcile lease (ported) + +Migration `047_dispatch_reconcile_lease` revises `046_api_key_usage_events`. It is +ported from the archived agent-middleware-api chain with the same revision id, +so databases that service already migrated to 047-050 (staging and production, +both at `050_demo_key_first_used`) are at a revision this repository knows. + +It adds nullable `reconcile_status`, `reconcile_lease_owner`, +`reconcile_lease_expires_at`, `reconcile_next_probe_at`, `reconciled_at`, and +`reconcile_probe_count` (NOT NULL, default 0) to `mcp_dispatch_attempts`, plus +three indexes. Columns and indexes are added only when missing. No row is +updated. `McpDispatchAttemptModel` maps the columns; nothing here writes them yet. + +## Lineage gap for databases at the api chain's 050 + +The two chains share 001-042 and then diverge. A database migrated by the api +chain to 050 never ran this repository's `044_receipt_resolutions`, +`045_approval_gate_approvals`, or `046_api_key_usage_events`. Because 047 now +follows this repository's 046, Alembic treats those as applied, so such a +database stays at 050 without `receipt_resolutions`, `resolution_chain_heads`, +`approval_gate_approvals`, `api_key_usage_events`, or the `api_key_usage_daily` +view. It also keeps the api-only insights tables, which no model here maps. +This port does not repair that; a later idempotent migration must create the +missing objects before code that uses them serves against such a database. + +## Compatibility release + +Production boot requires the database revision to match the packaged head. +Fresh databases from this chain gain 047-050 normally. Qualify against a +disposable PostgreSQL upgrade from 046 and from an api-chain 050 copy. +These release checks have not been run against staging or production. + +## Rollback boundary + +Downgrade to 046 refuses while any row has a non-NULL `reconcile_status` and +otherwise drops the six columns and three indexes. diff --git a/gateway/docs/schema-048-rollout.md b/gateway/docs/schema-048-rollout.md new file mode 100644 index 000000000..12738d7bf --- /dev/null +++ b/gateway/docs/schema-048-rollout.md @@ -0,0 +1,19 @@ +# Schema 048: tenant RLS policies (ported) + +Migration `048_tenant_rls` revises `047_dispatch_reconcile_lease`, ported from +the agent-middleware-api chain with the same revision id. PostgreSQL only. +It creates the `amw_tenant_isolation` and `amw_delegated_issuer_read` +policies. This repository has no `TENANT_RLS_MODE` setting and no +`app.rls_bypass` in `migrations/env.py`, so the setting is read with an `off` +default and row-level security is never enabled or forced: policies exist but +do nothing, which matches the original's default. Enabling RLS is out of scope. + +## Compatibility release + +No behaviour change while RLS stays disabled. A database already at 050 from +the api chain is unchanged. + +## Rollback boundary + +Downgrade drops the policies and runs NO FORCE / DISABLE ROW LEVEL SECURITY on +each listed table. diff --git a/gateway/docs/schema-049-rollout.md b/gateway/docs/schema-049-rollout.md new file mode 100644 index 000000000..fe3c5ee99 --- /dev/null +++ b/gateway/docs/schema-049-rollout.md @@ -0,0 +1,9 @@ +# Schema 049: demo key attribution (ported) + +Migration `049_demo_key_attribution` revises `048_tenant_rls`, ported with the +same revision id. `043_demo_key_fields` already adds the UTM and referrer +columns here, so on this chain it adds only missing columns (normally none). + +## Rollback boundary + +Downgrade is a no-op; the columns belong to 043, which retains them. diff --git a/gateway/docs/schema-050-rollout.md b/gateway/docs/schema-050-rollout.md new file mode 100644 index 000000000..6d69a2d82 --- /dev/null +++ b/gateway/docs/schema-050-rollout.md @@ -0,0 +1,11 @@ +# Schema 050: demo key first use (ported) + +Migration `050_demo_key_first_used` revises `049_demo_key_attribution`, ported +with the same revision id. `043_demo_key_fields` already adds +`api_keys.first_used_at` and the `demo_key_funnel_by_source` view, so this adds +them only when missing and backfills only NULL `first_used_at` from +`last_used_at`. Staging and production are at this revision. + +## Rollback boundary + +Downgrade is a no-op; the column and view belong to 043, which retains them. diff --git a/gateway/migrations/versions/047_dispatch_reconcile_lease.py b/gateway/migrations/versions/047_dispatch_reconcile_lease.py new file mode 100644 index 000000000..3a8fbf6cb --- /dev/null +++ b/gateway/migrations/versions/047_dispatch_reconcile_lease.py @@ -0,0 +1,107 @@ +"""Add provider-status reconciliation columns to governed MCP dispatch attempts. + +Additive and nullable (the probe counter defaults to zero). Existing +``delivery_uncertain`` rows upgrade to an unresolved reconcile status, which +is exactly their meaning today: parked for manual review. No data update or +backfill is performed, and ``state`` is never touched. + +Revision ID: 047_dispatch_reconcile_lease +Revises: 046_api_key_usage_events + +Ported from the archived agent-middleware-api chain with the same revision +id so databases already stamped at 047-050 by that service stay on a known +revision. Here it follows this repo's 046. Columns and indexes are added only +when missing. +""" + +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + + +revision: str = "047_dispatch_reconcile_lease" +down_revision: Union[str, None] = "046_api_key_usage_events" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +_COLUMNS = ( + ( + "reconcile_status", + lambda: sa.Column("reconcile_status", sa.String(length=32), nullable=True), + ), + ( + "reconcile_lease_owner", + lambda: sa.Column("reconcile_lease_owner", sa.String(length=64), nullable=True), + ), + ( + "reconcile_lease_expires_at", + lambda: sa.Column("reconcile_lease_expires_at", sa.DateTime(), nullable=True), + ), + ( + "reconcile_next_probe_at", + lambda: sa.Column("reconcile_next_probe_at", sa.DateTime(), nullable=True), + ), + ( + "reconcile_probe_count", + lambda: sa.Column( + "reconcile_probe_count", sa.Integer(), nullable=False, server_default="0" + ), + ), + ("reconciled_at", lambda: sa.Column("reconciled_at", sa.DateTime(), nullable=True)), +) +_INDEXES = ( + ("ix_mcp_dispatch_attempts_reconcile_status", "reconcile_status"), + ( + "ix_mcp_dispatch_attempts_reconcile_lease_expires_at", + "reconcile_lease_expires_at", + ), + ("ix_mcp_dispatch_attempts_reconcile_next_probe_at", "reconcile_next_probe_at"), +) + + +def upgrade() -> None: + inspector = sa.inspect(op.get_bind()) + columns = {c["name"] for c in inspector.get_columns("mcp_dispatch_attempts")} + indexes = {i["name"] for i in inspector.get_indexes("mcp_dispatch_attempts")} + missing_columns = [make() for name, make in _COLUMNS if name not in columns] + missing_indexes = [(n, c) for n, c in _INDEXES if n not in indexes] + if not missing_columns and not missing_indexes: + return + with op.batch_alter_table("mcp_dispatch_attempts") as batch_op: + for column in missing_columns: + batch_op.add_column(column) + for name, column in missing_indexes: + batch_op.create_index(name, [column]) + + +def downgrade() -> None: + # Any non-NULL status is a durable provider decision. A refunded row's + # refund and budget release outlive the column, and 046 accounting counts + # every delivery_uncertain receipt as consumed, so a budget rebuild would + # re-charge the released spend; a pending row may be half applied; and a + # re-upgrade would re-probe every erased decision. Refuse rather than + # silently drop any of them. + bind = op.get_bind() + decided = bind.execute( + sa.text( + "SELECT COUNT(*) FROM mcp_dispatch_attempts " + "WHERE reconcile_status IS NOT NULL" + ) + ).scalar_one() + if decided: + raise RuntimeError( + f"047 downgrade refused: {decided} dispatch attempt(s) carry a " + "reconcile_status decision that 046 cannot represent" + ) + with op.batch_alter_table("mcp_dispatch_attempts") as batch_op: + batch_op.drop_index("ix_mcp_dispatch_attempts_reconcile_next_probe_at") + batch_op.drop_index("ix_mcp_dispatch_attempts_reconcile_lease_expires_at") + batch_op.drop_index("ix_mcp_dispatch_attempts_reconcile_status") + batch_op.drop_column("reconciled_at") + batch_op.drop_column("reconcile_probe_count") + batch_op.drop_column("reconcile_next_probe_at") + batch_op.drop_column("reconcile_lease_expires_at") + batch_op.drop_column("reconcile_lease_owner") + batch_op.drop_column("reconcile_status") diff --git a/gateway/migrations/versions/048_tenant_rls.py b/gateway/migrations/versions/048_tenant_rls.py new file mode 100644 index 000000000..01486fe2f --- /dev/null +++ b/gateway/migrations/versions/048_tenant_rls.py @@ -0,0 +1,132 @@ +"""Wallet row-level security policies; enabled only under TENANT_RLS_MODE=enforce. + +Revision ID: 048_tenant_rls +Revises: 047_dispatch_reconcile_lease + +PostgreSQL only; a no-op on SQLite. Each listed table gets one policy whose USING and WITH CHECK admit a row only +when an owning wallet column equals ``app.current_wallet_id`` or +the app.rls_bypass setting is ``'on'``. ``current_setting(..., true)`` yields NULL when +the setting was never set and '' after a ``SET LOCAL`` ends; NULLIF folds both +into NULL, and a NULL comparison admits nothing, so an unset scope fails +closed. + +Default off: the policies are created but row-level security stays disabled +on every table, so no client sees any change. ENABLE and FORCE ROW LEVEL +SECURITY run only when this migration executes with TENANT_RLS_MODE=enforce; +enabling later is the per-table ALTER in docs/tenant-rls.md in the api repo. Wallet columns are character varying; the setting is text, compared with +the built-in text equality, so no cast is needed and the wallet indexes stay +usable. + +Superusers and BYPASSRLS roles skip every policy. FORCE binds the table owner +too, so this migration (and any later data migration) runs with +the app.rls_bypass setting set locally by migrations/env.py. Runtime role setup and +the admin mechanism are documented in docs/tenant-rls.md in the api repo. + +A second, SELECT-only policy mirrors the delegated-issuer branch of +``authorize_receipt_access``: the issuer of a permit may read receipts filed +under that permit's subject wallet, and the ledger entry (and its refund), the +dispatch attempt, and the idempotency record such a visible receipt points at. +Those subqueries are themselves filtered by the receipts and permits policies, +so they can only widen reads along links the caller can already see. Writes +stay limited to the caller's own wallet. + +The table list is a frozen copy of app.db.tenant_rls.RLS_TABLES in the api repo. + +Ported from the archived agent-middleware-api chain with the same revision +id. This service has no ``TENANT_RLS_MODE`` setting and no the app.rls_bypass setting +in migrations/env.py, so the setting is read with an ``off`` default: +policies are created, row-level security is never enabled or forced here. +That is the same default-off result the original produced. +""" + +from alembic import op + +from app.core.config import get_settings + +revision: str = "048_tenant_rls" +down_revision: str = "047_dispatch_reconcile_lease" +branch_labels = None +depends_on = None + +POLICY_NAME = "amw_tenant_isolation" + +RLS_TABLES: dict[str, tuple[str, ...]] = { + "api_keys": ("wallet_id",), + "billing_alerts": ("wallet_id",), + "daily_balance_snapshots": ("wallet_id",), + "human_approvals": ("wallet_id",), + "idempotency_records": ("wallet_id",), + "key_rotation_logs": ("wallet_id",), + "kyc_verifications": ("wallet_id",), + "ledger_entries": ("wallet_id",), + "mcp_dispatch_attempts": ("wallet_id",), + "permit_requests": ("issuer_wallet_id", "subject_wallet_id"), + "permits": ("issuer_wallet_id", "subject_wallet_id"), + "policy_bundles": ("wallet_id",), + "quotes": ("wallet_id",), + "receipts": ("wallet_id",), + "refresh_tokens": ("wallet_id",), +} + +_CURRENT_WALLET = "NULLIF(current_setting('app.current_wallet_id', true), '')" +_BYPASS = "current_setting('app.rls_bypass', true) = 'on'" + +READ_POLICY_NAME = "amw_delegated_issuer_read" + +DELEGATED_READ_PREDICATES: dict[str, str] = { + "receipts": ( + "EXISTS (SELECT 1 FROM permits p WHERE p.permit_id = receipts.permit_id " + "AND p.subject_wallet_id = receipts.wallet_id " + f"AND p.issuer_wallet_id = {_CURRENT_WALLET})" + ), + "ledger_entries": ( + "EXISTS (SELECT 1 FROM receipts r WHERE r.ledger_entry_id = " + "ledger_entries.entry_id OR r.ledger_entry_id = ledger_entries.correlation_id)" + ), + "mcp_dispatch_attempts": ( + "EXISTS (SELECT 1 FROM receipts r " + "WHERE r.dispatch_attempt_id = mcp_dispatch_attempts.attempt_id)" + ), + "idempotency_records": ( + "EXISTS (SELECT 1 FROM receipts r " + "WHERE r.idempotency_record_id = idempotency_records.record_id)" + ), +} + + +def policy_predicate(columns: tuple[str, ...]) -> str: + wallet_match = " OR ".join(f"{column} = {_CURRENT_WALLET}" for column in columns) + return f"({wallet_match}) OR {_BYPASS}" + + +def upgrade(): + if op.get_bind().dialect.name != "postgresql": + return + enforce = getattr(get_settings(), "TENANT_RLS_MODE", "off") == "enforce" + for table, columns in RLS_TABLES.items(): + predicate = policy_predicate(columns) + if enforce: + op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") + op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY") + op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") + op.execute( + f"CREATE POLICY {POLICY_NAME} ON {table} AS PERMISSIVE FOR ALL " + f"USING ({predicate}) WITH CHECK ({predicate})" + ) + for table, predicate in DELEGATED_READ_PREDICATES.items(): + op.execute(f"DROP POLICY IF EXISTS {READ_POLICY_NAME} ON {table}") + op.execute( + f"CREATE POLICY {READ_POLICY_NAME} ON {table} AS PERMISSIVE FOR SELECT " + f"USING ({predicate})" + ) + + +def downgrade(): + if op.get_bind().dialect.name != "postgresql": + return + for table in DELEGATED_READ_PREDICATES: + op.execute(f"DROP POLICY IF EXISTS {READ_POLICY_NAME} ON {table}") + for table in RLS_TABLES: + op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") + op.execute(f"ALTER TABLE {table} NO FORCE ROW LEVEL SECURITY") + op.execute(f"ALTER TABLE {table} DISABLE ROW LEVEL SECURITY") diff --git a/gateway/migrations/versions/049_demo_key_attribution.py b/gateway/migrations/versions/049_demo_key_attribution.py new file mode 100644 index 000000000..a0d0a51a8 --- /dev/null +++ b/gateway/migrations/versions/049_demo_key_attribution.py @@ -0,0 +1,44 @@ +"""Store optional UTM and referrer attribution on demo API keys. + +Revision ID: 049_demo_key_attribution +Revises: 048_tenant_rls + +Nullable columns. Existing keys, including demo keys issued before this +migration, stay NULL. Only POST /v1/demo/keys writes them. + +Ported from the archived agent-middleware-api chain with the same revision +id. In this repo ``043_demo_key_fields`` already adds these columns, so the +upgrade only adds any that are missing and the downgrade leaves them to 043. +""" + +from alembic import op +import sqlalchemy as sa + +revision: str = "049_demo_key_attribution" +down_revision: str = "048_tenant_rls" +branch_labels = None +depends_on = None + + +COLUMNS = ( + ("utm_source", 128), + ("utm_medium", 128), + ("utm_campaign", 128), + ("utm_content", 128), + ("utm_term", 128), + ("referrer", 512), +) + + +def upgrade(): + existing = {c["name"] for c in sa.inspect(op.get_bind()).get_columns("api_keys")} + missing = [(name, size) for name, size in COLUMNS if name not in existing] + if not missing: + return + with op.batch_alter_table("api_keys", schema=None) as batch_op: + for name, size in missing: + batch_op.add_column(sa.Column(name, sa.String(length=size), nullable=True)) + + +def downgrade(): + """Columns belong to 043_demo_key_fields, which retains them on rollback.""" diff --git a/gateway/migrations/versions/050_demo_key_first_used.py b/gateway/migrations/versions/050_demo_key_first_used.py new file mode 100644 index 000000000..721d27b1f --- /dev/null +++ b/gateway/migrations/versions/050_demo_key_first_used.py @@ -0,0 +1,84 @@ +"""Record the first authenticated use of an API key; demo funnel view. + +Revision ID: 050_demo_key_first_used +Revises: 049_demo_key_attribution + +Additive only. ``api_keys.first_used_at`` is nullable and is backfilled from +``last_used_at`` where a key has already been used (an UPDATE of the new +column only; no row is deleted and no other column changes). The read-only +view ``demo_key_funnel_by_source`` groups demo-tenant keys (``tenant = +'demo'``, the label ``app.services.demo_tenant`` stamps on issuance) by +acquisition source and counts issued versus used keys. + +PostgreSQL groups by the referrer's host. Other dialects (SQLite in tests) +group by the raw referrer, because they have no portable host extraction. +Ported from the archived agent-middleware-api chain with the same revision +id. In this repo ``043_demo_key_fields`` already creates the column and the +view, so the upgrade adds the column and view only when missing, the +backfill only touches NULL ``first_used_at``, and the downgrade leaves both +to 043. +""" + +from alembic import op +import sqlalchemy as sa + +revision: str = "050_demo_key_first_used" +down_revision: str = "049_demo_key_attribution" +branch_labels = None +depends_on = None + +VIEW_NAME = "demo_key_funnel_by_source" + +# First capture group = host of an absolute URL, skipping any userinfo. +_PG_REFERRER_HOST = ( + "COALESCE(lower(substring(referrer from " + "'^[A-Za-z][A-Za-z0-9+.-]*://(?:[^@/?#]*@)?([^/:?#]+)')), referrer)" +) + + +def _view_sql(referrer_expr: str) -> str: + return f""" + CREATE VIEW {VIEW_NAME} AS + SELECT + COALESCE(utm_source, '(none)') AS utm_source, + utm_medium, + utm_campaign, + {referrer_expr} AS referrer_host, + COUNT(*) AS keys_issued, + COUNT(first_used_at) AS keys_used, + MIN(created_at) AS first_issued_at, + MAX(created_at) AS last_issued_at + FROM api_keys + WHERE tenant = 'demo' + GROUP BY + COALESCE(utm_source, '(none)'), + utm_medium, + utm_campaign, + {referrer_expr} + """ + + +def upgrade(): + bind = op.get_bind() + existing = {c["name"] for c in sa.inspect(bind).get_columns("api_keys")} + if "first_used_at" not in existing: + with op.batch_alter_table("api_keys", schema=None) as batch_op: + batch_op.add_column( + sa.Column("first_used_at", sa.DateTime(), nullable=True) + ) + + op.execute( + "UPDATE api_keys SET first_used_at = last_used_at " + "WHERE first_used_at IS NULL AND last_used_at IS NOT NULL" + ) + + if VIEW_NAME in sa.inspect(bind).get_view_names(): + return + if bind.dialect.name == "postgresql": + op.execute(_view_sql(_PG_REFERRER_HOST)) + else: + op.execute(_view_sql("referrer")) + + +def downgrade(): + """Column and view belong to 043_demo_key_fields, which retains them.""" diff --git a/gateway/tests/test_api_chain_port_migrations.py b/gateway/tests/test_api_chain_port_migrations.py new file mode 100644 index 000000000..8ff05d347 --- /dev/null +++ b/gateway/tests/test_api_chain_port_migrations.py @@ -0,0 +1,103 @@ +"""Ported agent-middleware-api migrations 047-050 on this repo's chain.""" + +import asyncio + +from alembic import command +from alembic.config import Config +from alembic.script import ScriptDirectory +from sqlalchemy import create_engine, inspect, text + +RECONCILE_COLUMNS = { + "reconcile_status", + "reconcile_lease_owner", + "reconcile_lease_expires_at", + "reconcile_next_probe_at", + "reconcile_probe_count", + "reconciled_at", +} +RECONCILE_INDEXES = { + "ix_mcp_dispatch_attempts_reconcile_status", + "ix_mcp_dispatch_attempts_reconcile_lease_expires_at", + "ix_mcp_dispatch_attempts_reconcile_next_probe_at", +} + + +def _config(tmp_path, monkeypatch): + db_path = tmp_path / "port.db" + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + return Config("alembic.ini"), f"sqlite:///{db_path}" + + +def _upgrade(config, target): + command.upgrade(config, target) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def _downgrade(config, target): + command.downgrade(config, target) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def test_single_head_and_ported_order(): + script = ScriptDirectory.from_config(Config("alembic.ini")) + assert script.get_heads() == ["050_demo_key_first_used"] + chain = { + "047_dispatch_reconcile_lease": "046_api_key_usage_events", + "048_tenant_rls": "047_dispatch_reconcile_lease", + "049_demo_key_attribution": "048_tenant_rls", + "050_demo_key_first_used": "049_demo_key_attribution", + } + for revision, down in chain.items(): + assert script.get_revision(revision).down_revision == down + + +def test_fresh_upgrade_to_head_and_round_trip(tmp_path, monkeypatch): + config, sync_url = _config(tmp_path, monkeypatch) + _upgrade(config, "head") + engine = create_engine(sync_url) + insp = inspect(engine) + cols = {c["name"] for c in insp.get_columns("mcp_dispatch_attempts")} + assert RECONCILE_COLUMNS <= cols + idx = {i["name"] for i in insp.get_indexes("mcp_dispatch_attempts")} + assert RECONCILE_INDEXES <= idx + assert "demo_key_funnel_by_source" in insp.get_view_names() + for table in ( + "receipt_resolutions", + "approval_gate_approvals", + "api_key_usage_events", + ): + assert table in insp.get_table_names() + with engine.connect() as conn: + assert conn.execute( + text("SELECT version_num FROM alembic_version") + ).scalar() == ("050_demo_key_first_used") + engine.dispose() + + _downgrade(config, "046_api_key_usage_events") + engine = create_engine(sync_url) + insp = inspect(engine) + cols = {c["name"] for c in insp.get_columns("mcp_dispatch_attempts")} + assert not (RECONCILE_COLUMNS & cols) + # 049/050 leave 043's columns and view in place. + key_cols = {c["name"] for c in insp.get_columns("api_keys")} + assert {"utm_source", "referrer", "first_used_at"} <= key_cols + assert "demo_key_funnel_by_source" in insp.get_view_names() + engine.dispose() + + _upgrade(config, "head") + engine = create_engine(sync_url) + cols = {c["name"] for c in inspect(engine).get_columns("mcp_dispatch_attempts")} + assert RECONCILE_COLUMNS <= cols + engine.dispose() + + +def test_upgrade_at_head_is_noop(tmp_path, monkeypatch): + config, sync_url = _config(tmp_path, monkeypatch) + _upgrade(config, "050_demo_key_first_used") + _upgrade(config, "head") + engine = create_engine(sync_url) + with engine.connect() as conn: + assert conn.execute( + text("SELECT version_num FROM alembic_version") + ).scalar() == ("050_demo_key_first_used") + engine.dispose() diff --git a/gateway/tests/test_api_key_usage_migration.py b/gateway/tests/test_api_key_usage_migration.py index 8741c0251..9f2a4c617 100644 --- a/gateway/tests/test_api_key_usage_migration.py +++ b/gateway/tests/test_api_key_usage_migration.py @@ -10,7 +10,7 @@ def test_046_revision_and_daily_view(tmp_path, monkeypatch) -> None: script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["046_api_key_usage_events"] + assert script.get_revision("046_api_key_usage_events") is not None assert script.get_revision("046_api_key_usage_events").down_revision == ( "045_approval_gate_approvals" ) From f563483743e308139b66352d25c6fee95590ea62 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:36:48 -0700 Subject: [PATCH 08/11] fix(migrations): rls_bypass in env.py, boot check for reconcile columns Address review 5642272418 on #234: - migrations/env.py sets app.rls_bypass=on (transaction-local) on PostgreSQL, as the archived api env.py did, so the 050 backfill sees rows under FORCE ROW LEVEL SECURITY with a non-superuser owner. - REQUIRED_TRUST_COLUMNS for mcp_dispatch_attempts now lists the six 047 reconcile columns; legacy create_all boot test covers each. - 048 docstring matches env.py. Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/db/database.py | 12 +++++++++++- gateway/migrations/env.py | 9 +++++++++ gateway/migrations/versions/048_tenant_rls.py | 12 +++++++----- gateway/tests/test_schema_boot.py | 15 +++++++++++++++ 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/gateway/app/db/database.py b/gateway/app/db/database.py index ecdcf09bc..05396ded2 100644 --- a/gateway/app/db/database.py +++ b/gateway/app/db/database.py @@ -79,7 +79,17 @@ "created_at", } ), - "mcp_dispatch_attempts": frozenset({"dispatch_claim_hash"}), + "mcp_dispatch_attempts": frozenset( + { + "dispatch_claim_hash", + "reconcile_status", + "reconcile_lease_owner", + "reconcile_lease_expires_at", + "reconcile_next_probe_at", + "reconcile_probe_count", + "reconciled_at", + } + ), "resolution_chain_heads": frozenset({"last_sequence", "last_hash"}), "receipt_resolutions": frozenset( { diff --git a/gateway/migrations/env.py b/gateway/migrations/env.py index 2c8175d01..d42b2de3f 100644 --- a/gateway/migrations/env.py +++ b/gateway/migrations/env.py @@ -64,6 +64,15 @@ def do_run_migrations(connection: Connection) -> None: context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): + if connection.dialect.name == "postgresql": + # Explicit admin mechanism for migrations, as in the archived api + # chain: FORCE ROW LEVEL SECURITY (048_tenant_rls, enforce mode) + # binds the table owner too, so data migrations such as the 050 + # backfill opt out of the wallet policies for this transaction + # only (set_config is_local=true, the SET LOCAL equivalent). + connection.exec_driver_sql( + "SELECT set_config('app.rls_bypass', 'on', true)" + ) context.run_migrations() diff --git a/gateway/migrations/versions/048_tenant_rls.py b/gateway/migrations/versions/048_tenant_rls.py index 01486fe2f..e4e969947 100644 --- a/gateway/migrations/versions/048_tenant_rls.py +++ b/gateway/migrations/versions/048_tenant_rls.py @@ -19,7 +19,8 @@ Superusers and BYPASSRLS roles skip every policy. FORCE binds the table owner too, so this migration (and any later data migration) runs with -the app.rls_bypass setting set locally by migrations/env.py. Runtime role setup and +the app.rls_bypass setting set to 'on' for the migration transaction only by +migrations/env.py (``set_config(..., true)``). Runtime role setup and the admin mechanism are documented in docs/tenant-rls.md in the api repo. A second, SELECT-only policy mirrors the delegated-issuer branch of @@ -33,10 +34,11 @@ The table list is a frozen copy of app.db.tenant_rls.RLS_TABLES in the api repo. Ported from the archived agent-middleware-api chain with the same revision -id. This service has no ``TENANT_RLS_MODE`` setting and no the app.rls_bypass setting -in migrations/env.py, so the setting is read with an ``off`` default: -policies are created, row-level security is never enabled or forced here. -That is the same default-off result the original produced. +id. This service has no ``TENANT_RLS_MODE`` setting, so it is read with an +``off`` default: policies are created and row-level security is enabled or +forced only when an operator sets TENANT_RLS_MODE=enforce, as in the +original. migrations/env.py sets the app.rls_bypass setting exactly as the +archived env.py did, so data migrations still see every row under FORCE. """ from alembic import op diff --git a/gateway/tests/test_schema_boot.py b/gateway/tests/test_schema_boot.py index 96b1b5fba..f1fc89be9 100644 --- a/gateway/tests/test_schema_boot.py +++ b/gateway/tests/test_schema_boot.py @@ -214,6 +214,17 @@ async def test_init_db_production_like_accepts_legacy_create_all_tables( ("table_name", "column_name"), [ ("mcp_dispatch_attempts", "dispatch_claim_hash"), + *[ + ("mcp_dispatch_attempts", column) + for column in ( + "reconcile_status", + "reconcile_lease_owner", + "reconcile_lease_expires_at", + "reconcile_next_probe_at", + "reconcile_probe_count", + "reconciled_at", + ) + ], ("permits", "repeat_window_seconds"), ("receipt_resolutions", "payload_hash"), ("receipt_resolutions", "signing_input"), @@ -245,6 +256,10 @@ async def test_init_db_rejects_unstamped_legacy_table_missing_required_column( sync = create_engine(f"sqlite:///{db_path}") with sync.begin() as connection: + # SQLite cannot drop an indexed column; drop its indexes first. + for index in inspect(connection).get_indexes(table_name): + if column_name in index["column_names"]: + connection.exec_driver_sql(f"DROP INDEX {index['name']}") connection.exec_driver_sql( f"ALTER TABLE {table_name} DROP COLUMN {column_name}" ) From e6d5f997988ca7a273832e4c0667b642f952fc6a Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:36:49 -0700 Subject: [PATCH 09/11] fix(migrations): port TENANT_RLS_MODE setting; RLS for resolution tables Address codex review of f563483 on #234: - Settings.TENANT_RLS_MODE ported from agent-middleware-api d7bc941 (same name, default 'off', off/enforce validator). 048 reads it directly. - 048 applies amw_tenant_isolation to receipt_resolutions and resolution_chain_heads when they exist (fresh chain); 053 covers api-chain DBs. Downgrade drops them too. - schema-048 rollout note: env.py bypass, fail-closed warning (no runtime app.current_wallet_id in this gateway yet). - Opt-in PG test (TENANT_RLS_MIGRATION_DATABASE_URL): non-superuser owner, enforce forces RLS on all 17 tables, 050 backfills. Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/core/config.py | 18 +++ gateway/docs/schema-048-rollout.md | 44 ++++++-- gateway/migrations/versions/048_tenant_rls.py | 59 +++++++--- gateway/tests/test_tenant_rls_migration.py | 105 ++++++++++++++++++ 4 files changed, 197 insertions(+), 29 deletions(-) create mode 100644 gateway/tests/test_tenant_rls_migration.py diff --git a/gateway/app/core/config.py b/gateway/app/core/config.py index 726ae8640..00b735b26 100644 --- a/gateway/app/core/config.py +++ b/gateway/app/core/config.py @@ -58,6 +58,15 @@ class Settings(BaseSettings): DATABASE_URL: str = "" REDIS_URL: str = "" SQLITE_URL: str = "" + # PostgreSQL row-level security for wallet-scoped tables (migration + # 048_tenant_rls), ported from the archived agent-middleware-api Settings + # with the same name, default and validation. "off" (default): the + # migration creates the policies but leaves RLS disabled, so nothing + # changes for any client. "enforce": migrating in this mode enables and + # forces RLS. This gateway does not yet set app.current_wallet_id per + # transaction, so enforce fails closed for a NOSUPERUSER NOBYPASSRLS + # runtime role; see docs/schema-048-rollout.md. No effect on SQLite. + TENANT_RLS_MODE: str = "off" # --- Database Pool Settings --- # Used for SQLModel/SQLAlchemy async sessions @@ -317,6 +326,15 @@ def demo_allowed_tools_list(self) -> list[str]: # advertised rate drift from the rate real money converts at. EXCHANGE_RATE: Decimal = Decimal("1000.0") + @field_validator("TENANT_RLS_MODE") + @classmethod + def _validate_tenant_rls_mode(cls, value: str) -> str: + """Only the two documented modes; a typo must not silently mean off.""" + normalized = (value or "").strip().lower() + if normalized not in {"off", "enforce"}: + raise ValueError("TENANT_RLS_MODE must be 'off' or 'enforce'") + return normalized + @field_validator("EXCHANGE_RATE") @classmethod def _validate_exchange_rate(cls, value: Decimal) -> Decimal: diff --git a/gateway/docs/schema-048-rollout.md b/gateway/docs/schema-048-rollout.md index 12738d7bf..7ede1a20e 100644 --- a/gateway/docs/schema-048-rollout.md +++ b/gateway/docs/schema-048-rollout.md @@ -1,19 +1,39 @@ # Schema 048: tenant RLS policies (ported) -Migration `048_tenant_rls` revises `047_dispatch_reconcile_lease`, ported from -the agent-middleware-api chain with the same revision id. PostgreSQL only. -It creates the `amw_tenant_isolation` and `amw_delegated_issuer_read` -policies. This repository has no `TENANT_RLS_MODE` setting and no -`app.rls_bypass` in `migrations/env.py`, so the setting is read with an `off` -default and row-level security is never enabled or forced: policies exist but -do nothing, which matches the original's default. Enabling RLS is out of scope. +Migration `048_tenant_rls` revises `047_dispatch_reconcile_lease`. It is ported +from the agent-middleware-api chain with the same revision id and is +PostgreSQL only. It creates the `amw_tenant_isolation` policy on the 15 +archived wallet-scoped tables and the `amw_delegated_issuer_read` policies. + +The two wallet-scoped tables from this repo's 044, `receipt_resolutions` and +`resolution_chain_heads`, get the same `amw_tenant_isolation` policy when they +already exist. On an api-chain database they don't exist yet; +`053_repair_api_lineage` creates them and applies the identical policy. + +`TENANT_RLS_MODE` is ported from the api Settings with the same default (`off`) +and the same validation (`off` or `enforce`). + +- `off`: the policies exist, but row-level security stays disabled, so nothing + changes. This matches the original's default. +- `enforce`: running the migration enables and forces RLS on every listed table. + +`migrations/env.py` sets `app.rls_bypass` to `on` for the migration +transaction only, as the archived env.py did. That lets data migrations, such +as the 050 backfill, see every row under FORCE with a non-superuser owner. ## Compatibility release -No behaviour change while RLS stays disabled. A database already at 050 from -the api chain is unchanged. +There is no behaviour change in `off` mode. + +Warning: this gateway does not yet set `app.current_wallet_id` per transaction +(the api repo's runtime tenant scope is not ported). A database that was +migrated under `enforce` therefore fails closed for a NOSUPERUSER NOBYPASSRLS +runtime role: wallet-scoped tables read as empty and writes are refused. That +includes an api-chain 050 database that already has RLS forced. Don't migrate +under `enforce`, and don't point this gateway at such a database with a +policy-bound role, until the runtime scope is ported. -## Rollback boundary +## Rollback -Downgrade drops the policies and runs NO FORCE / DISABLE ROW LEVEL SECURITY on -each listed table. +Downgrade drops the policies. It also runs NO FORCE / DISABLE ROW LEVEL +SECURITY on each listed table, including the two late tables when they exist. diff --git a/gateway/migrations/versions/048_tenant_rls.py b/gateway/migrations/versions/048_tenant_rls.py index e4e969947..22d775bcd 100644 --- a/gateway/migrations/versions/048_tenant_rls.py +++ b/gateway/migrations/versions/048_tenant_rls.py @@ -34,13 +34,20 @@ The table list is a frozen copy of app.db.tenant_rls.RLS_TABLES in the api repo. Ported from the archived agent-middleware-api chain with the same revision -id. This service has no ``TENANT_RLS_MODE`` setting, so it is read with an -``off`` default: policies are created and row-level security is enabled or -forced only when an operator sets TENANT_RLS_MODE=enforce, as in the -original. migrations/env.py sets the app.rls_bypass setting exactly as the -archived env.py did, so data migrations still see every row under FORCE. +id. ``Settings.TENANT_RLS_MODE`` is ported with the same name, default +(``off``) and validation, so this migration behaves as the original did. +migrations/env.py sets the app.rls_bypass setting exactly as the archived +env.py did, so data migrations still see every row under FORCE. + +This repository's chain also has the wallet-scoped receipt_resolutions and +resolution_chain_heads (044), which the api chain never had. They get the +same tenant policy here when they exist (a fresh chain, where 044 ran +first). On a database that reached 050 through the api chain they do not +exist yet; 053_repair_api_lineage creates them and applies the identical +policy, so both lineages end with the same policy set. """ +import sqlalchemy as sa from alembic import op from app.core.config import get_settings @@ -70,6 +77,13 @@ "refresh_tokens": ("wallet_id",), } +# Tables from this repo's 044 that are absent on an api-chain database when +# 048 runs there; 053_repair_api_lineage applies the same policy to them. +LATE_RLS_TABLES: dict[str, tuple[str, ...]] = { + "receipt_resolutions": ("wallet_id",), + "resolution_chain_heads": ("wallet_id",), +} + _CURRENT_WALLET = "NULLIF(current_setting('app.current_wallet_id', true), '')" _BYPASS = "current_setting('app.rls_bypass', true) = 'on'" @@ -101,20 +115,29 @@ def policy_predicate(columns: tuple[str, ...]) -> str: return f"({wallet_match}) OR {_BYPASS}" +def _apply_tenant_policy(table: str, columns: tuple[str, ...], enforce: bool): + predicate = policy_predicate(columns) + if enforce: + op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") + op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY") + op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") + op.execute( + f"CREATE POLICY {POLICY_NAME} ON {table} AS PERMISSIVE FOR ALL " + f"USING ({predicate}) WITH CHECK ({predicate})" + ) + + def upgrade(): - if op.get_bind().dialect.name != "postgresql": + bind = op.get_bind() + if bind.dialect.name != "postgresql": return - enforce = getattr(get_settings(), "TENANT_RLS_MODE", "off") == "enforce" + enforce = get_settings().TENANT_RLS_MODE == "enforce" for table, columns in RLS_TABLES.items(): - predicate = policy_predicate(columns) - if enforce: - op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") - op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY") - op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") - op.execute( - f"CREATE POLICY {POLICY_NAME} ON {table} AS PERMISSIVE FOR ALL " - f"USING ({predicate}) WITH CHECK ({predicate})" - ) + _apply_tenant_policy(table, columns, enforce) + existing = set(sa.inspect(bind).get_table_names()) + for table, columns in LATE_RLS_TABLES.items(): + if table in existing: + _apply_tenant_policy(table, columns, enforce) for table, predicate in DELEGATED_READ_PREDICATES.items(): op.execute(f"DROP POLICY IF EXISTS {READ_POLICY_NAME} ON {table}") op.execute( @@ -128,7 +151,9 @@ def downgrade(): return for table in DELEGATED_READ_PREDICATES: op.execute(f"DROP POLICY IF EXISTS {READ_POLICY_NAME} ON {table}") - for table in RLS_TABLES: + existing = set(sa.inspect(op.get_bind()).get_table_names()) + late = [table for table in LATE_RLS_TABLES if table in existing] + for table in [*RLS_TABLES, *late]: op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") op.execute(f"ALTER TABLE {table} NO FORCE ROW LEVEL SECURITY") op.execute(f"ALTER TABLE {table} DISABLE ROW LEVEL SECURITY") diff --git a/gateway/tests/test_tenant_rls_migration.py b/gateway/tests/test_tenant_rls_migration.py new file mode 100644 index 000000000..e9b726aa1 --- /dev/null +++ b/gateway/tests/test_tenant_rls_migration.py @@ -0,0 +1,105 @@ +"""TENANT_RLS_MODE setting and 048 under forced RLS on PostgreSQL (opt-in).""" + +import asyncio +import importlib.util +import os +from pathlib import Path + +import pytest +from alembic import command +from alembic.config import Config + +from app.core.config import Settings, get_settings +from tests.support import db_gate + +MIGRATION = Path(__file__).parents[1] / "migrations/versions/048_tenant_rls.py" + + +def _load_048(): + spec = importlib.util.spec_from_file_location("m048", MIGRATION) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_tenant_rls_mode_setting_matches_archived_api(): + assert Settings().TENANT_RLS_MODE == "off" + assert Settings(TENANT_RLS_MODE=" Enforce ").TENANT_RLS_MODE == "enforce" + with pytest.raises(ValueError, match="TENANT_RLS_MODE must be"): + Settings(TENANT_RLS_MODE="enforced") + + +def test_048_covers_wallet_scoped_resolution_tables(): + module = _load_048() + assert module.LATE_RLS_TABLES == { + "receipt_resolutions": ("wallet_id",), + "resolution_chain_heads": ("wallet_id",), + } + assert not set(module.LATE_RLS_TABLES) & set(module.RLS_TABLES) + + +@db_gate.collection_mark( + url_env="TENANT_RLS_MIGRATION_DATABASE_URL", + reason="requires a fresh disposable PostgreSQL DB owned by a " + "NOSUPERUSER NOBYPASSRLS role", +) +def test_postgres_enforce_forces_rls_and_050_backfills(monkeypatch): + import asyncpg + + url = os.environ["TENANT_RLS_MIGRATION_DATABASE_URL"] + raw = url.replace("postgresql+asyncpg", "postgresql") + + def sql(statement, *, bypass=False): + async def run(): + connection = await asyncpg.connect(raw) + try: + if bypass: + await connection.execute("SET app.rls_bypass = 'on'") + if ";" in statement: + await connection.execute(statement) + return [] + return [tuple(r) for r in await connection.fetch(statement)] + finally: + await connection.close() + + return asyncio.run(run()) + + assert sql( + "SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user" + ) == [(False,)] + assert sql("SELECT count(*) FROM pg_tables WHERE schemaname='public'") == [(0,)], ( + "refuse reused migration DB" + ) + monkeypatch.setenv("DATABASE_URL", url) + monkeypatch.setattr(get_settings(), "TENANT_RLS_MODE", "enforce") + + def upgrade(target): + command.upgrade(Config("alembic.ini"), target) + asyncio.set_event_loop(asyncio.new_event_loop()) + + upgrade("049_demo_key_attribution") + # Minimal seed (no migration creates api_keys rows), under the RLS bypass. + sql( + "INSERT INTO wallets (wallet_id,wallet_type,balance,lifetime_credits," + "lifetime_debits,daily_spent,auto_refill,status) VALUES " + "('w1','agent',0,0,0,0,false,'active');" + "INSERT INTO api_keys (key_id,wallet_id,key_hash,key_prefix,last_used_at) " + "VALUES ('k1','w1','h1','p1',now()),('k2','w1','h2','p2',NULL);", + bypass=True, + ) + upgrade("050_demo_key_first_used") + assert sql("SELECT count(*) FROM api_keys") == [(0,)] # owner is bound + assert sql( + "SELECT count(*) FROM api_keys WHERE first_used_at IS NOT NULL", bypass=True + ) == [(1,)] + module = _load_048() + tables = sorted([*module.RLS_TABLES, *module.LATE_RLS_TABLES]) + rows = sql( + "SELECT c.relname, c.relrowsecurity, c.relforcerowsecurity, " + "EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid " + "AND p.polname = 'amw_tenant_isolation') FROM pg_class c " + "WHERE c.relkind = 'r' AND c.relname = ANY(ARRAY[" + + ",".join(f"'{t}'" for t in tables) + + "]) ORDER BY 1" + ) + assert rows == [(t, True, True, True) for t in tables] From 6d977e26f0a1c5acf561f4a238866c4e29bb5e76 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:43:49 -0700 Subject: [PATCH 10/11] feat(migrations): add opt-in TENANT_RLS_MODE=enable and PG RLS proof Keep 'off' as default; 'enable' turns on RLS without FORCE; 'enforce' forces it. Adds tests/test_tenant_rls_postgres.py covering off, enable and enforce (including LATE_RLS_TABLES). Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/core/config.py | 11 +- gateway/docs/schema-048-rollout.md | 7 +- gateway/migrations/versions/048_tenant_rls.py | 24 +- gateway/tests/test_tenant_rls_migration.py | 1 + gateway/tests/test_tenant_rls_postgres.py | 266 ++++++++++++++++++ 5 files changed, 296 insertions(+), 13 deletions(-) create mode 100644 gateway/tests/test_tenant_rls_postgres.py diff --git a/gateway/app/core/config.py b/gateway/app/core/config.py index 00b735b26..fe0b27309 100644 --- a/gateway/app/core/config.py +++ b/gateway/app/core/config.py @@ -62,8 +62,11 @@ class Settings(BaseSettings): # 048_tenant_rls), ported from the archived agent-middleware-api Settings # with the same name, default and validation. "off" (default): the # migration creates the policies but leaves RLS disabled, so nothing - # changes for any client. "enforce": migrating in this mode enables and - # forces RLS. This gateway does not yet set app.current_wallet_id per + # changes for any client. "enable" (opt-in): migrating in this mode runs + # ENABLE ROW LEVEL SECURITY but not FORCE, so the table owner, superusers + # and BYPASSRLS roles keep full access while every other role is limited + # to its app.current_wallet_id. "enforce": migrating in this mode enables + # and forces RLS. This gateway does not yet set app.current_wallet_id per # transaction, so enforce fails closed for a NOSUPERUSER NOBYPASSRLS # runtime role; see docs/schema-048-rollout.md. No effect on SQLite. TENANT_RLS_MODE: str = "off" @@ -331,8 +334,8 @@ def demo_allowed_tools_list(self) -> list[str]: def _validate_tenant_rls_mode(cls, value: str) -> str: """Only the two documented modes; a typo must not silently mean off.""" normalized = (value or "").strip().lower() - if normalized not in {"off", "enforce"}: - raise ValueError("TENANT_RLS_MODE must be 'off' or 'enforce'") + if normalized not in {"off", "enable", "enforce"}: + raise ValueError("TENANT_RLS_MODE must be 'off', 'enable' or 'enforce'") return normalized @field_validator("EXCHANGE_RATE") diff --git a/gateway/docs/schema-048-rollout.md b/gateway/docs/schema-048-rollout.md index 7ede1a20e..d4bfdf913 100644 --- a/gateway/docs/schema-048-rollout.md +++ b/gateway/docs/schema-048-rollout.md @@ -11,10 +11,15 @@ already exist. On an api-chain database they don't exist yet; `053_repair_api_lineage` creates them and applies the identical policy. `TENANT_RLS_MODE` is ported from the api Settings with the same default (`off`) -and the same validation (`off` or `enforce`). +and the same validation, plus one opt-in mode added here (`off`, `enable` or +`enforce`). - `off`: the policies exist, but row-level security stays disabled, so nothing changes. This matches the original's default. +- `enable` (opt-in, not in the original): running the migration enables RLS + without FORCE. The table owner, superusers and BYPASSRLS roles are + unaffected; any other role sees only rows for its `app.current_wallet_id` + (none when unset). - `enforce`: running the migration enables and forces RLS on every listed table. `migrations/env.py` sets `app.rls_bypass` to `on` for the migration diff --git a/gateway/migrations/versions/048_tenant_rls.py b/gateway/migrations/versions/048_tenant_rls.py index 22d775bcd..ccd37165f 100644 --- a/gateway/migrations/versions/048_tenant_rls.py +++ b/gateway/migrations/versions/048_tenant_rls.py @@ -1,4 +1,4 @@ -"""Wallet row-level security policies; enabled only under TENANT_RLS_MODE=enforce. +"""Wallet row-level security policies; enabled only under TENANT_RLS_MODE=enable/enforce. Revision ID: 048_tenant_rls Revises: 047_dispatch_reconcile_lease @@ -11,8 +11,9 @@ closed. Default off: the policies are created but row-level security stays disabled -on every table, so no client sees any change. ENABLE and FORCE ROW LEVEL -SECURITY run only when this migration executes with TENANT_RLS_MODE=enforce; +on every table, so no client sees any change. TENANT_RLS_MODE=enable runs +ENABLE ROW LEVEL SECURITY only (the owner is not bound); ENABLE and FORCE ROW +LEVEL SECURITY run only when this migration executes with TENANT_RLS_MODE=enforce; enabling later is the per-table ALTER in docs/tenant-rls.md in the api repo. Wallet columns are character varying; the setting is text, compared with the built-in text equality, so no cast is needed and the wallet indexes stay usable. @@ -115,10 +116,17 @@ def policy_predicate(columns: tuple[str, ...]) -> str: return f"({wallet_match}) OR {_BYPASS}" -def _apply_tenant_policy(table: str, columns: tuple[str, ...], enforce: bool): +def _apply_tenant_policy(table: str, columns: tuple[str, ...], mode: str): + """Create the wallet policy; ENABLE under enable/enforce, FORCE under enforce. + + Idempotent: safe to call again (053 reuses it for the late tables). + """ + if mode not in ("off", "enable", "enforce"): + raise RuntimeError(f"unknown TENANT_RLS_MODE {mode!r}") predicate = policy_predicate(columns) - if enforce: + if mode in ("enable", "enforce"): op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") + if mode == "enforce": op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY") op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") op.execute( @@ -131,13 +139,13 @@ def upgrade(): bind = op.get_bind() if bind.dialect.name != "postgresql": return - enforce = get_settings().TENANT_RLS_MODE == "enforce" + mode = get_settings().TENANT_RLS_MODE for table, columns in RLS_TABLES.items(): - _apply_tenant_policy(table, columns, enforce) + _apply_tenant_policy(table, columns, mode) existing = set(sa.inspect(bind).get_table_names()) for table, columns in LATE_RLS_TABLES.items(): if table in existing: - _apply_tenant_policy(table, columns, enforce) + _apply_tenant_policy(table, columns, mode) for table, predicate in DELEGATED_READ_PREDICATES.items(): op.execute(f"DROP POLICY IF EXISTS {READ_POLICY_NAME} ON {table}") op.execute( diff --git a/gateway/tests/test_tenant_rls_migration.py b/gateway/tests/test_tenant_rls_migration.py index e9b726aa1..c162d0724 100644 --- a/gateway/tests/test_tenant_rls_migration.py +++ b/gateway/tests/test_tenant_rls_migration.py @@ -25,6 +25,7 @@ def _load_048(): def test_tenant_rls_mode_setting_matches_archived_api(): assert Settings().TENANT_RLS_MODE == "off" assert Settings(TENANT_RLS_MODE=" Enforce ").TENANT_RLS_MODE == "enforce" + assert Settings(TENANT_RLS_MODE="enable").TENANT_RLS_MODE == "enable" with pytest.raises(ValueError, match="TENANT_RLS_MODE must be"): Settings(TENANT_RLS_MODE="enforced") diff --git a/gateway/tests/test_tenant_rls_postgres.py b/gateway/tests/test_tenant_rls_postgres.py new file mode 100644 index 000000000..646ea5644 --- /dev/null +++ b/gateway/tests/test_tenant_rls_postgres.py @@ -0,0 +1,266 @@ +"""Opt-in PostgreSQL proof for 048_tenant_rls and the 050 backfill. + +Set TENANT_RLS_PG_ADMIN_URL to a superuser URL on a disposable local server +(e.g. postgresql://postgres@127.0.0.1:5432/postgres). The test creates its own +database and two non-superuser roles, runs every migration as the database +owner, and drops everything afterwards. + +* enforce mode: 048 FORCEs RLS, so the owner itself is wallet-scoped. The 050 + backfill must still update rows (migrations/env.py sets app.rls_bypass), and + every table in RLS_TABLES (including receipt_resolutions and + resolution_chain_heads) must show only the current wallet's rows. +* default mode (off): policies exist but RLS stays disabled; a no-op for + every role. +* enable mode: RLS is enabled but not forced; the owner keeps full access and + a separate non-owner role sees only its wallet. +* the boot schema check passes against the migrated database. +""" + +from __future__ import annotations + +import asyncio +import importlib.util +import os +import re +import subprocess +import sys +import uuid +from pathlib import Path +from urllib.parse import urlsplit, urlunsplit + +import pytest + +from tests.support import db_gate + +GATEWAY_ROOT = Path(__file__).resolve().parents[1] +ADMIN_ENV = "TENANT_RLS_PG_ADMIN_URL" +W1, W2 = "wallet-rls-one", "wallet-rls-two" + +pytestmark = db_gate.collection_mark( + url_env=ADMIN_ENV, reason="requires a disposable local PostgreSQL superuser URL" +) + + +def _rls_tables() -> dict[str, tuple[str, ...]]: + path = GATEWAY_ROOT / "migrations" / "versions" / "048_tenant_rls.py" + spec = importlib.util.spec_from_file_location("m048", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return {**module.RLS_TABLES, **module.LATE_RLS_TABLES} + + +def _with(url: str, *, user: str | None = None, db: str | None = None) -> str: + parts = urlsplit(url.replace("postgresql+asyncpg", "postgresql")) + netloc = parts.netloc.rsplit("@", 1)[-1] + if user: + netloc = f"{user}@{netloc}" + elif "@" in parts.netloc: + netloc = parts.netloc + path = f"/{db}" if db else parts.path + return urlunsplit((parts.scheme, netloc, path, parts.query, "")) + + +async def _run(url: str, *statements: str, fetch: str | None = None): + import asyncpg + + conn = await asyncpg.connect(url) + try: + async with conn.transaction(): + for statement in statements: + await conn.execute(statement) + if fetch: + return [tuple(r) for r in await conn.fetch(fetch)] + finally: + await conn.close() + + +def sql(url, *statements, fetch=None): + return asyncio.run(_run(url, *statements, fetch=fetch)) + + +def migrate(url: str, revision: str, mode: str | None): + env = {**os.environ, "DATABASE_URL": url.replace("postgresql://", "postgresql+asyncpg://", 1)} + env.pop("TENANT_RLS_MODE", None) + if mode: + env["TENANT_RLS_MODE"] = mode + result = subprocess.run( + [sys.executable, "-m", "alembic", "upgrade", revision], + cwd=GATEWAY_ROOT, env=env, capture_output=True, text=True, timeout=180, + ) + assert result.returncode == 0, result.stderr[-4000:] + + +_FILL = { + "integer": "1", "bigint": "1", "smallint": "1", "numeric": "1", + "double precision": "1", "real": "1", "boolean": "false", + "timestamp without time zone": "now()", "timestamp with time zone": "now()", + "date": "current_date", "json": "'{}'", "jsonb": "'{}'", "uuid": "gen_random_uuid()", +} + + +def _seed_statements(admin_db: str, tables) -> list[str]: + """One row per wallet per table, FK triggers off (superuser, replica role).""" + tables = {"wallets": ("wallet_id",), **tables} + names = ",".join(f"'{t}'" for t in tables) + cols = sql(admin_db, fetch=( + "SELECT table_name, column_name, data_type, character_maximum_length FROM information_schema.columns " + f"WHERE table_schema='public' AND table_name IN ({names}) " + "AND is_nullable='NO' AND column_default IS NULL ORDER BY table_name, ordinal_position" + )) + required: dict[str, list[tuple[str, str, int | None]]] = {t: [] for t in tables} + for table, column, dtype, max_len in cols: + required[table].append((column, dtype, max_len)) + # Enumerated CHECKs (col IN ('a', ...)): use the first allowed literal. + allowed: dict[tuple[str, str], str] = {} + for table, definition in sql(admin_db, fetch=( + "SELECT conrelid::regclass::text, pg_get_constraintdef(oid) FROM pg_constraint " + f"WHERE contype='c' AND conrelid::regclass::text IN ({names})" + )): + match = re.search(r"\(+(\w+)\)?(?:::text)? = ANY \(\(?ARRAY\['([^']*)'", definition) + if match: + allowed[(table, match.group(1))] = f"'{match.group(2)}'" + out = ["SET LOCAL session_replication_role = replica"] + for table, wallet_cols in tables.items(): + for wallet in (W1, W2): + values = {c: f"'{wallet}'" for c in wallet_cols} + for column, dtype, max_len in required[table]: + if column in values: + continue + text = uuid.uuid4().hex[: max_len or 32] + values[column] = allowed.get( + (table, column), _FILL.get(dtype, f"'{text}'") + ) + out.append( + f"INSERT INTO {table} ({','.join(values)}) VALUES ({','.join(values.values())})" + ) + return out + + +@pytest.fixture +def cluster(): + admin = os.environ[ADMIN_ENV] + host = urlsplit(admin).hostname or "" + if host not in ("", "localhost", "127.0.0.1", "::1") and not host.startswith("/"): + pytest.fail("refusing non-local admin URL") + suffix = uuid.uuid4().hex[:8] + owner, reader, db = f"rls_owner_{suffix}", f"rls_reader_{suffix}", f"rls_proof_{suffix}" + admin_url = _with(admin) + sql(admin_url, f"CREATE ROLE {owner} LOGIN NOSUPERUSER NOBYPASSRLS") + sql(admin_url, f"CREATE ROLE {reader} LOGIN NOSUPERUSER NOBYPASSRLS") + + async def create_db(): + import asyncpg + conn = await asyncpg.connect(admin_url) + try: + await conn.execute(f"CREATE DATABASE {db} OWNER {owner}") + finally: + await conn.close() + + asyncio.run(create_db()) + try: + yield { + "admin": _with(admin, db=db), + "owner": _with(admin, user=owner, db=db), + "reader": _with(admin, user=reader, db=db), + "reader_role": reader, + } + finally: + async def drop(): + import asyncpg + conn = await asyncpg.connect(admin_url) + try: + await conn.execute(f"DROP DATABASE IF EXISTS {db} WITH (FORCE)") + await conn.execute(f"DROP ROLE IF EXISTS {owner}") + await conn.execute(f"DROP ROLE IF EXISTS {reader}") + finally: + await conn.close() + + asyncio.run(drop()) + + +def _visible(url: str, table: str, cols, wallet: str | None) -> set[str]: + scope = [f"SELECT set_config('app.current_wallet_id', '{wallet}', true)"] if wallet else [] + rows = sql(url, *scope, fetch=f"SELECT DISTINCT {cols[0]} FROM {table}") + return {r[0] for r in rows} + + +def test_enforce_mode_force_rls_isolates_every_table_and_backfill_runs(cluster): + tables = _rls_tables() + assert {"receipt_resolutions", "resolution_chain_heads"} <= set(tables) + migrate(cluster["owner"], "049_demo_key_attribution", "enforce") + flags = dict( + (r[0], (r[1], r[2])) + for r in sql(cluster["admin"], fetch=( + "SELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class " + "WHERE relnamespace='public'::regnamespace AND relkind='r'" + )) + ) + for table in tables: + assert flags[table] == (True, True), table + # Seed rows before 050 so its backfill has work to do under FORCE. + sql(cluster["admin"], *_seed_statements(cluster["admin"], tables)) + sql(cluster["admin"], "UPDATE api_keys SET last_used_at = now(), first_used_at = NULL") + migrate(cluster["owner"], "head", "enforce") + backfilled = sql(cluster["admin"], fetch=( + "SELECT count(*) FROM api_keys WHERE first_used_at IS NOT NULL" + ))[0][0] + assert backfilled == 2 + + for table, cols in tables.items(): + assert _visible(cluster["owner"], table, cols, None) == set(), table + assert _visible(cluster["owner"], table, cols, W1) == {W1}, table + assert _visible(cluster["owner"], table, cols, W2) == {W2}, table + # WITH CHECK: the owner cannot move a visible row into another wallet + # (every wallet column, since any one matching admits the row). + with pytest.raises(Exception, match="row-level security"): + sql( + cluster["owner"], + f"SELECT set_config('app.current_wallet_id', '{W1}', true)", + f"UPDATE {table} SET " + + ", ".join(f"{c} = '{W2}'" for c in cols) + + f" WHERE {cols[0]} = '{W1}'", + ) + + from sqlalchemy.ext.asyncio import create_async_engine + from app.db.database import verify_required_schema + + async def boot_check(): + engine = create_async_engine( + cluster["owner"].replace("postgresql://", "postgresql+asyncpg://", 1) + ) + try: + await verify_required_schema(engine) + finally: + await engine.dispose() + + asyncio.run(boot_check()) + + +@pytest.mark.parametrize("mode", [None, "enable"], ids=["default-off", "enable"]) +def test_off_is_noop_and_enable_isolates_non_owner_roles(cluster, mode): + tables = _rls_tables() + migrate(cluster["owner"], "head", mode) + flags = dict( + (r[0], (r[1], r[2])) + for r in sql(cluster["admin"], fetch=( + "SELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class " + "WHERE relnamespace='public'::regnamespace AND relkind='r'" + )) + ) + policies = { + r[0] + for r in sql(cluster["admin"], fetch=( + "SELECT tablename FROM pg_policies WHERE policyname='amw_tenant_isolation'" + )) + } + sql(cluster["admin"], *_seed_statements(cluster["admin"], tables)) + sql(cluster["owner"], f"GRANT SELECT ON ALL TABLES IN SCHEMA public TO {cluster['reader_role']}") + enabled = mode == "enable" + for table, cols in tables.items(): + assert table in policies, table + assert flags[table] == (enabled, False), table + assert _visible(cluster["owner"], table, cols, None) == {W1, W2}, table + expected_unscoped = set() if enabled else {W1, W2} + assert _visible(cluster["reader"], table, cols, None) == expected_unscoped, table + expected_w1 = {W1} if enabled else {W1, W2} + assert _visible(cluster["reader"], table, cols, W1) == expected_w1, table From e62d99e2a92a6240bf28fa2e883b0470ae73c9ca Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:51:06 -0700 Subject: [PATCH 11/11] Revert "feat(migrations): add opt-in TENANT_RLS_MODE=enable and PG RLS proof" This reverts commit 6d977e26f0a1c5acf561f4a238866c4e29bb5e76. Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/core/config.py | 11 +- gateway/docs/schema-048-rollout.md | 7 +- gateway/migrations/versions/048_tenant_rls.py | 24 +- gateway/tests/test_tenant_rls_migration.py | 1 - gateway/tests/test_tenant_rls_postgres.py | 266 ------------------ 5 files changed, 13 insertions(+), 296 deletions(-) delete mode 100644 gateway/tests/test_tenant_rls_postgres.py diff --git a/gateway/app/core/config.py b/gateway/app/core/config.py index fe0b27309..00b735b26 100644 --- a/gateway/app/core/config.py +++ b/gateway/app/core/config.py @@ -62,11 +62,8 @@ class Settings(BaseSettings): # 048_tenant_rls), ported from the archived agent-middleware-api Settings # with the same name, default and validation. "off" (default): the # migration creates the policies but leaves RLS disabled, so nothing - # changes for any client. "enable" (opt-in): migrating in this mode runs - # ENABLE ROW LEVEL SECURITY but not FORCE, so the table owner, superusers - # and BYPASSRLS roles keep full access while every other role is limited - # to its app.current_wallet_id. "enforce": migrating in this mode enables - # and forces RLS. This gateway does not yet set app.current_wallet_id per + # changes for any client. "enforce": migrating in this mode enables and + # forces RLS. This gateway does not yet set app.current_wallet_id per # transaction, so enforce fails closed for a NOSUPERUSER NOBYPASSRLS # runtime role; see docs/schema-048-rollout.md. No effect on SQLite. TENANT_RLS_MODE: str = "off" @@ -334,8 +331,8 @@ def demo_allowed_tools_list(self) -> list[str]: def _validate_tenant_rls_mode(cls, value: str) -> str: """Only the two documented modes; a typo must not silently mean off.""" normalized = (value or "").strip().lower() - if normalized not in {"off", "enable", "enforce"}: - raise ValueError("TENANT_RLS_MODE must be 'off', 'enable' or 'enforce'") + if normalized not in {"off", "enforce"}: + raise ValueError("TENANT_RLS_MODE must be 'off' or 'enforce'") return normalized @field_validator("EXCHANGE_RATE") diff --git a/gateway/docs/schema-048-rollout.md b/gateway/docs/schema-048-rollout.md index d4bfdf913..7ede1a20e 100644 --- a/gateway/docs/schema-048-rollout.md +++ b/gateway/docs/schema-048-rollout.md @@ -11,15 +11,10 @@ already exist. On an api-chain database they don't exist yet; `053_repair_api_lineage` creates them and applies the identical policy. `TENANT_RLS_MODE` is ported from the api Settings with the same default (`off`) -and the same validation, plus one opt-in mode added here (`off`, `enable` or -`enforce`). +and the same validation (`off` or `enforce`). - `off`: the policies exist, but row-level security stays disabled, so nothing changes. This matches the original's default. -- `enable` (opt-in, not in the original): running the migration enables RLS - without FORCE. The table owner, superusers and BYPASSRLS roles are - unaffected; any other role sees only rows for its `app.current_wallet_id` - (none when unset). - `enforce`: running the migration enables and forces RLS on every listed table. `migrations/env.py` sets `app.rls_bypass` to `on` for the migration diff --git a/gateway/migrations/versions/048_tenant_rls.py b/gateway/migrations/versions/048_tenant_rls.py index ccd37165f..22d775bcd 100644 --- a/gateway/migrations/versions/048_tenant_rls.py +++ b/gateway/migrations/versions/048_tenant_rls.py @@ -1,4 +1,4 @@ -"""Wallet row-level security policies; enabled only under TENANT_RLS_MODE=enable/enforce. +"""Wallet row-level security policies; enabled only under TENANT_RLS_MODE=enforce. Revision ID: 048_tenant_rls Revises: 047_dispatch_reconcile_lease @@ -11,9 +11,8 @@ closed. Default off: the policies are created but row-level security stays disabled -on every table, so no client sees any change. TENANT_RLS_MODE=enable runs -ENABLE ROW LEVEL SECURITY only (the owner is not bound); ENABLE and FORCE ROW -LEVEL SECURITY run only when this migration executes with TENANT_RLS_MODE=enforce; +on every table, so no client sees any change. ENABLE and FORCE ROW LEVEL +SECURITY run only when this migration executes with TENANT_RLS_MODE=enforce; enabling later is the per-table ALTER in docs/tenant-rls.md in the api repo. Wallet columns are character varying; the setting is text, compared with the built-in text equality, so no cast is needed and the wallet indexes stay usable. @@ -116,17 +115,10 @@ def policy_predicate(columns: tuple[str, ...]) -> str: return f"({wallet_match}) OR {_BYPASS}" -def _apply_tenant_policy(table: str, columns: tuple[str, ...], mode: str): - """Create the wallet policy; ENABLE under enable/enforce, FORCE under enforce. - - Idempotent: safe to call again (053 reuses it for the late tables). - """ - if mode not in ("off", "enable", "enforce"): - raise RuntimeError(f"unknown TENANT_RLS_MODE {mode!r}") +def _apply_tenant_policy(table: str, columns: tuple[str, ...], enforce: bool): predicate = policy_predicate(columns) - if mode in ("enable", "enforce"): + if enforce: op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") - if mode == "enforce": op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY") op.execute(f"DROP POLICY IF EXISTS {POLICY_NAME} ON {table}") op.execute( @@ -139,13 +131,13 @@ def upgrade(): bind = op.get_bind() if bind.dialect.name != "postgresql": return - mode = get_settings().TENANT_RLS_MODE + enforce = get_settings().TENANT_RLS_MODE == "enforce" for table, columns in RLS_TABLES.items(): - _apply_tenant_policy(table, columns, mode) + _apply_tenant_policy(table, columns, enforce) existing = set(sa.inspect(bind).get_table_names()) for table, columns in LATE_RLS_TABLES.items(): if table in existing: - _apply_tenant_policy(table, columns, mode) + _apply_tenant_policy(table, columns, enforce) for table, predicate in DELEGATED_READ_PREDICATES.items(): op.execute(f"DROP POLICY IF EXISTS {READ_POLICY_NAME} ON {table}") op.execute( diff --git a/gateway/tests/test_tenant_rls_migration.py b/gateway/tests/test_tenant_rls_migration.py index c162d0724..e9b726aa1 100644 --- a/gateway/tests/test_tenant_rls_migration.py +++ b/gateway/tests/test_tenant_rls_migration.py @@ -25,7 +25,6 @@ def _load_048(): def test_tenant_rls_mode_setting_matches_archived_api(): assert Settings().TENANT_RLS_MODE == "off" assert Settings(TENANT_RLS_MODE=" Enforce ").TENANT_RLS_MODE == "enforce" - assert Settings(TENANT_RLS_MODE="enable").TENANT_RLS_MODE == "enable" with pytest.raises(ValueError, match="TENANT_RLS_MODE must be"): Settings(TENANT_RLS_MODE="enforced") diff --git a/gateway/tests/test_tenant_rls_postgres.py b/gateway/tests/test_tenant_rls_postgres.py deleted file mode 100644 index 646ea5644..000000000 --- a/gateway/tests/test_tenant_rls_postgres.py +++ /dev/null @@ -1,266 +0,0 @@ -"""Opt-in PostgreSQL proof for 048_tenant_rls and the 050 backfill. - -Set TENANT_RLS_PG_ADMIN_URL to a superuser URL on a disposable local server -(e.g. postgresql://postgres@127.0.0.1:5432/postgres). The test creates its own -database and two non-superuser roles, runs every migration as the database -owner, and drops everything afterwards. - -* enforce mode: 048 FORCEs RLS, so the owner itself is wallet-scoped. The 050 - backfill must still update rows (migrations/env.py sets app.rls_bypass), and - every table in RLS_TABLES (including receipt_resolutions and - resolution_chain_heads) must show only the current wallet's rows. -* default mode (off): policies exist but RLS stays disabled; a no-op for - every role. -* enable mode: RLS is enabled but not forced; the owner keeps full access and - a separate non-owner role sees only its wallet. -* the boot schema check passes against the migrated database. -""" - -from __future__ import annotations - -import asyncio -import importlib.util -import os -import re -import subprocess -import sys -import uuid -from pathlib import Path -from urllib.parse import urlsplit, urlunsplit - -import pytest - -from tests.support import db_gate - -GATEWAY_ROOT = Path(__file__).resolve().parents[1] -ADMIN_ENV = "TENANT_RLS_PG_ADMIN_URL" -W1, W2 = "wallet-rls-one", "wallet-rls-two" - -pytestmark = db_gate.collection_mark( - url_env=ADMIN_ENV, reason="requires a disposable local PostgreSQL superuser URL" -) - - -def _rls_tables() -> dict[str, tuple[str, ...]]: - path = GATEWAY_ROOT / "migrations" / "versions" / "048_tenant_rls.py" - spec = importlib.util.spec_from_file_location("m048", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return {**module.RLS_TABLES, **module.LATE_RLS_TABLES} - - -def _with(url: str, *, user: str | None = None, db: str | None = None) -> str: - parts = urlsplit(url.replace("postgresql+asyncpg", "postgresql")) - netloc = parts.netloc.rsplit("@", 1)[-1] - if user: - netloc = f"{user}@{netloc}" - elif "@" in parts.netloc: - netloc = parts.netloc - path = f"/{db}" if db else parts.path - return urlunsplit((parts.scheme, netloc, path, parts.query, "")) - - -async def _run(url: str, *statements: str, fetch: str | None = None): - import asyncpg - - conn = await asyncpg.connect(url) - try: - async with conn.transaction(): - for statement in statements: - await conn.execute(statement) - if fetch: - return [tuple(r) for r in await conn.fetch(fetch)] - finally: - await conn.close() - - -def sql(url, *statements, fetch=None): - return asyncio.run(_run(url, *statements, fetch=fetch)) - - -def migrate(url: str, revision: str, mode: str | None): - env = {**os.environ, "DATABASE_URL": url.replace("postgresql://", "postgresql+asyncpg://", 1)} - env.pop("TENANT_RLS_MODE", None) - if mode: - env["TENANT_RLS_MODE"] = mode - result = subprocess.run( - [sys.executable, "-m", "alembic", "upgrade", revision], - cwd=GATEWAY_ROOT, env=env, capture_output=True, text=True, timeout=180, - ) - assert result.returncode == 0, result.stderr[-4000:] - - -_FILL = { - "integer": "1", "bigint": "1", "smallint": "1", "numeric": "1", - "double precision": "1", "real": "1", "boolean": "false", - "timestamp without time zone": "now()", "timestamp with time zone": "now()", - "date": "current_date", "json": "'{}'", "jsonb": "'{}'", "uuid": "gen_random_uuid()", -} - - -def _seed_statements(admin_db: str, tables) -> list[str]: - """One row per wallet per table, FK triggers off (superuser, replica role).""" - tables = {"wallets": ("wallet_id",), **tables} - names = ",".join(f"'{t}'" for t in tables) - cols = sql(admin_db, fetch=( - "SELECT table_name, column_name, data_type, character_maximum_length FROM information_schema.columns " - f"WHERE table_schema='public' AND table_name IN ({names}) " - "AND is_nullable='NO' AND column_default IS NULL ORDER BY table_name, ordinal_position" - )) - required: dict[str, list[tuple[str, str, int | None]]] = {t: [] for t in tables} - for table, column, dtype, max_len in cols: - required[table].append((column, dtype, max_len)) - # Enumerated CHECKs (col IN ('a', ...)): use the first allowed literal. - allowed: dict[tuple[str, str], str] = {} - for table, definition in sql(admin_db, fetch=( - "SELECT conrelid::regclass::text, pg_get_constraintdef(oid) FROM pg_constraint " - f"WHERE contype='c' AND conrelid::regclass::text IN ({names})" - )): - match = re.search(r"\(+(\w+)\)?(?:::text)? = ANY \(\(?ARRAY\['([^']*)'", definition) - if match: - allowed[(table, match.group(1))] = f"'{match.group(2)}'" - out = ["SET LOCAL session_replication_role = replica"] - for table, wallet_cols in tables.items(): - for wallet in (W1, W2): - values = {c: f"'{wallet}'" for c in wallet_cols} - for column, dtype, max_len in required[table]: - if column in values: - continue - text = uuid.uuid4().hex[: max_len or 32] - values[column] = allowed.get( - (table, column), _FILL.get(dtype, f"'{text}'") - ) - out.append( - f"INSERT INTO {table} ({','.join(values)}) VALUES ({','.join(values.values())})" - ) - return out - - -@pytest.fixture -def cluster(): - admin = os.environ[ADMIN_ENV] - host = urlsplit(admin).hostname or "" - if host not in ("", "localhost", "127.0.0.1", "::1") and not host.startswith("/"): - pytest.fail("refusing non-local admin URL") - suffix = uuid.uuid4().hex[:8] - owner, reader, db = f"rls_owner_{suffix}", f"rls_reader_{suffix}", f"rls_proof_{suffix}" - admin_url = _with(admin) - sql(admin_url, f"CREATE ROLE {owner} LOGIN NOSUPERUSER NOBYPASSRLS") - sql(admin_url, f"CREATE ROLE {reader} LOGIN NOSUPERUSER NOBYPASSRLS") - - async def create_db(): - import asyncpg - conn = await asyncpg.connect(admin_url) - try: - await conn.execute(f"CREATE DATABASE {db} OWNER {owner}") - finally: - await conn.close() - - asyncio.run(create_db()) - try: - yield { - "admin": _with(admin, db=db), - "owner": _with(admin, user=owner, db=db), - "reader": _with(admin, user=reader, db=db), - "reader_role": reader, - } - finally: - async def drop(): - import asyncpg - conn = await asyncpg.connect(admin_url) - try: - await conn.execute(f"DROP DATABASE IF EXISTS {db} WITH (FORCE)") - await conn.execute(f"DROP ROLE IF EXISTS {owner}") - await conn.execute(f"DROP ROLE IF EXISTS {reader}") - finally: - await conn.close() - - asyncio.run(drop()) - - -def _visible(url: str, table: str, cols, wallet: str | None) -> set[str]: - scope = [f"SELECT set_config('app.current_wallet_id', '{wallet}', true)"] if wallet else [] - rows = sql(url, *scope, fetch=f"SELECT DISTINCT {cols[0]} FROM {table}") - return {r[0] for r in rows} - - -def test_enforce_mode_force_rls_isolates_every_table_and_backfill_runs(cluster): - tables = _rls_tables() - assert {"receipt_resolutions", "resolution_chain_heads"} <= set(tables) - migrate(cluster["owner"], "049_demo_key_attribution", "enforce") - flags = dict( - (r[0], (r[1], r[2])) - for r in sql(cluster["admin"], fetch=( - "SELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class " - "WHERE relnamespace='public'::regnamespace AND relkind='r'" - )) - ) - for table in tables: - assert flags[table] == (True, True), table - # Seed rows before 050 so its backfill has work to do under FORCE. - sql(cluster["admin"], *_seed_statements(cluster["admin"], tables)) - sql(cluster["admin"], "UPDATE api_keys SET last_used_at = now(), first_used_at = NULL") - migrate(cluster["owner"], "head", "enforce") - backfilled = sql(cluster["admin"], fetch=( - "SELECT count(*) FROM api_keys WHERE first_used_at IS NOT NULL" - ))[0][0] - assert backfilled == 2 - - for table, cols in tables.items(): - assert _visible(cluster["owner"], table, cols, None) == set(), table - assert _visible(cluster["owner"], table, cols, W1) == {W1}, table - assert _visible(cluster["owner"], table, cols, W2) == {W2}, table - # WITH CHECK: the owner cannot move a visible row into another wallet - # (every wallet column, since any one matching admits the row). - with pytest.raises(Exception, match="row-level security"): - sql( - cluster["owner"], - f"SELECT set_config('app.current_wallet_id', '{W1}', true)", - f"UPDATE {table} SET " - + ", ".join(f"{c} = '{W2}'" for c in cols) - + f" WHERE {cols[0]} = '{W1}'", - ) - - from sqlalchemy.ext.asyncio import create_async_engine - from app.db.database import verify_required_schema - - async def boot_check(): - engine = create_async_engine( - cluster["owner"].replace("postgresql://", "postgresql+asyncpg://", 1) - ) - try: - await verify_required_schema(engine) - finally: - await engine.dispose() - - asyncio.run(boot_check()) - - -@pytest.mark.parametrize("mode", [None, "enable"], ids=["default-off", "enable"]) -def test_off_is_noop_and_enable_isolates_non_owner_roles(cluster, mode): - tables = _rls_tables() - migrate(cluster["owner"], "head", mode) - flags = dict( - (r[0], (r[1], r[2])) - for r in sql(cluster["admin"], fetch=( - "SELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class " - "WHERE relnamespace='public'::regnamespace AND relkind='r'" - )) - ) - policies = { - r[0] - for r in sql(cluster["admin"], fetch=( - "SELECT tablename FROM pg_policies WHERE policyname='amw_tenant_isolation'" - )) - } - sql(cluster["admin"], *_seed_statements(cluster["admin"], tables)) - sql(cluster["owner"], f"GRANT SELECT ON ALL TABLES IN SCHEMA public TO {cluster['reader_role']}") - enabled = mode == "enable" - for table, cols in tables.items(): - assert table in policies, table - assert flags[table] == (enabled, False), table - assert _visible(cluster["owner"], table, cols, None) == {W1, W2}, table - expected_unscoped = set() if enabled else {W1, W2} - assert _visible(cluster["reader"], table, cols, None) == expected_unscoped, table - expected_w1 = {W1} if enabled else {W1, W2} - assert _visible(cluster["reader"], table, cols, W1) == expected_w1, table