diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh index 4887a0847..79a8340ba 100644 --- a/.github/scripts/smoke_gateway_image.sh +++ b/.github/scripts/smoke_gateway_image.sh @@ -145,6 +145,17 @@ docker build --target build-metadata -f gateway/Dockerfile \ --build-arg "RELEASE_COMMIT_SHA=${stamp^^}" -t amw-gateway:ci-metadata . check_metadata_stamp amw-gateway:ci-metadata +# CI and Railway build args supply the commit without a stamp file. +docker build --target build-metadata -f gateway/Dockerfile \ + --build-arg "GIT_COMMIT_SHA=$stamp" -t amw-gateway:ci-metadata . +check_metadata_stamp amw-gateway:ci-metadata +docker build --target build-metadata -f gateway/Dockerfile \ + --build-arg "RAILWAY_GIT_COMMIT_SHA=$stamp" -t amw-gateway:ci-metadata . +check_metadata_stamp amw-gateway:ci-metadata +# A stale pinned override fails instead of stamping the wrong commit. +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$other" \ + --build-arg "RAILWAY_GIT_COMMIT_SHA=$stamp" + rm gateway/.build_commit_sha expect_metadata_failure # neither root stamp nor argument exists COMMIT_SHA="$stamp" BUILD_COMMIT_SHA="$stamp" expect_metadata_failure diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index da8809ff5..6bb1cdbc2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -463,6 +463,7 @@ jobs: "amw_action_dispatch", "amw_pg_stress", "amw_action_multiprocess", + "amw_rls_off_migration", ) @@ -516,9 +517,13 @@ jobs: env: ACTION_MIGRATION_DATABASE_URL: postgresql+asyncpg://sellers@127.0.0.1:55439/amw_action_migration DISPATCH_MIGRATION_DATABASE_URL: postgresql+asyncpg://sellers@127.0.0.1:55439/amw_action_dispatch + # Empty DB, never migrated by an earlier step: the 048 default-off + # proof refuses a reused database. + TENANT_RLS_OFF_MIGRATION_DATABASE_URL: postgresql+asyncpg://sellers@127.0.0.1:55439/amw_rls_off_migration run: | uv run --no-sync pytest -q -rs --timeout 300 \ "tests/test_action_migrations.py::test_postgres_legacy_roundtrip_and_fail_closed_downgrade" \ + "tests/test_047_048_negative_paths.py::test_postgres_default_off_creates_policies_but_leaves_rls_disabled" \ tests/test_dispatch_call_slot_migration.py 2>&1 | tee "$GITHUB_WORKSPACE/proof-logs-migration.txt" test "${PIPESTATUS[0]}" -eq 0 - name: Run asyncpg driver proofs diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fa9d371..64480f302 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,17 @@ 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. +- Ops: the startup `runtime_posture` log line and `GET /health` now report + `tenant_rls_mode` (`off` or `enforce`). The default stays `off`. +- Boot: the schema check now requires `receipts.enforcement_mode` and + `receipts.gateway_build` (migration 052), so a database missing them fails at + startup instead of on the first receipt write. +- CI: the Postgres proofs job sets `TENANT_RLS_OFF_MIGRATION_DATABASE_URL`, so the + 048 default-off migration proof runs instead of skipping. +- Build: the image commit stamp now resolves `RELEASE_COMMIT_SHA` (explicit + override), then `RAILWAY_GIT_COMMIT_SHA`, then a CI `GIT_COMMIT_SHA` build arg, + then the staged `.build_commit_sha`. Each set value must be a 7-40 hex SHA and + all set values must agree, so a stale pin fails the build instead of stamping it. - 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. diff --git a/gateway/Dockerfile b/gateway/Dockerfile index 5bf9c00c7..6e334f88d 100644 --- a/gateway/Dockerfile +++ b/gateway/Dockerfile @@ -5,7 +5,13 @@ FROM python:3.12-slim AS build-metadata # named COPY that fails on clean trees. .dockerignore excludes local secrets. WORKDIR /context COPY . /context/ +# Commit sources, highest precedence first: RELEASE_COMMIT_SHA (explicit +# override), RAILWAY_GIT_COMMIT_SHA (Railway passes it because it is declared +# here), GIT_COMMIT_SHA (CI build arg), then the staged root stamp. All set +# sources must agree. BUILD_COMMIT_SHA/COMMIT_SHA are not read (stale vars). ARG RELEASE_COMMIT_SHA +ARG RAILWAY_GIT_COMMIT_SHA +ARG GIT_COMMIT_SHA RUN mkdir /stamp \ && STAGED_SHA_PATH=/context/.build_commit_sha \ BUILD_SHA_PATH=/stamp/.build_commit_sha \ diff --git a/gateway/app/db/database.py b/gateway/app/db/database.py index 05396ded2..dd746b3fc 100644 --- a/gateway/app/db/database.py +++ b/gateway/app/db/database.py @@ -125,6 +125,8 @@ "action_schema_version", "action_public_tool_id", "action_upstream_binding_hash", + "enforcement_mode", + "gateway_build", } ), } diff --git a/gateway/app/main.py b/gateway/app/main.py index 75272c012..abd7d13b7 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -191,6 +191,7 @@ async def lifespan(app: FastAPI): enable_dogfood_second_tool=bool(settings.ENABLE_DOGFOOD_SECOND_TOOL), simulation_modes=get_simulation_modes(), cors_origins=settings.CORS_ORIGINS, + tenant_rls_mode=settings.TENANT_RLS_MODE, ) # A public deployment whose manifest tells agents the operator has no # contact is a discovery-honesty defect, not a neutral default. Partial @@ -1243,7 +1244,8 @@ async def root(request: Request): "Redis is configured but does not answer within 1 second; in " "production-like environments the rate limiter then refuses /v1 " "requests, so the API is not serving even though the process is up. " - "`checks.redis` is `up`, `down`, or `not_configured`." + "`checks.redis` is `up`, `down`, or `not_configured`. " + "`tenant_rls_mode` is `off` or `enforce`." ), ) async def health(): @@ -1260,6 +1262,9 @@ async def health(): # path. A bare SHA cannot be told apart from a stale stamp; a SHA # plus "stamped" can only mean the deployment is behind main. "build_provenance": get_build_provenance(), + # "off" or "enforce": whether migrations enable wallet RLS. A + # validated enum, never a credential. + "tenant_rls_mode": get_settings().TENANT_RLS_MODE, "checks": {"redis": redis_status}, }, ) diff --git a/gateway/docs/openapi.json b/gateway/docs/openapi.json index d0e6920d0..9ca42b0cc 100644 --- a/gateway/docs/openapi.json +++ b/gateway/docs/openapi.json @@ -5952,7 +5952,7 @@ "Discovery" ], "summary": "Liveness check", - "description": "Returns 200 with status `healthy` when the API is running and its Redis (shared rate limiter) answers a PING, or when REDIS_URL is not configured (no PING is sent). Returns 503 with status `degraded` when Redis is configured but does not answer within 1 second; in production-like environments the rate limiter then refuses /v1 requests, so the API is not serving even though the process is up. `checks.redis` is `up`, `down`, or `not_configured`.", + "description": "Returns 200 with status `healthy` when the API is running and its Redis (shared rate limiter) answers a PING, or when REDIS_URL is not configured (no PING is sent). Returns 503 with status `degraded` when Redis is configured but does not answer within 1 second; in production-like environments the rate limiter then refuses /v1 requests, so the API is not serving even though the process is up. `checks.redis` is `up`, `down`, or `not_configured`. `tenant_rls_mode` is `off` or `enforce`.", "operationId": "health_health_get", "responses": { "200": { diff --git a/gateway/scripts/write_build_commit_sha.py b/gateway/scripts/write_build_commit_sha.py index 8e567e811..1dfda9b32 100644 --- a/gateway/scripts/write_build_commit_sha.py +++ b/gateway/scripts/write_build_commit_sha.py @@ -4,15 +4,21 @@ clean tree before the build starts, and no workflow in this repo creates the file. The production Dockerfile runs this script instead. -Sources: - -1. A stamp at the repository build-context root (release archive). It is authoritative. -2. The ``RELEASE_COMMIT_SHA`` build arg, for ``docker build`` on a clean tree. - -The build fails when neither source is a 7–64 character hex SHA, when the -staged file is present but invalid, or when both sources are valid and -disagree. The arg is not named COMMIT_SHA or ``BUILD_COMMIT_SHA`` so a -stale Railway service variable is not picked up as the stamp. +Sources, in precedence order: + +1. ``RELEASE_COMMIT_SHA`` build arg: explicit operator override (kept so a + pinned staging service variable keeps working). +2. ``RAILWAY_GIT_COMMIT_SHA`` build arg: Railway's own deployment metadata, + passed in because the Dockerfile declares it as an ARG. +3. ``GIT_COMMIT_SHA`` build arg: passed by CI (``git rev-parse HEAD``). +4. A stamp at the repository build-context root (release archive). + +Every source that is set must be a 7-40 character hex SHA, and every set +source must agree (case-insensitively); otherwise the build fails. A stale +pinned value therefore cannot win over the real commit: it fails the build. +The build also fails when no source is set. ``BUILD_COMMIT_SHA`` and plain +COMMIT_SHA are deliberately not read, because they are commonly stale +Railway service variables. ``STAGED_SHA_PATH`` and ``BUILD_SHA_PATH`` select the input and output paths for the image metadata stage and tests. The two paths must be distinct in the @@ -26,13 +32,14 @@ import sys from pathlib import Path -# Same shape as app.core.build_metadata._GIT_SHA_RE. Kept local so image +# Git object names (SHA-1, abbreviated to at least 7). Kept local so the image # build does not import application settings. -_GIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,64}$") +_GIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$") _DEFAULT_PATH = Path("/app/.build_commit_sha") _MISSING = ( "Release commit stamp missing. Stage .build_commit_sha in the build " - "context or pass --build-arg RELEASE_COMMIT_SHA=$(git rev-parse HEAD)." + "context or pass --build-arg GIT_COMMIT_SHA=$(git rev-parse HEAD) " + "(Railway supplies RAILWAY_GIT_COMMIT_SHA for Git-triggered deploys)." ) @@ -40,29 +47,46 @@ def _valid(value: str) -> bool: return _GIT_SHA_RE.fullmatch(value) is not None -def resolve_stamp(staged: str | None, build_arg: str) -> str: +def resolve_stamp( + staged: str | None, + build_arg: str = "", + railway_sha: str = "", + ci_sha: str = "", +) -> str: """Return the lowercase SHA to write. ``staged`` is the file contents, or ``None`` when the file is absent. + ``build_arg`` is ``RELEASE_COMMIT_SHA``, ``railway_sha`` is + ``RAILWAY_GIT_COMMIT_SHA`` and ``ci_sha`` is ``GIT_COMMIT_SHA``. """ - arg = build_arg.strip() - if arg and not _valid(arg): - raise SystemExit("RELEASE_COMMIT_SHA is not a 7-64 character hex git SHA.") - - if staged is None: - if not _valid(arg): - raise SystemExit(_MISSING) - return arg.lower() - - staged_sha = staged.strip() - if not _valid(staged_sha): - raise SystemExit( - "Staged .build_commit_sha is not a 7-64 character hex git SHA." - ) - if arg and arg.lower() != staged_sha.lower(): - raise SystemExit("RELEASE_COMMIT_SHA disagrees with staged .build_commit_sha.") - return staged_sha.lower() + sources: list[tuple[str, str]] = [] + for name, raw in ( + ("RELEASE_COMMIT_SHA", build_arg), + ("RAILWAY_GIT_COMMIT_SHA", railway_sha), + ("GIT_COMMIT_SHA", ci_sha), + ): + value = (raw or "").strip() + if not value: + continue + if not _valid(value): + raise SystemExit(f"{name} is not a 7-40 character hex git SHA.") + sources.append((name, value.lower())) + if staged is not None: + staged_sha = staged.strip() + if not _valid(staged_sha): + raise SystemExit( + "Staged .build_commit_sha is not a 7-40 character hex git SHA." + ) + sources.append(("staged .build_commit_sha", staged_sha.lower())) + + if not sources: + raise SystemExit(_MISSING) + winner_name, winner = sources[0] + for name, value in sources[1:]: + if value != winner: + raise SystemExit(f"{winner_name} disagrees with {name}.") + return winner def main() -> int: @@ -76,7 +100,12 @@ def main() -> int: except OSError as exc: raise SystemExit(f"Cannot read {staged_path}: {exc}") from exc - sha = resolve_stamp(staged, os.environ.get("RELEASE_COMMIT_SHA", "")) + sha = resolve_stamp( + staged, + os.environ.get("RELEASE_COMMIT_SHA", ""), + os.environ.get("RAILWAY_GIT_COMMIT_SHA", ""), + os.environ.get("GIT_COMMIT_SHA", ""), + ) path.write_text(sha + "\n", encoding="utf-8") return 0 diff --git a/gateway/tests/test_tenant_rls_reporting.py b/gateway/tests/test_tenant_rls_reporting.py new file mode 100644 index 000000000..1925ec8f0 --- /dev/null +++ b/gateway/tests/test_tenant_rls_reporting.py @@ -0,0 +1,78 @@ +"""TENANT_RLS_MODE reporting (startup log, /health) and 052 boot columns.""" + +from __future__ import annotations + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy.ext.asyncio import create_async_engine + + +class _PostureLogged(Exception): + pass + + +@pytest.mark.parametrize("mode", ["off", "enforce"]) +async def test_startup_posture_line_reports_tenant_rls_mode( + clean_database, monkeypatch, mode +): + import app.main as main_module + + monkeypatch.setattr(main_module.settings, "TENANT_RLS_MODE", mode) + recorded: list[dict] = [] + + def info(event, **fields): + recorded.append({"event": event, **fields}) + if event == "app_startup" and fields.get("phase") == "runtime_posture": + raise _PostureLogged + + monkeypatch.setattr(main_module.logger, "info", info) + with pytest.raises(_PostureLogged): + async with main_module.lifespan(main_module.app): + pytest.fail("lifespan should stop at the posture line in this test") + posture = [r for r in recorded if r.get("phase") == "runtime_posture"] + assert len(posture) == 1 + assert posture[0]["tenant_rls_mode"] == mode + + +@pytest.mark.parametrize("mode", ["off", "enforce"]) +async def test_health_reports_tenant_rls_mode(clean_database, monkeypatch, mode): + from app.core.config import get_settings + from app.main import app + + monkeypatch.setattr(get_settings(), "TENANT_RLS_MODE", mode) + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as client: + response = await client.get("/health") + assert response.status_code == 200 + assert response.json()["tenant_rls_mode"] == mode + + +def test_tenant_rls_mode_default_stays_off(): + from app.core.config import Settings + + assert Settings().TENANT_RLS_MODE == "off" + + +def test_receipt_mode_build_columns_are_required_at_boot(): + from app.db.database import REQUIRED_TRUST_COLUMNS + + assert {"enforcement_mode", "gateway_build"} <= REQUIRED_TRUST_COLUMNS["receipts"] + + +async def test_boot_check_names_missing_receipt_mode_build_columns(): + from app.db.database import _missing_required_columns + + engine = create_async_engine("sqlite+aiosqlite:///:memory:") + try: + async with engine.begin() as conn: + await conn.exec_driver_sql( + "CREATE TABLE receipts (id TEXT PRIMARY KEY, " + "action_contract_version TEXT, action_payload_hash TEXT, " + "action_schema_id TEXT, action_schema_version TEXT, " + "action_public_tool_id TEXT, action_upstream_binding_hash TEXT)" + ) + missing = await conn.run_sync(_missing_required_columns) + finally: + await engine.dispose() + assert {"receipts.enforcement_mode", "receipts.gateway_build"} <= missing diff --git a/gateway/tests/test_write_build_commit_sha.py b/gateway/tests/test_write_build_commit_sha.py index 2219885ab..29d81064c 100644 --- a/gateway/tests/test_write_build_commit_sha.py +++ b/gateway/tests/test_write_build_commit_sha.py @@ -20,6 +20,7 @@ def _run( staged: str | None, build_arg: str | None, nested: str | None = None, + extra_env: dict[str, str] | None = None, ): context = tmp_path / "context" context.mkdir() @@ -33,6 +34,9 @@ def _run( env = os.environ.copy() env["STAGED_SHA_PATH"] = str(stamp) env["BUILD_SHA_PATH"] = str(output) + env.pop("RAILWAY_GIT_COMMIT_SHA", None) + env.pop("GIT_COMMIT_SHA", None) + env.update(extra_env or {}) if build_arg is None: env.pop("RELEASE_COMMIT_SHA", None) else: @@ -130,3 +134,76 @@ def test_short_sha_rejected(): def test_seven_char_sha_accepted(): assert resolve_stamp(None, "abc1234") == "abc1234" + + +# Resolution order: RELEASE_COMMIT_SHA > RAILWAY_GIT_COMMIT_SHA > +# GIT_COMMIT_SHA > staged file. Every set source must agree. + + +def test_railway_sha_alone_is_used(): + assert resolve_stamp(None, "", SHA.upper(), "") == SHA + + +def test_ci_sha_alone_is_used(): + assert resolve_stamp(None, "", "", SHA) == SHA + + +def test_staged_file_is_last_resort(): + assert resolve_stamp(SHA + "\n") == SHA + + +@pytest.mark.parametrize( + ("release", "railway", "ci", "staged", "loser"), + [ + (OTHER, SHA, "", None, "RAILWAY_GIT_COMMIT_SHA"), + ("", OTHER, SHA, None, "GIT_COMMIT_SHA"), + ("", "", OTHER, SHA + "\n", "staged .build_commit_sha"), + (OTHER, "", "", SHA + "\n", "staged .build_commit_sha"), + ], +) +def test_any_disagreement_fails_instead_of_using_stale_value( + release, railway, ci, staged, loser +): + with pytest.raises(SystemExit, match=f"disagrees with {loser}"): + resolve_stamp(staged, release, railway, ci) + + +def test_all_sources_agreeing_returns_highest_precedence_lowercase(): + assert resolve_stamp(SHA + "\n", SHA.upper(), SHA, SHA[:]) == SHA + + +@pytest.mark.parametrize( + ("kwargs", "name"), + [ + ({"railway_sha": "xyz1234"}, "RAILWAY_GIT_COMMIT_SHA"), + ({"ci_sha": "abc12"}, "GIT_COMMIT_SHA"), + ({"ci_sha": "a" * 41}, "GIT_COMMIT_SHA"), + ], +) +def test_invalid_source_fails_by_name(kwargs, name): + with pytest.raises(SystemExit, match=name): + resolve_stamp(None, **kwargs) + + +def test_forty_char_upper_bound(): + assert resolve_stamp(None, ci_sha="a" * 40) == "a" * 40 + + +def test_script_reads_railway_and_ci_build_args(tmp_path): + result, output = _run( + tmp_path, + None, + None, + extra_env={"RAILWAY_GIT_COMMIT_SHA": SHA, "GIT_COMMIT_SHA": SHA.upper()}, + ) + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_script_fails_when_pinned_override_is_stale(tmp_path): + result, output = _run( + tmp_path, None, OTHER, extra_env={"RAILWAY_GIT_COMMIT_SHA": SHA} + ) + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA disagrees with RAILWAY_GIT_COMMIT_SHA" in result.stderr + assert not output.exists()