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/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/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..7ede1a20e --- /dev/null +++ b/gateway/docs/schema-048-rollout.md @@ -0,0 +1,39 @@ +# Schema 048: tenant RLS policies (ported) + +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 + +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 + +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/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/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/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..22d775bcd --- /dev/null +++ b/gateway/migrations/versions/048_tenant_rls.py @@ -0,0 +1,159 @@ +"""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 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 +``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. ``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 + +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",), +} + +# 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'" + +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 _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(): + bind = op.get_bind() + if bind.dialect.name != "postgresql": + return + enforce = get_settings().TENANT_RLS_MODE == "enforce" + for table, columns in RLS_TABLES.items(): + _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( + 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}") + 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/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_047_048_negative_paths.py b/gateway/tests/test_047_048_negative_paths.py new file mode 100644 index 000000000..549f47179 --- /dev/null +++ b/gateway/tests/test_047_048_negative_paths.py @@ -0,0 +1,134 @@ +"""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 new file mode 100644 index 000000000..4d54fa011 --- /dev/null +++ b/gateway/tests/test_api_chain_port_migrations.py @@ -0,0 +1,106 @@ +"""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 len(script.get_heads()) == 1 + 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) + # 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")} + 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, "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() + == ScriptDirectory.from_config(config).get_current_head() + ) + 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" ) 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}" ) 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]