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 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 From eb10c0121bffd91883ed53988d4f9ed38a67fc9e Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:21:47 -0700 Subject: [PATCH 6/7] test(migrations): avoid head pins and cover 047/048 negative paths Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/tests/test_047_048_negative_paths.py | 128 ++++++++++++++++++ .../tests/test_api_chain_port_migrations.py | 21 +-- 2 files changed, 140 insertions(+), 9 deletions(-) create mode 100644 gateway/tests/test_047_048_negative_paths.py diff --git a/gateway/tests/test_047_048_negative_paths.py b/gateway/tests/test_047_048_negative_paths.py new file mode 100644 index 000000000..3d464a157 --- /dev/null +++ b/gateway/tests/test_047_048_negative_paths.py @@ -0,0 +1,128 @@ +"""Negative paths for ported 047 (reconcile lease) and 048 (tenant RLS).""" + +import asyncio +import os + +import pytest +from alembic import command +from alembic.config import Config +from sqlalchemy import create_engine, inspect, text + +from tests.test_api_chain_port_migrations import RECONCILE_COLUMNS, RECONCILE_INDEXES + + +def _config(tmp_path, monkeypatch): + db_path = tmp_path / "neg.db" + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + return Config("alembic.ini"), f"sqlite:///{db_path}" + + +def _run(fn, config, target): + fn(config, target) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def _insert_attempt(conn, **overrides): + """Insert one mcp_dispatch_attempts row, filling NOT NULL columns by type.""" + values = {} + for col in inspect(conn).get_columns("mcp_dispatch_attempts"): + name = col["name"] + if name in overrides: + values[name] = overrides[name] + elif not col["nullable"] and col.get("default") is None and not col.get( + "autoincrement" + ): + kind = str(col["type"]).upper() + if "INT" in kind or "NUMERIC" in kind or "FLOAT" in kind: + values[name] = 0 + elif "BOOL" in kind: + values[name] = False + elif "DATE" in kind or "TIME" in kind: + values[name] = "2026-01-01 00:00:00" + else: + values[name] = f"{name}-1" + names = ", ".join(values) + params = ", ".join(f":{n}" for n in values) + conn.execute(text(f"INSERT INTO mcp_dispatch_attempts ({names}) VALUES ({params})"), values) + + +def test_047_downgrade_refuses_when_reconcile_status_is_set(tmp_path, monkeypatch): + config, sync_url = _config(tmp_path, monkeypatch) + _run(command.upgrade, config, "047_dispatch_reconcile_lease") + engine = create_engine(sync_url) + with engine.begin() as conn: + _insert_attempt(conn, reconcile_status="refunded") + engine.dispose() + with pytest.raises(RuntimeError, match="047 downgrade refused: 1 dispatch"): + _run(command.downgrade, config, "046_api_key_usage_events") + engine = create_engine(sync_url) + cols = {c["name"] for c in inspect(engine).get_columns("mcp_dispatch_attempts")} + with engine.connect() as conn: + version = conn.execute(text("SELECT version_num FROM alembic_version")).scalar() + engine.dispose() + assert RECONCILE_COLUMNS <= cols + assert version == "047_dispatch_reconcile_lease" + + +def test_047_upgrade_fills_in_partially_existing_columns_and_indexes( + tmp_path, monkeypatch +): + config, sync_url = _config(tmp_path, monkeypatch) + _run(command.upgrade, config, "046_api_key_usage_events") + engine = create_engine(sync_url) + with engine.begin() as conn: + conn.execute( + text("ALTER TABLE mcp_dispatch_attempts ADD COLUMN reconcile_status VARCHAR(32)") + ) + conn.execute( + text( + "CREATE INDEX ix_mcp_dispatch_attempts_reconcile_status " + "ON mcp_dispatch_attempts (reconcile_status)" + ) + ) + engine.dispose() + _run(command.upgrade, config, "047_dispatch_reconcile_lease") + engine = create_engine(sync_url) + insp = inspect(engine) + cols = [c["name"] for c in insp.get_columns("mcp_dispatch_attempts")] + idx = {i["name"] for i in insp.get_indexes("mcp_dispatch_attempts")} + engine.dispose() + assert RECONCILE_COLUMNS <= set(cols) + assert cols.count("reconcile_status") == 1 + assert RECONCILE_INDEXES <= idx + + +@pytest.mark.skipif( + not os.environ.get("TENANT_RLS_OFF_MIGRATION_DATABASE_URL"), + reason="set TENANT_RLS_OFF_MIGRATION_DATABASE_URL to an empty PostgreSQL DB", +) +def test_postgres_default_off_creates_policies_but_leaves_rls_disabled(monkeypatch): + import asyncpg + + from app.core.config import get_settings + + url = os.environ["TENANT_RLS_OFF_MIGRATION_DATABASE_URL"] + raw = url.replace("postgresql+asyncpg", "postgresql") + + def fetch(statement): + async def run(): + connection = await asyncpg.connect(raw) + try: + return [tuple(r) for r in await connection.fetch(statement)] + finally: + await connection.close() + + return asyncio.run(run()) + + assert fetch("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", "off") + _run(command.upgrade, Config("alembic.ini"), "head") + policies = {r[0] for r in fetch("SELECT DISTINCT polname FROM pg_policy")} + assert {"amw_tenant_isolation", "amw_delegated_issuer_read"} <= policies + assert fetch( + "SELECT count(*) FROM pg_class WHERE relnamespace = 'public'::regnamespace " + "AND relkind = 'r' AND (relrowsecurity OR relforcerowsecurity)" + ) == [(0,)] diff --git a/gateway/tests/test_api_chain_port_migrations.py b/gateway/tests/test_api_chain_port_migrations.py index 8ff05d347..4d54fa011 100644 --- a/gateway/tests/test_api_chain_port_migrations.py +++ b/gateway/tests/test_api_chain_port_migrations.py @@ -40,7 +40,7 @@ def _downgrade(config, target): def test_single_head_and_ported_order(): script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["050_demo_key_first_used"] + assert len(script.get_heads()) == 1 chain = { "047_dispatch_reconcile_lease": "046_api_key_usage_events", "048_tenant_rls": "047_dispatch_reconcile_lease", @@ -53,7 +53,8 @@ def test_single_head_and_ported_order(): def test_fresh_upgrade_to_head_and_round_trip(tmp_path, monkeypatch): config, sync_url = _config(tmp_path, monkeypatch) - _upgrade(config, "head") + # 051 refuses SQLite downgrade, so the round trip runs at the ported 050. + _upgrade(config, "050_demo_key_first_used") engine = create_engine(sync_url) insp = inspect(engine) cols = {c["name"] for c in insp.get_columns("mcp_dispatch_attempts")} @@ -68,9 +69,10 @@ def test_fresh_upgrade_to_head_and_round_trip(tmp_path, monkeypatch): ): 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") + 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") @@ -93,11 +95,12 @@ def test_fresh_upgrade_to_head_and_round_trip(tmp_path, monkeypatch): 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") _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") + assert ( + conn.execute(text("SELECT version_num FROM alembic_version")).scalar() + == ScriptDirectory.from_config(config).get_current_head() + ) engine.dispose() From f00ff66890ddf78c027960dedc2e799a2d791c24 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:24:54 -0700 Subject: [PATCH 7/7] style(tests): ruff format 047/048 negative-path tests Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/tests/test_047_048_negative_paths.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/gateway/tests/test_047_048_negative_paths.py b/gateway/tests/test_047_048_negative_paths.py index 3d464a157..549f47179 100644 --- a/gateway/tests/test_047_048_negative_paths.py +++ b/gateway/tests/test_047_048_negative_paths.py @@ -29,8 +29,10 @@ def _insert_attempt(conn, **overrides): name = col["name"] if name in overrides: values[name] = overrides[name] - elif not col["nullable"] and col.get("default") is None and not col.get( - "autoincrement" + elif ( + not col["nullable"] + and col.get("default") is None + and not col.get("autoincrement") ): kind = str(col["type"]).upper() if "INT" in kind or "NUMERIC" in kind or "FLOAT" in kind: @@ -43,7 +45,9 @@ def _insert_attempt(conn, **overrides): values[name] = f"{name}-1" names = ", ".join(values) params = ", ".join(f":{n}" for n in values) - conn.execute(text(f"INSERT INTO mcp_dispatch_attempts ({names}) VALUES ({params})"), values) + conn.execute( + text(f"INSERT INTO mcp_dispatch_attempts ({names}) VALUES ({params})"), values + ) def test_047_downgrade_refuses_when_reconcile_status_is_set(tmp_path, monkeypatch): @@ -72,7 +76,9 @@ def test_047_upgrade_fills_in_partially_existing_columns_and_indexes( engine = create_engine(sync_url) with engine.begin() as conn: conn.execute( - text("ALTER TABLE mcp_dispatch_attempts ADD COLUMN reconcile_status VARCHAR(32)") + text( + "ALTER TABLE mcp_dispatch_attempts ADD COLUMN reconcile_status VARCHAR(32)" + ) ) conn.execute( text( @@ -114,9 +120,9 @@ async def run(): return asyncio.run(run()) - assert fetch("SELECT count(*) FROM pg_tables WHERE schemaname='public'") == [(0,)], ( - "refuse reused migration DB" - ) + assert fetch("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", "off") _run(command.upgrade, Config("alembic.ini"), "head")