Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/scripts/smoke_gateway_image.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,7 @@ jobs:
"amw_action_dispatch",
"amw_pg_stress",
"amw_action_multiprocess",
"amw_rls_off_migration",
)


Expand Down Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions gateway/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
2 changes: 2 additions & 0 deletions gateway/app/db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@
"action_schema_version",
"action_public_tool_id",
"action_upstream_binding_hash",
"enforcement_mode",
"gateway_build",
}
),
}
Expand Down
7 changes: 6 additions & 1 deletion gateway/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand All @@ -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},
},
)
Expand Down
2 changes: 1 addition & 1 deletion gateway/docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
91 changes: 60 additions & 31 deletions gateway/scripts/write_build_commit_sha.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -26,43 +32,61 @@
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)."
)


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:
Expand All @@ -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

Expand Down
78 changes: 78 additions & 0 deletions gateway/tests/test_tenant_rls_reporting.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading