diff --git a/CHANGELOG.md b/CHANGELOG.md index 59dda7db7..39fa9d371 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ This repository starts with a fresh history. Releases are listed here once tagge - Receipts: new optional signed fields `enforcement_mode` ("enforce" or "permissive") and `gateway_build` (build commit). Each is signed only when set, so older receipts still verify. Migration 052 adds the columns. +- Migrations: 053 recreates `receipt_resolutions`, `resolution_chain_heads`, + `approval_gate_approvals`, `api_key_usage_events` and the `api_key_usage_daily` + view on databases built by the archived api chain, only when missing. - Replay: whitespace-only recorded `approval_id` now raises `ReplayError` like the empty string, and `amw-replay` writes `receipts.jsonl`, `summary.json`, and `keys.json` atomically (temp file in the output dir, then rename), leaving no diff --git a/gateway/docs/schema-053-rollout.md b/gateway/docs/schema-053-rollout.md new file mode 100644 index 000000000..118a9faee --- /dev/null +++ b/gateway/docs/schema-053-rollout.md @@ -0,0 +1,34 @@ +# Schema 053: repair databases built by the archived api chain + +Migration `053_repair_api_lineage` revises `052_receipt_mode_build`. A database +that reached `050_demo_key_first_used` through the archived agent-middleware-api +chain never ran this repo's 044-046, so it lacks `receipt_resolutions`, +`resolution_chain_heads`, `approval_gate_approvals`, `api_key_usage_events` and +the `api_key_usage_daily` view. 053 creates each one only when absent, with the +columns, indexes and constraints of 044-046, and writes no rows. On a database +built from this chain it changes nothing. + +On PostgreSQL, 053 also gives `receipt_resolutions` and +`resolution_chain_heads` the `amw_tenant_isolation` policy from +`048_tenant_rls` wherever that policy is missing. This is the case on an +api-chain database, because 048 ran there before these tables existed. RLS is +enabled and forced on them when `TENANT_RLS_MODE` is `enforce`, or when +`api_keys` already has forced RLS. A fresh database and a repaired api-chain +database therefore end up with identical policies. Downgrade leaves the +policies in place, together with the tables. + +The api-only tables such as `insight_reporting_principals` are left in place. + +## Compatibility release + +Production boot requires the database revision to match the packaged head, so +a 052-packaged image cannot restart after 053 is applied. Qualify a +053-capable image against a disposable PostgreSQL copy of the database first. +These release checks have not been run against staging or production. + +## Rollback + +Downgrade is a documented no-op. After upgrade nothing records whether 053 or +044-046 created an object, so dropping them could destroy tables a fresh +chain owns. Rolling back to 052 leaves the repaired objects in place, which is +compatible with 052 code. diff --git a/gateway/migrations/versions/053_repair_api_lineage.py b/gateway/migrations/versions/053_repair_api_lineage.py new file mode 100644 index 000000000..218a0ce0e --- /dev/null +++ b/gateway/migrations/versions/053_repair_api_lineage.py @@ -0,0 +1,245 @@ +"""Repair databases that reached 050 through the archived api chain. + +Revision ID: 053_repair_api_lineage +Revises: 052_receipt_mode_build + +The archived agent-middleware-api chain shares revision ids 047-050 with this +chain but never ran this repo's 044-046, so a database stamped there arrives +at 050 without receipt_resolutions, resolution_chain_heads, +approval_gate_approvals, api_key_usage_events and the +api_key_usage_daily view. This revision creates each one only when it is +absent, with exactly the columns, indexes and constraints of 044-046. It +writes no rows. On a database built from this chain it changes nothing. + +PostgreSQL only: receipt_resolutions and resolution_chain_heads are +wallet-scoped, and on this chain 048_tenant_rls gives them the +amw_tenant_isolation policy. An api-chain database ran 048 before they +existed, so this revision creates that identical policy (same name and +predicate, frozen copy) on each table that lacks it. It enables and forces +RLS when TENANT_RLS_MODE is enforce or when api_keys already has forced RLS, +so the repaired tables match the posture the rest of the database already has. + +Downgrade is a deliberate no-op: once applied, nothing in the schema records +whether 053 or 044-046 created an object, so dropping any of them could +destroy tables a fresh chain owns. Rolling back 044-046 remains their job. +""" + +import sqlalchemy as sa +from alembic import op + +revision: str = "053_repair_api_lineage" +down_revision: str = "052_receipt_mode_build" +branch_labels = None +depends_on = None + +# Copied verbatim from 046_api_key_usage_events. +CREATE_API_KEY_USAGE_DAILY_VIEW_SQL = """ +CREATE VIEW api_key_usage_daily AS +WITH ranked AS ( + SELECT + key_id, + DATE(created_at) AS day, + status_code, + latency_ms, + created_at, + ROW_NUMBER() OVER ( + PARTITION BY key_id, DATE(created_at) + ORDER BY latency_ms, id + ) AS latency_rank, + COUNT(*) OVER ( + PARTITION BY key_id, DATE(created_at) + ) AS call_count + FROM api_key_usage_events +), positioned AS ( + SELECT + *, + ((call_count - 1) * 50) / 100 + 1 AS p50_floor_rank, + ((call_count - 1) * 50) % 100 AS p50_remainder, + ((call_count - 1) * 95) / 100 + 1 AS p95_floor_rank, + ((call_count - 1) * 95) % 100 AS p95_remainder + FROM ranked +) +SELECT + key_id, + day, + COUNT(*) AS calls, + SUM(CASE WHEN status_code BETWEEN 400 AND 499 THEN 1 ELSE 0 END) AS calls_4xx, + SUM(CASE WHEN status_code BETWEEN 500 AND 599 THEN 1 ELSE 0 END) AS calls_5xx, + SUM(CASE WHEN latency_rank = p50_floor_rank THEN latency_ms * (100 - p50_remainder) / 100.0 WHEN latency_rank = p50_floor_rank + 1 THEN latency_ms * p50_remainder / 100.0 ELSE 0 END) AS p50_latency_ms, + SUM(CASE WHEN latency_rank = p95_floor_rank THEN latency_ms * (100 - p95_remainder) / 100.0 WHEN latency_rank = p95_floor_rank + 1 THEN latency_ms * p95_remainder / 100.0 ELSE 0 END) AS p95_latency_ms, + MIN(created_at) AS first_call_at, + MAX(created_at) AS last_call_at +FROM positioned +GROUP BY key_id, day +""" + + +def _resolution_chain_heads() -> None: + op.create_table( + "resolution_chain_heads", + sa.Column("wallet_id", sa.String(length=50), primary_key=True), + sa.Column("last_sequence", sa.Integer(), nullable=False, server_default="0"), + sa.Column("last_hash", sa.String(length=64), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]), + sa.CheckConstraint( + "last_sequence >= 0", name="ck_resolution_chain_heads_sequence" + ), + ) + + +def _receipt_resolutions() -> None: + op.create_table( + "receipt_resolutions", + sa.Column("resolution_id", sa.String(length=64), primary_key=True), + sa.Column("receipt_id", sa.String(length=64), nullable=False), + sa.Column("wallet_id", sa.String(length=50), nullable=False), + sa.Column("sequence", sa.Integer(), nullable=False), + sa.Column("prev_hash", sa.String(length=64), nullable=True), + sa.Column("receipt_hash", sa.String(length=64), nullable=False), + sa.Column("outcome", sa.String(length=32), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("payload_hash", sa.String(length=64), nullable=False), + sa.Column("resolution_hash", sa.String(length=64), nullable=False), + sa.Column("signing_input", sa.Text(), nullable=False), + sa.Column("signature", sa.String(), nullable=False), + sa.Column("signature_key_id", sa.String(length=64), nullable=False), + sa.ForeignKeyConstraint(["receipt_id"], ["receipts.receipt_id"]), + sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]), + sa.ForeignKeyConstraint(["signature_key_id"], ["signing_keys.key_id"]), + sa.UniqueConstraint( + "wallet_id", "sequence", name="uq_receipt_resolutions_wallet_seq" + ), + sa.CheckConstraint("sequence >= 1", name="ck_receipt_resolutions_sequence"), + sa.CheckConstraint( + "outcome IN ('confirmed_success', 'confirmed_not_delivered')", + name="ck_receipt_resolutions_outcome", + ), + ) + for column in ( + "receipt_id", + "wallet_id", + "receipt_hash", + "resolution_hash", + "signature_key_id", + ): + op.create_index( + f"ix_receipt_resolutions_{column}", + "receipt_resolutions", + [column], + unique=column in {"receipt_id", "resolution_hash"}, + ) + + +def _approval_gate_approvals() -> None: + op.create_table( + "approval_gate_approvals", + sa.Column("nonce", sa.String(length=64), primary_key=True), + sa.Column("idempotency_key", sa.String(length=128), nullable=False), + sa.Column("args_hash", sa.String(length=128), nullable=False), + sa.Column("principal", sa.String(length=255), nullable=False), + sa.Column("tool", sa.String(length=128), nullable=False), + sa.Column("session_id", sa.String(length=128), nullable=False), + sa.Column("status", sa.String(length=16), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("deadline", sa.DateTime(), nullable=False), + sa.Column("decided_at", sa.DateTime(), nullable=True), + sa.Column("consumed_at", sa.DateTime(), nullable=True), + sa.CheckConstraint( + "status IN ('pending', 'approved', 'denied', 'expired')", + name="ck_approval_gate_approvals_status", + ), + ) + for column in ("idempotency_key", "status"): + op.create_index( + f"ix_approval_gate_approvals_{column}", + "approval_gate_approvals", + [column], + unique=False, + ) + + +def _api_key_usage_events() -> None: + op.create_table( + "api_key_usage_events", + sa.Column("id", sa.String(length=36), primary_key=True), + sa.Column("key_id", sa.String(length=50), nullable=False), + sa.Column("tenant", sa.String(length=32), nullable=True), + sa.Column("method", sa.String(length=16), nullable=False), + sa.Column("endpoint", sa.String(length=512), nullable=False), + sa.Column("status_code", sa.Integer(), nullable=False), + sa.Column("latency_ms", sa.Integer(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + ) + op.create_index( + "ix_api_key_usage_events_key_created", + "api_key_usage_events", + ["key_id", "created_at"], + ) + op.create_index( + "ix_api_key_usage_events_created", "api_key_usage_events", ["created_at"] + ) + + +# Creation order respects foreign keys; each runs only if its table is absent. +TABLES = ( + ("resolution_chain_heads", _resolution_chain_heads), + ("receipt_resolutions", _receipt_resolutions), + ("approval_gate_approvals", _approval_gate_approvals), + ("api_key_usage_events", _api_key_usage_events), +) + + +# Frozen copy of 048_tenant_rls's policy for its LATE_RLS_TABLES. +POLICY_NAME = "amw_tenant_isolation" +_CURRENT_WALLET = "NULLIF(current_setting('app.current_wallet_id', true), '')" +_BYPASS = "current_setting('app.rls_bypass', true) = 'on'" +RLS_TABLES = ("receipt_resolutions", "resolution_chain_heads") + + +def _apply_tenant_policy(bind) -> None: + from app.core.config import get_settings + + forced_already = bind.execute( + sa.text( + "SELECT relforcerowsecurity FROM pg_class " + "WHERE relname = 'api_keys' AND relkind = 'r' " + "AND relnamespace = current_schema()::regnamespace" + ) + ).scalar() + enforce = get_settings().TENANT_RLS_MODE == "enforce" or bool(forced_already) + predicate = f"(wallet_id = {_CURRENT_WALLET}) OR {_BYPASS}" + for table in RLS_TABLES: + has_policy = bind.execute( + sa.text( + "SELECT 1 FROM pg_policy WHERE polname = :name " + "AND polrelid = to_regclass(:table)" + ), + {"name": POLICY_NAME, "table": table}, + ).scalar() + if has_policy: + continue + 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"CREATE POLICY {POLICY_NAME} ON {table} AS PERMISSIVE FOR ALL " + f"USING ({predicate}) WITH CHECK ({predicate})" + ) + + +def upgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + tables = set(inspector.get_table_names()) + for name, create in TABLES: + if name not in tables: + create() + if "api_key_usage_daily" not in set(inspector.get_view_names()): + op.execute(CREATE_API_KEY_USAGE_DAILY_VIEW_SQL) + if bind.dialect.name == "postgresql": + _apply_tenant_policy(bind) + + +def downgrade() -> None: + """No-op by design; see the module docstring.""" diff --git a/gateway/tests/test_repair_api_lineage_migration.py b/gateway/tests/test_repair_api_lineage_migration.py new file mode 100644 index 000000000..edcd74b6f --- /dev/null +++ b/gateway/tests/test_repair_api_lineage_migration.py @@ -0,0 +1,95 @@ +"""053 restores 044-046 objects missing from databases built by the api chain.""" + +import asyncio + +from alembic import command +from alembic.config import Config +from alembic.script import ScriptDirectory +from sqlalchemy import create_engine, inspect, text + +TABLES = ( + "receipt_resolutions", + "resolution_chain_heads", + "approval_gate_approvals", + "api_key_usage_events", +) +VIEW = "api_key_usage_daily" + + +def _config(tmp_path, monkeypatch): + db_path = tmp_path / "repair.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 _shape(sync_url): + engine = create_engine(sync_url) + insp = inspect(engine) + shape = { + name: ( + [ + (c["name"], str(c["type"]), c["nullable"]) + for c in insp.get_columns(name) + ], + sorted( + (i["name"], tuple(i["column_names"]), bool(i["unique"])) + for i in insp.get_indexes(name) + ), + sorted(str(c["sqltext"]) for c in insp.get_check_constraints(name)), + sorted( + (tuple(f["constrained_columns"]), f["referred_table"]) + for f in insp.get_foreign_keys(name) + ), + ) + for name in TABLES + } + views = set(insp.get_view_names()) + engine.dispose() + return shape, views + + +def test_053_follows_052(): + script = ScriptDirectory.from_config(Config("alembic.ini")) + rev = script.get_revision("053_repair_api_lineage") + assert rev.down_revision == "052_receipt_mode_build" + assert len(script.get_heads()) == 1 + + +def test_fresh_chain_upgrade_is_noop_for_053(tmp_path, monkeypatch): + config, sync_url = _config(tmp_path, monkeypatch) + _run(command.upgrade, config, "052_receipt_mode_build") + before = _shape(sync_url) + _run(command.upgrade, config, "053_repair_api_lineage") + assert _shape(sync_url) == before + + +def test_missing_objects_are_recreated_with_main_shape(tmp_path, monkeypatch): + config, sync_url = _config(tmp_path, monkeypatch) + _run(command.upgrade, config, "052_receipt_mode_build") + expected = _shape(sync_url) + engine = create_engine(sync_url) + with engine.begin() as conn: + conn.execute(text(f"DROP VIEW {VIEW}")) + for name in ( + "receipt_resolutions", + "resolution_chain_heads", + "approval_gate_approvals", + "api_key_usage_events", + ): + conn.execute(text(f"DROP TABLE {name}")) + engine.dispose() + + _run(command.upgrade, config, "head") + shape, views = _shape(sync_url) + assert shape == expected[0] + assert VIEW in views + # A second upgrade is a no-op and downgrade leaves every object in place. + _run(command.upgrade, config, "head") + _run(command.downgrade, config, "052_receipt_mode_build") + shape, views = _shape(sync_url) + assert shape == expected[0] and VIEW in views