From a7187076cb0fe1e0f85cfd7243be1d118f6e664c Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:14:24 -0700 Subject: [PATCH 01/14] SEL-286: Gateway images omit `b2a_sdk`, so app import crashes Linear: SEL-286 Refs https://github.com/agentmiddleware/agent-middleware/issues/106 Engine: grok (fleet coding engine, Grok Bot dispatch) --- .dockerignore | 36 +++++++ gateway/Dockerfile | 17 ++- gateway/Dockerfile.dev | 14 ++- gateway/app/routers/mcp_public.py | 73 ++++++++----- gateway/docker-compose.yml | 6 +- gateway/tests/test_gateway_image_sdk.py | 132 ++++++++++++++++++++++++ 6 files changed, 239 insertions(+), 39 deletions(-) create mode 100644 .dockerignore create mode 100644 gateway/tests/test_gateway_image_sdk.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..225674f13 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,36 @@ +# Image builds use the repository root as the context. See gateway/Dockerfile. +.git +.github +.agents +.claude +.envrc +.vercel +.railway +.venv +**/.venv +.pytest_cache +**/.pytest_cache +.ruff_cache +**/.ruff_cache +__pycache__ +**/__pycache__ +*.py[cod] +**/*.py[cod] +*.pyo +**/*.pyo +*.pyd +**/*.pyd +.env +**/.env +.env.* +**/.env.* +*.db +**/*.db +gateway/tests +gateway/docker-compose.yml +gateway/docker-compose.prod.yml +sdk/typescript +integrations +examples +spec +verifier diff --git a/gateway/Dockerfile b/gateway/Dockerfile index 86df7407e..5a1b9e4dd 100644 --- a/gateway/Dockerfile +++ b/gateway/Dockerfile @@ -2,20 +2,27 @@ FROM python:3.12-slim WORKDIR /app +# b2a_sdk is imported while app.main loads. The build context is the +# repository root (not this directory): sdk/python is not inside gateway/. +# docker build -f gateway/Dockerfile . +# The release stamp .build_commit_sha must sit at that context root. ENV PYTHONUNBUFFERED=1 \ - PYTHONDONTWRITEBYTECODE=1 + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=/sdk/python/src # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ && rm -rf /var/lib/apt/lists/* -# Install Python dependencies -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +# Install Python dependencies, then the in-repo SDK those imports require. +COPY sdk/python /sdk/python +COPY gateway/requirements.txt /tmp/requirements.txt +RUN pip install --no-cache-dir -r /tmp/requirements.txt \ + && pip install --no-cache-dir /sdk/python # Copy application code -COPY . . +COPY gateway/ /app/ # Release contexts must carry a commit stamp generated from the exact Git tree. COPY .build_commit_sha /app/.build_commit_sha diff --git a/gateway/Dockerfile.dev b/gateway/Dockerfile.dev index 159dc475e..cab334703 100644 --- a/gateway/Dockerfile.dev +++ b/gateway/Dockerfile.dev @@ -2,17 +2,23 @@ FROM python:3.12-slim WORKDIR /app +# b2a_sdk is imported while app.main loads. The build context is the +# repository root (not this directory). See docker-compose.yml. +# docker build -f gateway/Dockerfile.dev . ENV PYTHONUNBUFFERED=1 \ - PYTHONDONTWRITEBYTECODE=1 + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=/sdk/python/src RUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ && rm -rf /var/lib/apt/lists/* -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY sdk/python /sdk/python +COPY gateway/requirements.txt /tmp/requirements.txt +RUN pip install --no-cache-dir -r /tmp/requirements.txt \ + && pip install --no-cache-dir /sdk/python -COPY . . +COPY gateway/ /app/ RUN chmod +x scripts/docker_entrypoint.sh \ && groupadd --system app \ diff --git a/gateway/app/routers/mcp_public.py b/gateway/app/routers/mcp_public.py index a31410844..2d8c05423 100644 --- a/gateway/app/routers/mcp_public.py +++ b/gateway/app/routers/mcp_public.py @@ -60,38 +60,55 @@ ) +# Image layout: both Dockerfiles copy the in-repo SDK to /sdk/python, install +# it, and set PYTHONPATH=/sdk/python/src. From /app/app/routers/mcp_public.py, +# parents[3] is /, so the checkout-relative path is this same file. +_IMAGE_SDK_RECEIPT_VERIFIER = Path("/sdk/python/src/b2a_sdk/receipt_verifier.py") +_CHECKOUT_SDK_RECEIPT_VERIFIER = ( + Path(__file__).resolve().parents[3] + / "sdk" + / "python" + / "src" + / "b2a_sdk" + / "receipt_verifier.py" +) + + +def _receipt_verifier_file_candidates() -> tuple[Path, ...]: + """Checkout path first. In the image that path is ``/sdk/python/...``.""" + if _CHECKOUT_SDK_RECEIPT_VERIFIER == _IMAGE_SDK_RECEIPT_VERIFIER: + return (_IMAGE_SDK_RECEIPT_VERIFIER,) + return (_CHECKOUT_SDK_RECEIPT_VERIFIER, _IMAGE_SDK_RECEIPT_VERIFIER) + + +def _load_receipt_verifier_file(module_path: Path): + spec = importlib.util.spec_from_file_location( + "_agent_middleware_receipt_verifier", + module_path, + ) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load receipt verifier from {module_path}") + receipt_verifier = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = receipt_verifier + spec.loader.exec_module(receipt_verifier) + return receipt_verifier + + def _import_receipt_verifier(): - """Import the first-party offline verifier, in-repo when not installed. + """Import the first-party offline verifier. - ``b2a_sdk`` is packaged for external verifiers and is not a declared app - dependency; tests see it via pytest's ``pythonpath`` and deployed images - carry the source tree at the repo root. Falling back to that tree keeps - the public tool running the *same* verifier code an outside party runs, - instead of a drift-prone reimplementation. + Images declare the dependency by installing ``/sdk/python`` and putting + ``/sdk/python/src`` on ``PYTHONPATH``. A checkout that has not installed + the package still loads that same file from the repository root. The + fallback is not a second implementation. """ try: - receipt_verifier = importlib.import_module("b2a_sdk.receipt_verifier") - except ImportError: - module_path = ( - Path(__file__).resolve().parents[3] - / "sdk" - / "python" - / "src" - / "b2a_sdk" - / "receipt_verifier.py" - ) - if not module_path.is_file(): - raise - spec = importlib.util.spec_from_file_location( - "_agent_middleware_receipt_verifier", - module_path, - ) - if spec is None or spec.loader is None: - raise ImportError(f"cannot load receipt verifier from {module_path}") - receipt_verifier = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = receipt_verifier - spec.loader.exec_module(receipt_verifier) - return receipt_verifier + return importlib.import_module("b2a_sdk.receipt_verifier") + except ImportError as import_error: + for module_path in _receipt_verifier_file_candidates(): + if module_path.is_file(): + return _load_receipt_verifier_file(module_path) + raise import_error _receipt_verifier = _import_receipt_verifier() diff --git a/gateway/docker-compose.yml b/gateway/docker-compose.yml index 437243f25..6fb7dc4cc 100644 --- a/gateway/docker-compose.yml +++ b/gateway/docker-compose.yml @@ -3,8 +3,10 @@ services: api: build: - context: . - dockerfile: Dockerfile.dev + # Repository root, so the image can COPY sdk/python. Paths inside the + # Dockerfile are relative to that root; this file stays in gateway/. + context: .. + dockerfile: gateway/Dockerfile.dev ports: - "8000:8000" env_file: diff --git a/gateway/tests/test_gateway_image_sdk.py b/gateway/tests/test_gateway_image_sdk.py new file mode 100644 index 000000000..1f6ef6ab1 --- /dev/null +++ b/gateway/tests/test_gateway_image_sdk.py @@ -0,0 +1,132 @@ +"""Gateway images must ship the in-repo SDK that app import loads. + +``app.main`` imports ``mcp_public``, which imports ``b2a_sdk.receipt_verifier`` +at import time. The SDK is not inside ``gateway/``. A build whose context is +only that directory installs requirements.txt, then fails when uvicorn loads +``app.main:app``. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +from app.routers import mcp_public + +GATEWAY = Path(__file__).resolve().parents[1] +REPO = GATEWAY.parent +_FILE_LOADER = "_agent_middleware_receipt_verifier" + + +def _dockerfile(name: str) -> str: + return (GATEWAY / name).read_text(encoding="utf-8") + + +def test_checkout_still_has_the_verifier_the_fallback_loads(): + assert mcp_public._CHECKOUT_SDK_RECEIPT_VERIFIER.is_file() + assert mcp_public._IMAGE_SDK_RECEIPT_VERIFIER == Path( + "/sdk/python/src/b2a_sdk/receipt_verifier.py" + ) + # Inside the image the module is /app/app/routers/mcp_public.py, so + # parents[3] is /. That is the same file the Dockerfiles copy into place. + container_module = Path("/app/app/routers/mcp_public.py") + derived = ( + container_module.parents[3] + / "sdk" + / "python" + / "src" + / "b2a_sdk" + / "receipt_verifier.py" + ) + assert derived == mcp_public._IMAGE_SDK_RECEIPT_VERIFIER + # On a host checkout the two paths differ, and the repository file wins + # over a stray /sdk tree. In the image they are the same path. + assert mcp_public._receipt_verifier_file_candidates() == ( + mcp_public._CHECKOUT_SDK_RECEIPT_VERIFIER, + mcp_public._IMAGE_SDK_RECEIPT_VERIFIER, + ) + + +def test_image_build_context_contains_the_sdk(): + compose = (GATEWAY / "docker-compose.yml").read_text(encoding="utf-8") + assert "context: .." in compose + assert "dockerfile: gateway/Dockerfile.dev" in compose + context = (GATEWAY / "..").resolve() + assert context == REPO + assert (context / "sdk/python/pyproject.toml").is_file() + assert (context / "sdk/python/src/b2a_sdk/receipt_verifier.py").is_file() + assert (context / "gateway/requirements.txt").is_file() + + +@pytest.mark.parametrize("name", ["Dockerfile", "Dockerfile.dev"]) +def test_images_install_sdk_and_put_it_on_pythonpath(name: str): + text = _dockerfile(name) + sdk_copy = text.index("COPY sdk/python /sdk/python") + requirements = text.index("COPY gateway/requirements.txt /tmp/requirements.txt") + install = text.index("pip install --no-cache-dir /sdk/python") + user = text.index("\nUSER app\n") + assert "PYTHONPATH=/sdk/python/src" in text + assert "COPY gateway/ /app/" in text + assert sdk_copy < install < user + assert requirements < install + + +def test_release_dockerfile_still_requires_the_context_root_stamp(): + text = _dockerfile("Dockerfile") + assert "COPY .build_commit_sha /app/.build_commit_sha" in text + assert "COPY .build_commit_sha" not in _dockerfile("Dockerfile.dev") + + +def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): + lines = [ + line.strip() + for line in (REPO / ".dockerignore").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + assert "sdk" not in lines + assert "sdk/python" not in lines + assert "sdk/python/src" not in lines + assert ".build_commit_sha" not in lines + assert "gateway/tests" in lines + assert ".env" in lines + + +def _package_not_installed(_name: str): + raise ImportError("b2a_sdk is not installed") + + +def test_fallback_uses_the_image_file_when_the_package_is_not_installed( + monkeypatch, tmp_path +): + image_copy = tmp_path / "receipt_verifier.py" + image_copy.write_text( + mcp_public._CHECKOUT_SDK_RECEIPT_VERIFIER.read_text(encoding="utf-8") + + "\nMARKER = 'image-layout'\n", + encoding="utf-8", + ) + monkeypatch.setattr(mcp_public.importlib, "import_module", _package_not_installed) + monkeypatch.setattr( + mcp_public, + "_receipt_verifier_file_candidates", + lambda: (image_copy, Path("/no/such/checkout/receipt_verifier.py")), + ) + sys.modules.pop(_FILE_LOADER, None) + + loaded = mcp_public._import_receipt_verifier() + + assert loaded.MARKER == "image-layout" + assert hasattr(loaded, "verify_bundle") + + +def test_fallback_reraises_the_original_import_error_when_no_file_exists(monkeypatch): + monkeypatch.setattr(mcp_public.importlib, "import_module", _package_not_installed) + monkeypatch.setattr( + mcp_public, + "_receipt_verifier_file_candidates", + lambda: (Path("/no/such/image/receipt_verifier.py"),), + ) + + with pytest.raises(ImportError, match="b2a_sdk is not installed"): + mcp_public._import_receipt_verifier() From 512fa3fc1ee66c0c9916eb16e7da60f8e57382a0 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:12:23 -0700 Subject: [PATCH 02/14] SEL-285: Production image build copies a gitignored file that is not in the tree Linear: SEL-285 Refs https://github.com/agentmiddleware/agent-middleware/issues/107 Engine: cursor (fleet coding engine, Grok Bot dispatch) --- gateway/Dockerfile | 9 +- gateway/app/core/build_metadata.py | 4 +- gateway/scripts/write_build_commit_sha.py | 86 ++++++++++++++++ gateway/tests/test_build_provenance.py | 2 +- .../tests/test_stale_commit_sha_prevention.py | 16 ++- gateway/tests/test_write_build_commit_sha.py | 97 +++++++++++++++++++ 6 files changed, 205 insertions(+), 9 deletions(-) create mode 100644 gateway/scripts/write_build_commit_sha.py create mode 100644 gateway/tests/test_write_build_commit_sha.py diff --git a/gateway/Dockerfile b/gateway/Dockerfile index 86df7407e..db55bf89c 100644 --- a/gateway/Dockerfile +++ b/gateway/Dockerfile @@ -14,11 +14,14 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -# Copy application code +# Copy application code. A release archive may already include +# .build_commit_sha; that file is gitignored and is not in a clean checkout. COPY . . -# Release contexts must carry a commit stamp generated from the exact Git tree. -COPY .build_commit_sha /app/.build_commit_sha +# Bake /app/.build_commit_sha from the staged file or RELEASE_COMMIT_SHA. +# A named COPY of the gitignored stamp fails before the build starts. +ARG RELEASE_COMMIT_SHA +RUN python scripts/write_build_commit_sha.py RUN chmod +x scripts/docker_entrypoint.sh \ && groupadd --system app \ diff --git a/gateway/app/core/build_metadata.py b/gateway/app/core/build_metadata.py index d3259246b..75200b2e8 100644 --- a/gateway/app/core/build_metadata.py +++ b/gateway/app/core/build_metadata.py @@ -57,7 +57,9 @@ def get_build_provenance() -> str: The documented Railway release path builds a temporary context from ``git archive`` at the exact release SHA and adds a stamp file before - upload. The Dockerfile requires that file at build time. Railway sets + upload. The production image build writes that same path from the staged + file or, when the file is absent, from the ``RELEASE_COMMIT_SHA`` build + arg. A missing, invalid, or disagreeing stamp fails the build. Railway sets ``RAILWAY_GIT_COMMIT_SHA`` only for GitHub-triggered deployments, so a local ``railway up`` release relies on the baked stamp. A disagreement — or a missing stamp — is the signature of a build that did not come through diff --git a/gateway/scripts/write_build_commit_sha.py b/gateway/scripts/write_build_commit_sha.py new file mode 100644 index 000000000..3496ec81e --- /dev/null +++ b/gateway/scripts/write_build_commit_sha.py @@ -0,0 +1,86 @@ +"""Bake /app/.build_commit_sha during the production image build. + +``.build_commit_sha`` is gitignored. A named ``COPY`` of that path fails on a +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 already copied into the image (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. + +``BUILD_SHA_PATH`` overrides the output path (tests only). +""" + +from __future__ import annotations + +import os +import re +import sys +from pathlib import Path + +# Same shape as app.core.build_metadata._GIT_SHA_RE. Kept local so image +# build does not import application settings. +_GIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,64}$") +_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)." +) + + +def _valid(value: str) -> bool: + return _GIT_SHA_RE.fullmatch(value) is not None + + +def resolve_stamp(staged: str | None, build_arg: str) -> str: + """Return the lowercase SHA to write. + + ``staged`` is the file contents, or ``None`` when the file is absent. + """ + + 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() + + +def main() -> int: + path = Path(os.environ.get("BUILD_SHA_PATH", str(_DEFAULT_PATH))) + staged: str | None + try: + staged = path.read_text(encoding="utf-8") + except FileNotFoundError: + staged = None + except OSError as exc: + raise SystemExit(f"Cannot read {path}: {exc}") from exc + + sha = resolve_stamp(staged, os.environ.get("RELEASE_COMMIT_SHA", "")) + path.write_text(sha + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/gateway/tests/test_build_provenance.py b/gateway/tests/test_build_provenance.py index deb8beb34..679c40517 100644 --- a/gateway/tests/test_build_provenance.py +++ b/gateway/tests/test_build_provenance.py @@ -50,7 +50,7 @@ def test_stamped_is_case_insensitive(baked, monkeypatch): def test_stamped_tolerates_trailing_newline(baked, monkeypatch): - # The Dockerfile writes the stamp with `echo`, so it carries a newline. + # The image stamp is written with a trailing newline. baked(SHA_A + "\n") monkeypatch.setenv("RAILWAY_GIT_COMMIT_SHA", SHA_A) assert get_build_provenance() == "stamped" diff --git a/gateway/tests/test_stale_commit_sha_prevention.py b/gateway/tests/test_stale_commit_sha_prevention.py index e50f61e0b..6f30fbe97 100644 --- a/gateway/tests/test_stale_commit_sha_prevention.py +++ b/gateway/tests/test_stale_commit_sha_prevention.py @@ -253,11 +253,19 @@ async def test_deployment_without_baked_stamp_reports_null_not_stale( get_settings.cache_clear() -def test_dockerfile_requires_staged_build_commit_sha_file(): - """Dockerfile must reject a release upload that lacks the staged stamp.""" - # Use relative path from test file location to repo root +def test_dockerfile_bakes_commit_stamp_without_copying_gitignored_file(): + """Production image build must not COPY a gitignored stamp that is absent. + + A named COPY fails on a clean tree before the build starts. The image + still refuses to finish without a staged file or RELEASE_COMMIT_SHA. + The arg must not be COMMIT_SHA or BUILD_COMMIT_SHA: those names match + untrusted Railway service variables. + """ repo_root = Path(__file__).parent.parent dockerfile = (repo_root / "Dockerfile").read_text(encoding="utf-8") - assert "COPY .build_commit_sha /app/.build_commit_sha" in dockerfile + assert "COPY .build_commit_sha" not in dockerfile + assert "ARG RELEASE_COMMIT_SHA" in dockerfile + assert "python scripts/write_build_commit_sha.py" in dockerfile assert "ARG COMMIT_SHA" not in dockerfile + assert "ARG BUILD_COMMIT_SHA" not in dockerfile diff --git a/gateway/tests/test_write_build_commit_sha.py b/gateway/tests/test_write_build_commit_sha.py new file mode 100644 index 000000000..3b4e0ab8d --- /dev/null +++ b/gateway/tests/test_write_build_commit_sha.py @@ -0,0 +1,97 @@ +"""Production image stamp: staged file or RELEASE_COMMIT_SHA, never a missing COPY.""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from scripts.write_build_commit_sha import resolve_stamp + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "write_build_commit_sha.py" +SHA = "abcdef0123456789abcdef0123456789abcdef01" +OTHER = "1234567890abcdef1234567890abcdef12345678" + + +def _run(tmp_path: Path, staged: str | None, build_arg: str | None): + stamp = tmp_path / ".build_commit_sha" + if staged is not None: + stamp.write_text(staged, encoding="utf-8") + env = os.environ.copy() + env["BUILD_SHA_PATH"] = str(stamp) + if build_arg is None: + env.pop("RELEASE_COMMIT_SHA", None) + else: + env["RELEASE_COMMIT_SHA"] = build_arg + return subprocess.run( + [sys.executable, str(SCRIPT)], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + + +def test_build_arg_writes_lowercase_stamp_with_newline(tmp_path): + result = _run(tmp_path, None, SHA.upper()) + assert result.returncode == 0, result.stderr + assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + + +def test_missing_stamp_and_empty_arg_fails(tmp_path): + result = _run(tmp_path, None, "") + assert result.returncode != 0 + assert "Release commit stamp missing" in result.stderr + assert not (tmp_path / ".build_commit_sha").exists() + + +def test_invalid_build_arg_fails(tmp_path): + result = _run(tmp_path, None, "not-a-sha") + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA" in result.stderr + assert not (tmp_path / ".build_commit_sha").exists() + + +def test_staged_file_is_authoritative(tmp_path): + result = _run(tmp_path, SHA + "\n", "") + assert result.returncode == 0, result.stderr + assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + + +def test_staged_and_arg_may_differ_only_by_case(tmp_path): + result = _run(tmp_path, SHA.upper() + "\n", SHA) + assert result.returncode == 0, result.stderr + assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + + +def test_disagreement_fails_and_leaves_staged_file(tmp_path): + result = _run(tmp_path, SHA + "\n", OTHER) + assert result.returncode != 0 + assert "disagrees" in result.stderr + assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + + +def test_invalid_staged_file_is_not_replaced_by_build_arg(tmp_path): + result = _run(tmp_path, "not-a-sha\n", SHA) + assert result.returncode != 0 + assert "Staged .build_commit_sha" in result.stderr + assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == "not-a-sha\n" + + +def test_invalid_arg_does_not_override_valid_staged_file(tmp_path): + result = _run(tmp_path, SHA + "\n", "not-a-sha") + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA" in result.stderr + assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + + +def test_short_sha_rejected(): + with pytest.raises(SystemExit): + resolve_stamp(None, "abc123") + + +def test_seven_char_sha_accepted(): + assert resolve_stamp(None, "abc1234") == "abc1234" From 904dde36948b3f98ebc891e7d9dc712b220ed0d0 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:47:47 -0700 Subject: [PATCH 03/14] Validate root release stamp separately from image output --- gateway/scripts/write_build_commit_sha.py | 21 +++--- gateway/tests/test_write_build_commit_sha.py | 75 ++++++++++++++------ 2 files changed, 65 insertions(+), 31 deletions(-) diff --git a/gateway/scripts/write_build_commit_sha.py b/gateway/scripts/write_build_commit_sha.py index 3496ec81e..6941a8736 100644 --- a/gateway/scripts/write_build_commit_sha.py +++ b/gateway/scripts/write_build_commit_sha.py @@ -1,4 +1,4 @@ -"""Bake /app/.build_commit_sha during the production image build. +"""Validate a repository-root release stamp for the production image. ``.build_commit_sha`` is gitignored. A named ``COPY`` of that path fails on a clean tree before the build starts, and no workflow in this repo creates the @@ -6,7 +6,7 @@ Sources: -1. A stamp already copied into the image (release archive). It is authoritative. +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 @@ -14,7 +14,9 @@ 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. -``BUILD_SHA_PATH`` overrides the output path (tests only). +``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 +image so a stray ``gateway/.build_commit_sha`` cannot become an input. """ from __future__ import annotations @@ -46,9 +48,7 @@ def resolve_stamp(staged: str | None, build_arg: str) -> str: arg = build_arg.strip() if arg and not _valid(arg): - raise SystemExit( - "RELEASE_COMMIT_SHA is not a 7-64 character hex git SHA." - ) + raise SystemExit("RELEASE_COMMIT_SHA is not a 7-64 character hex git SHA.") if staged is None: if not _valid(arg): @@ -61,21 +61,20 @@ def resolve_stamp(staged: str | None, build_arg: str) -> str: "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." - ) + raise SystemExit("RELEASE_COMMIT_SHA disagrees with staged .build_commit_sha.") return staged_sha.lower() def main() -> int: path = Path(os.environ.get("BUILD_SHA_PATH", str(_DEFAULT_PATH))) + staged_path = Path(os.environ.get("STAGED_SHA_PATH", str(path))) staged: str | None try: - staged = path.read_text(encoding="utf-8") + staged = staged_path.read_text(encoding="utf-8") except FileNotFoundError: staged = None except OSError as exc: - raise SystemExit(f"Cannot read {path}: {exc}") from exc + raise SystemExit(f"Cannot read {staged_path}: {exc}") from exc sha = resolve_stamp(staged, os.environ.get("RELEASE_COMMIT_SHA", "")) path.write_text(sha + "\n", encoding="utf-8") diff --git a/gateway/tests/test_write_build_commit_sha.py b/gateway/tests/test_write_build_commit_sha.py index 3b4e0ab8d..2219885ab 100644 --- a/gateway/tests/test_write_build_commit_sha.py +++ b/gateway/tests/test_write_build_commit_sha.py @@ -15,17 +15,29 @@ OTHER = "1234567890abcdef1234567890abcdef12345678" -def _run(tmp_path: Path, staged: str | None, build_arg: str | None): - stamp = tmp_path / ".build_commit_sha" +def _run( + tmp_path: Path, + staged: str | None, + build_arg: str | None, + nested: str | None = None, +): + context = tmp_path / "context" + context.mkdir() + stamp = context / ".build_commit_sha" + output = tmp_path / ".build_commit_sha" if staged is not None: stamp.write_text(staged, encoding="utf-8") + if nested is not None: + (context / "gateway").mkdir() + (context / "gateway" / ".build_commit_sha").write_text(nested, encoding="utf-8") env = os.environ.copy() - env["BUILD_SHA_PATH"] = str(stamp) + env["STAGED_SHA_PATH"] = str(stamp) + env["BUILD_SHA_PATH"] = str(output) if build_arg is None: env.pop("RELEASE_COMMIT_SHA", None) else: env["RELEASE_COMMIT_SHA"] = build_arg - return subprocess.run( + result = subprocess.run( [sys.executable, str(SCRIPT)], cwd=ROOT, env=env, @@ -33,59 +45,82 @@ def _run(tmp_path: Path, staged: str | None, build_arg: str | None): text=True, check=False, ) + return result, output def test_build_arg_writes_lowercase_stamp_with_newline(tmp_path): - result = _run(tmp_path, None, SHA.upper()) + result, output = _run(tmp_path, None, SHA.upper()) assert result.returncode == 0, result.stderr - assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + assert output.read_text(encoding="utf-8") == SHA + "\n" def test_missing_stamp_and_empty_arg_fails(tmp_path): - result = _run(tmp_path, None, "") + result, output = _run(tmp_path, None, "") assert result.returncode != 0 assert "Release commit stamp missing" in result.stderr - assert not (tmp_path / ".build_commit_sha").exists() + assert not output.exists() def test_invalid_build_arg_fails(tmp_path): - result = _run(tmp_path, None, "not-a-sha") + result, output = _run(tmp_path, None, "not-a-sha") assert result.returncode != 0 assert "RELEASE_COMMIT_SHA" in result.stderr - assert not (tmp_path / ".build_commit_sha").exists() + assert not output.exists() def test_staged_file_is_authoritative(tmp_path): - result = _run(tmp_path, SHA + "\n", "") + result, output = _run(tmp_path, SHA + "\n", "") assert result.returncode == 0, result.stderr - assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + assert output.read_text(encoding="utf-8") == SHA + "\n" def test_staged_and_arg_may_differ_only_by_case(tmp_path): - result = _run(tmp_path, SHA.upper() + "\n", SHA) + result, output = _run(tmp_path, SHA.upper() + "\n", SHA) assert result.returncode == 0, result.stderr - assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + assert output.read_text(encoding="utf-8") == SHA + "\n" def test_disagreement_fails_and_leaves_staged_file(tmp_path): - result = _run(tmp_path, SHA + "\n", OTHER) + result, output = _run(tmp_path, SHA + "\n", OTHER) assert result.returncode != 0 assert "disagrees" in result.stderr - assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + assert not output.exists() + assert (tmp_path / "context" / ".build_commit_sha").read_text() == SHA + "\n" def test_invalid_staged_file_is_not_replaced_by_build_arg(tmp_path): - result = _run(tmp_path, "not-a-sha\n", SHA) + result, output = _run(tmp_path, "not-a-sha\n", SHA) assert result.returncode != 0 assert "Staged .build_commit_sha" in result.stderr - assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == "not-a-sha\n" + assert not output.exists() def test_invalid_arg_does_not_override_valid_staged_file(tmp_path): - result = _run(tmp_path, SHA + "\n", "not-a-sha") + result, output = _run(tmp_path, SHA + "\n", "not-a-sha") assert result.returncode != 0 assert "RELEASE_COMMIT_SHA" in result.stderr - assert (tmp_path / ".build_commit_sha").read_text(encoding="utf-8") == SHA + "\n" + assert not output.exists() + + +def test_nested_stamp_alone_cannot_supply_provenance(tmp_path): + result, output = _run(tmp_path, None, None, nested=SHA + "\n") + assert result.returncode != 0 + assert "Release commit stamp missing" in result.stderr + assert not output.exists() + + +def test_root_stamp_overwrites_conflicting_nested_stamp(tmp_path): + result, output = _run(tmp_path, SHA + "\n", None, nested=OTHER + "\n") + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_stale_service_variables_cannot_supply_provenance(tmp_path, monkeypatch): + monkeypatch.setenv("COMMIT_SHA", SHA) + monkeypatch.setenv("BUILD_COMMIT_SHA", SHA) + result, output = _run(tmp_path, None, None) + assert result.returncode != 0 + assert not output.exists() def test_short_sha_rejected(): From 9b3ab29c88ca5ccef2bf28662245b82162f3b5e2 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:51:19 -0700 Subject: [PATCH 04/14] Cover stamp-free development image --- gateway/tests/test_gateway_image_sdk.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/gateway/tests/test_gateway_image_sdk.py b/gateway/tests/test_gateway_image_sdk.py index 90bf6fd51..e94831453 100644 --- a/gateway/tests/test_gateway_image_sdk.py +++ b/gateway/tests/test_gateway_image_sdk.py @@ -83,7 +83,14 @@ def test_release_dockerfile_validates_root_stamp_before_final_copy(): assert text.index("COPY gateway/ /app/") < text.index( "COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha" ) - assert "COPY .build_commit_sha" not in _dockerfile("Dockerfile.dev") + + +def test_development_image_does_not_require_or_copy_a_stamp(): + text = _dockerfile("Dockerfile.dev") + assert "RELEASE_COMMIT_SHA" not in text + assert "write_build_commit_sha.py" not in text + assert "COPY --from=build-metadata" not in text + assert "COPY .build_commit_sha" not in text def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): From dfadd750153db3ed21bb233cc9ae4160d15229e9 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:14:24 -0700 Subject: [PATCH 05/14] SEL-286: Gateway images omit `b2a_sdk`, so app import crashes Linear: SEL-286 Refs https://github.com/agentmiddleware/agent-middleware/issues/106 Engine: grok (fleet coding engine, Grok Bot dispatch) --- .dockerignore | 36 +++++++ gateway/Dockerfile | 17 ++- gateway/Dockerfile.dev | 14 ++- gateway/app/routers/mcp_public.py | 73 ++++++++----- gateway/docker-compose.yml | 6 +- gateway/tests/test_gateway_image_sdk.py | 132 ++++++++++++++++++++++++ 6 files changed, 239 insertions(+), 39 deletions(-) create mode 100644 .dockerignore create mode 100644 gateway/tests/test_gateway_image_sdk.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..225674f13 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,36 @@ +# Image builds use the repository root as the context. See gateway/Dockerfile. +.git +.github +.agents +.claude +.envrc +.vercel +.railway +.venv +**/.venv +.pytest_cache +**/.pytest_cache +.ruff_cache +**/.ruff_cache +__pycache__ +**/__pycache__ +*.py[cod] +**/*.py[cod] +*.pyo +**/*.pyo +*.pyd +**/*.pyd +.env +**/.env +.env.* +**/.env.* +*.db +**/*.db +gateway/tests +gateway/docker-compose.yml +gateway/docker-compose.prod.yml +sdk/typescript +integrations +examples +spec +verifier diff --git a/gateway/Dockerfile b/gateway/Dockerfile index 86df7407e..5a1b9e4dd 100644 --- a/gateway/Dockerfile +++ b/gateway/Dockerfile @@ -2,20 +2,27 @@ FROM python:3.12-slim WORKDIR /app +# b2a_sdk is imported while app.main loads. The build context is the +# repository root (not this directory): sdk/python is not inside gateway/. +# docker build -f gateway/Dockerfile . +# The release stamp .build_commit_sha must sit at that context root. ENV PYTHONUNBUFFERED=1 \ - PYTHONDONTWRITEBYTECODE=1 + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=/sdk/python/src # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ && rm -rf /var/lib/apt/lists/* -# Install Python dependencies -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +# Install Python dependencies, then the in-repo SDK those imports require. +COPY sdk/python /sdk/python +COPY gateway/requirements.txt /tmp/requirements.txt +RUN pip install --no-cache-dir -r /tmp/requirements.txt \ + && pip install --no-cache-dir /sdk/python # Copy application code -COPY . . +COPY gateway/ /app/ # Release contexts must carry a commit stamp generated from the exact Git tree. COPY .build_commit_sha /app/.build_commit_sha diff --git a/gateway/Dockerfile.dev b/gateway/Dockerfile.dev index 159dc475e..cab334703 100644 --- a/gateway/Dockerfile.dev +++ b/gateway/Dockerfile.dev @@ -2,17 +2,23 @@ FROM python:3.12-slim WORKDIR /app +# b2a_sdk is imported while app.main loads. The build context is the +# repository root (not this directory). See docker-compose.yml. +# docker build -f gateway/Dockerfile.dev . ENV PYTHONUNBUFFERED=1 \ - PYTHONDONTWRITEBYTECODE=1 + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=/sdk/python/src RUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ && rm -rf /var/lib/apt/lists/* -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY sdk/python /sdk/python +COPY gateway/requirements.txt /tmp/requirements.txt +RUN pip install --no-cache-dir -r /tmp/requirements.txt \ + && pip install --no-cache-dir /sdk/python -COPY . . +COPY gateway/ /app/ RUN chmod +x scripts/docker_entrypoint.sh \ && groupadd --system app \ diff --git a/gateway/app/routers/mcp_public.py b/gateway/app/routers/mcp_public.py index 359303b50..d5d8cad1a 100644 --- a/gateway/app/routers/mcp_public.py +++ b/gateway/app/routers/mcp_public.py @@ -60,38 +60,55 @@ ) +# Image layout: both Dockerfiles copy the in-repo SDK to /sdk/python, install +# it, and set PYTHONPATH=/sdk/python/src. From /app/app/routers/mcp_public.py, +# parents[3] is /, so the checkout-relative path is this same file. +_IMAGE_SDK_RECEIPT_VERIFIER = Path("/sdk/python/src/b2a_sdk/receipt_verifier.py") +_CHECKOUT_SDK_RECEIPT_VERIFIER = ( + Path(__file__).resolve().parents[3] + / "sdk" + / "python" + / "src" + / "b2a_sdk" + / "receipt_verifier.py" +) + + +def _receipt_verifier_file_candidates() -> tuple[Path, ...]: + """Checkout path first. In the image that path is ``/sdk/python/...``.""" + if _CHECKOUT_SDK_RECEIPT_VERIFIER == _IMAGE_SDK_RECEIPT_VERIFIER: + return (_IMAGE_SDK_RECEIPT_VERIFIER,) + return (_CHECKOUT_SDK_RECEIPT_VERIFIER, _IMAGE_SDK_RECEIPT_VERIFIER) + + +def _load_receipt_verifier_file(module_path: Path): + spec = importlib.util.spec_from_file_location( + "_agent_middleware_receipt_verifier", + module_path, + ) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load receipt verifier from {module_path}") + receipt_verifier = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = receipt_verifier + spec.loader.exec_module(receipt_verifier) + return receipt_verifier + + def _import_receipt_verifier(): - """Import the first-party offline verifier, in-repo when not installed. + """Import the first-party offline verifier. - ``b2a_sdk`` is packaged for external verifiers and is not a declared app - dependency; tests see it via pytest's ``pythonpath`` and deployed images - carry the source tree at the repo root. Falling back to that tree keeps - the public tool running the *same* verifier code an outside party runs, - instead of a drift-prone reimplementation. + Images declare the dependency by installing ``/sdk/python`` and putting + ``/sdk/python/src`` on ``PYTHONPATH``. A checkout that has not installed + the package still loads that same file from the repository root. The + fallback is not a second implementation. """ try: - receipt_verifier = importlib.import_module("b2a_sdk.receipt_verifier") - except ImportError: - module_path = ( - Path(__file__).resolve().parents[3] - / "sdk" - / "python" - / "src" - / "b2a_sdk" - / "receipt_verifier.py" - ) - if not module_path.is_file(): - raise - spec = importlib.util.spec_from_file_location( - "_agent_middleware_receipt_verifier", - module_path, - ) - if spec is None or spec.loader is None: - raise ImportError(f"cannot load receipt verifier from {module_path}") - receipt_verifier = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = receipt_verifier - spec.loader.exec_module(receipt_verifier) - return receipt_verifier + return importlib.import_module("b2a_sdk.receipt_verifier") + except ImportError as import_error: + for module_path in _receipt_verifier_file_candidates(): + if module_path.is_file(): + return _load_receipt_verifier_file(module_path) + raise import_error _receipt_verifier = _import_receipt_verifier() diff --git a/gateway/docker-compose.yml b/gateway/docker-compose.yml index 437243f25..6fb7dc4cc 100644 --- a/gateway/docker-compose.yml +++ b/gateway/docker-compose.yml @@ -3,8 +3,10 @@ services: api: build: - context: . - dockerfile: Dockerfile.dev + # Repository root, so the image can COPY sdk/python. Paths inside the + # Dockerfile are relative to that root; this file stays in gateway/. + context: .. + dockerfile: gateway/Dockerfile.dev ports: - "8000:8000" env_file: diff --git a/gateway/tests/test_gateway_image_sdk.py b/gateway/tests/test_gateway_image_sdk.py new file mode 100644 index 000000000..1f6ef6ab1 --- /dev/null +++ b/gateway/tests/test_gateway_image_sdk.py @@ -0,0 +1,132 @@ +"""Gateway images must ship the in-repo SDK that app import loads. + +``app.main`` imports ``mcp_public``, which imports ``b2a_sdk.receipt_verifier`` +at import time. The SDK is not inside ``gateway/``. A build whose context is +only that directory installs requirements.txt, then fails when uvicorn loads +``app.main:app``. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +from app.routers import mcp_public + +GATEWAY = Path(__file__).resolve().parents[1] +REPO = GATEWAY.parent +_FILE_LOADER = "_agent_middleware_receipt_verifier" + + +def _dockerfile(name: str) -> str: + return (GATEWAY / name).read_text(encoding="utf-8") + + +def test_checkout_still_has_the_verifier_the_fallback_loads(): + assert mcp_public._CHECKOUT_SDK_RECEIPT_VERIFIER.is_file() + assert mcp_public._IMAGE_SDK_RECEIPT_VERIFIER == Path( + "/sdk/python/src/b2a_sdk/receipt_verifier.py" + ) + # Inside the image the module is /app/app/routers/mcp_public.py, so + # parents[3] is /. That is the same file the Dockerfiles copy into place. + container_module = Path("/app/app/routers/mcp_public.py") + derived = ( + container_module.parents[3] + / "sdk" + / "python" + / "src" + / "b2a_sdk" + / "receipt_verifier.py" + ) + assert derived == mcp_public._IMAGE_SDK_RECEIPT_VERIFIER + # On a host checkout the two paths differ, and the repository file wins + # over a stray /sdk tree. In the image they are the same path. + assert mcp_public._receipt_verifier_file_candidates() == ( + mcp_public._CHECKOUT_SDK_RECEIPT_VERIFIER, + mcp_public._IMAGE_SDK_RECEIPT_VERIFIER, + ) + + +def test_image_build_context_contains_the_sdk(): + compose = (GATEWAY / "docker-compose.yml").read_text(encoding="utf-8") + assert "context: .." in compose + assert "dockerfile: gateway/Dockerfile.dev" in compose + context = (GATEWAY / "..").resolve() + assert context == REPO + assert (context / "sdk/python/pyproject.toml").is_file() + assert (context / "sdk/python/src/b2a_sdk/receipt_verifier.py").is_file() + assert (context / "gateway/requirements.txt").is_file() + + +@pytest.mark.parametrize("name", ["Dockerfile", "Dockerfile.dev"]) +def test_images_install_sdk_and_put_it_on_pythonpath(name: str): + text = _dockerfile(name) + sdk_copy = text.index("COPY sdk/python /sdk/python") + requirements = text.index("COPY gateway/requirements.txt /tmp/requirements.txt") + install = text.index("pip install --no-cache-dir /sdk/python") + user = text.index("\nUSER app\n") + assert "PYTHONPATH=/sdk/python/src" in text + assert "COPY gateway/ /app/" in text + assert sdk_copy < install < user + assert requirements < install + + +def test_release_dockerfile_still_requires_the_context_root_stamp(): + text = _dockerfile("Dockerfile") + assert "COPY .build_commit_sha /app/.build_commit_sha" in text + assert "COPY .build_commit_sha" not in _dockerfile("Dockerfile.dev") + + +def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): + lines = [ + line.strip() + for line in (REPO / ".dockerignore").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + assert "sdk" not in lines + assert "sdk/python" not in lines + assert "sdk/python/src" not in lines + assert ".build_commit_sha" not in lines + assert "gateway/tests" in lines + assert ".env" in lines + + +def _package_not_installed(_name: str): + raise ImportError("b2a_sdk is not installed") + + +def test_fallback_uses_the_image_file_when_the_package_is_not_installed( + monkeypatch, tmp_path +): + image_copy = tmp_path / "receipt_verifier.py" + image_copy.write_text( + mcp_public._CHECKOUT_SDK_RECEIPT_VERIFIER.read_text(encoding="utf-8") + + "\nMARKER = 'image-layout'\n", + encoding="utf-8", + ) + monkeypatch.setattr(mcp_public.importlib, "import_module", _package_not_installed) + monkeypatch.setattr( + mcp_public, + "_receipt_verifier_file_candidates", + lambda: (image_copy, Path("/no/such/checkout/receipt_verifier.py")), + ) + sys.modules.pop(_FILE_LOADER, None) + + loaded = mcp_public._import_receipt_verifier() + + assert loaded.MARKER == "image-layout" + assert hasattr(loaded, "verify_bundle") + + +def test_fallback_reraises_the_original_import_error_when_no_file_exists(monkeypatch): + monkeypatch.setattr(mcp_public.importlib, "import_module", _package_not_installed) + monkeypatch.setattr( + mcp_public, + "_receipt_verifier_file_candidates", + lambda: (Path("/no/such/image/receipt_verifier.py"),), + ) + + with pytest.raises(ImportError, match="b2a_sdk is not installed"): + mcp_public._import_receipt_verifier() From 45ef252cdd7c7938cb841320735ad973fa018427 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:57:54 -0700 Subject: [PATCH 06/14] ci: smoke-test gateway image imports --- .github/scripts/smoke_gateway_image.sh | 30 ++++++++++++++++++++++++++ .github/workflows/ci.yml | 15 ++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/smoke_gateway_image.sh diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh new file mode 100644 index 000000000..04b0a4806 --- /dev/null +++ b/.github/scripts/smoke_gateway_image.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Build both gateway images and import the modules needed at app startup. +set -euo pipefail + +if [[ -e .build_commit_sha ]]; then + echo '.build_commit_sha already exists; refusing to replace it' >&2 + exit 1 +fi + +stamp="$(git rev-parse HEAD)" +printf '%s\n' "$stamp" > .build_commit_sha +trap 'rm -f .build_commit_sha' EXIT + +docker build -f gateway/Dockerfile -t amw-gateway:ci-release . +docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-release -c ' +import sys +from pathlib import Path +import app.main +import b2a_sdk.receipt_verifier +assert Path("/app/.build_commit_sha").read_text().strip() == sys.argv[1] +' "$stamp" + +rm .build_commit_sha +docker build -f gateway/Dockerfile.dev -t amw-gateway:ci-dev . +docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-dev -c ' +from pathlib import Path +import app.main +import b2a_sdk.receipt_verifier +assert not Path("/app/.build_commit_sha").exists() +' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4abb9e32..22c2bf959 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -180,6 +180,19 @@ jobs: run: | uv run --no-sync pytest -q tests/test_action_postgres.py tests/test_permit_postgres_concurrency.py tests/test_duplicate_guard_postgres_concurrency.py tests/test_action_database_guard.py --timeout 300 + gateway-image-smoke: + name: Gateway image import smoke + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build and import release and development images + run: bash .github/scripts/smoke_gateway_image.sh + typescript: name: Node ${{ matrix.node-version }} / ${{ matrix.project }} needs: detect @@ -234,7 +247,7 @@ jobs: ci-result: # Single stable check name for branch protection, regardless of how the matrices expand. name: CI result - needs: [detect, python, typescript, postgres-concurrency] + needs: [detect, python, typescript, postgres-concurrency, gateway-image-smoke] if: always() runs-on: ubuntu-latest timeout-minutes: 2 From aa5c214828079baf46d5cd35aa6a53be02491dd6 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:47 -0700 Subject: [PATCH 07/14] Prove release metadata stamp inputs in image smoke job --- .github/scripts/smoke_gateway_image.sh | 52 +++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh index 04b0a4806..838fc7d22 100644 --- a/.github/scripts/smoke_gateway_image.sh +++ b/.github/scripts/smoke_gateway_image.sh @@ -6,10 +6,16 @@ if [[ -e .build_commit_sha ]]; then echo '.build_commit_sha already exists; refusing to replace it' >&2 exit 1 fi +if [[ -e gateway/.build_commit_sha ]]; then + echo 'gateway/.build_commit_sha already exists; refusing to replace it' >&2 + exit 1 +fi stamp="$(git rev-parse HEAD)" +other=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb printf '%s\n' "$stamp" > .build_commit_sha -trap 'rm -f .build_commit_sha' EXIT +printf '%s\n' "$other" > gateway/.build_commit_sha +trap 'rm -f .build_commit_sha gateway/.build_commit_sha' EXIT docker build -f gateway/Dockerfile -t amw-gateway:ci-release . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-release -c ' @@ -17,7 +23,7 @@ import sys from pathlib import Path import app.main import b2a_sdk.receipt_verifier -assert Path("/app/.build_commit_sha").read_text().strip() == sys.argv[1] +assert Path("/app/.build_commit_sha").read_bytes() == (sys.argv[1] + "\n").encode() ' "$stamp" rm .build_commit_sha @@ -28,3 +34,45 @@ import app.main import b2a_sdk.receipt_verifier assert not Path("/app/.build_commit_sha").exists() ' + +# Negative cases build only the small metadata stage. The nested stamp remains +# on disk but is excluded from the root Docker context by .dockerignore. +expect_metadata_failure() { + if docker build --target build-metadata -f gateway/Dockerfile "$@" .; then + echo "metadata stage accepted invalid provenance: $*" >&2 + exit 1 + fi +} + +check_metadata_stamp() { + local image="$1" + docker run --rm --network none --read-only --user 65534:65534 \ + --entrypoint python "$image" -c ' +import sys +from pathlib import Path +assert Path("/stamp/.build_commit_sha").read_bytes() == (sys.argv[1] + "\n").encode() +' "$stamp" +} + +# A gateway-local stamp cannot supply provenance, even when valid. +expect_metadata_failure + +# Argument-only provenance is accepted and written in canonical lowercase. +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 + +rm gateway/.build_commit_sha +expect_metadata_failure # neither root stamp nor argument exists +COMMIT_SHA="$stamp" BUILD_COMMIT_SHA="$stamp" expect_metadata_failure + +printf '%s\n' "${stamp^^}" > .build_commit_sha +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 + +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$other" +expect_metadata_failure --build-arg RELEASE_COMMIT_SHA=not-a-sha + +printf 'not-a-sha\n' > .build_commit_sha +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$stamp" From f0069b51984c2aa3e806319f66f43c92e3d0de3e Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:12:27 -0700 Subject: [PATCH 08/14] ci: keep local gateway state out of image contexts --- .dockerignore | 36 +++++++++++++++ .github/scripts/smoke_gateway_image.sh | 64 ++++++++++++++++++++++++-- 2 files changed, 96 insertions(+), 4 deletions(-) diff --git a/.dockerignore b/.dockerignore index 225674f13..3392fc62a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,10 +4,31 @@ .agents .claude .envrc +**/.envrc .vercel +**/.vercel .railway +**/.railway .venv **/.venv +.venv-local +**/.venv-local +venv +**/venv +env +**/env +node_modules +**/node_modules +.aws +**/.aws +.ssh +**/.ssh +.netrc +**/.netrc +.npmrc +**/.npmrc +.pypirc +**/.pypirc .pytest_cache **/.pytest_cache .ruff_cache @@ -26,7 +47,22 @@ __pycache__ **/.env.* *.db **/*.db +*.db-wal +**/*.db-wal +*.db-shm +**/*.db-shm +*.log +**/*.log +*.pem +**/*.pem +*.key +**/*.key +railway.json +**/railway.json +railway.toml +**/railway.toml gateway/tests +gateway/data gateway/docker-compose.yml gateway/docker-compose.prod.yml sdk/typescript diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh index 04b0a4806..586bc949c 100644 --- a/.github/scripts/smoke_gateway_image.sh +++ b/.github/scripts/smoke_gateway_image.sh @@ -2,14 +2,67 @@ # Build both gateway images and import the modules needed at app startup. set -euo pipefail -if [[ -e .build_commit_sha ]]; then +if [[ -e .build_commit_sha || -L .build_commit_sha ]]; then echo '.build_commit_sha already exists; refusing to replace it' >&2 exit 1 fi +canary_paths=( + gateway/data/quickstart/signing-seed.b64 + .amw-image-smoke.db-wal + gateway/.amw-image-smoke.db-shm + gateway/.amw-image-smoke.log + gateway/.amw-image-smoke.pem + sdk/python/.amw-image-smoke.key +) +for path in "${canary_paths[@]}"; do + if [[ -e "$path" || -L "$path" ]]; then + echo "Canary path already exists: $path" >&2 + exit 1 + fi +done + +created_dirs=() +created_files=() +stamp_created=false +cleanup() { + if [[ "$stamp_created" == true ]]; then rm -f .build_commit_sha; fi + for path in "${created_files[@]}"; do rm -f "$path"; done + for ((i=${#created_dirs[@]}-1; i>=0; i--)); do + rmdir "${created_dirs[i]}" 2>/dev/null || true + done +} +trap cleanup EXIT + +for dir in gateway/data gateway/data/quickstart; do + if [[ ! -d "$dir" ]]; then + mkdir "$dir" + created_dirs+=("$dir") + fi +done +for path in "${canary_paths[@]}"; do + printf 'synthetic image context canary\n' > "$path" + created_files+=("$path") +done + +# A named COPY of an ignored canary must fail before creating any layer. +for path in "${canary_paths[@]}"; do + if printf 'FROM scratch\nCOPY %s /probe/\n' "$path" | docker build -f - . >/dev/null 2>&1; then + echo "Docker context unexpectedly includes $path" >&2 + exit 1 + fi +done + +image_canaries=( + /app/data/quickstart/signing-seed.b64 + /app/.amw-image-smoke.db-shm + /app/.amw-image-smoke.log + /app/.amw-image-smoke.pem + /sdk/python/.amw-image-smoke.key +) stamp="$(git rev-parse HEAD)" printf '%s\n' "$stamp" > .build_commit_sha -trap 'rm -f .build_commit_sha' EXIT +stamp_created=true docker build -f gateway/Dockerfile -t amw-gateway:ci-release . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-release -c ' @@ -18,13 +71,16 @@ from pathlib import Path import app.main import b2a_sdk.receipt_verifier assert Path("/app/.build_commit_sha").read_text().strip() == sys.argv[1] -' "$stamp" +assert all(not Path(path).exists() for path in sys.argv[2:]) +' "$stamp" "${image_canaries[@]}" rm .build_commit_sha docker build -f gateway/Dockerfile.dev -t amw-gateway:ci-dev . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-dev -c ' +import sys from pathlib import Path import app.main import b2a_sdk.receipt_verifier assert not Path("/app/.build_commit_sha").exists() -' +assert all(not Path(path).exists() for path in sys.argv[1:]) +' "${image_canaries[@]}" From 8d167c78ce0b11db392f9a5fb0f64b83d0aa3ffb Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:18:36 -0700 Subject: [PATCH 09/14] ci: exclude nested local tooling from image context --- .dockerignore | 2 ++ .github/scripts/smoke_gateway_image.sh | 12 +++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.dockerignore b/.dockerignore index 3392fc62a..91b0226ae 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,7 +2,9 @@ .git .github .agents +**/.agents .claude +**/.claude .envrc **/.envrc .vercel diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh index 586bc949c..07480da6b 100644 --- a/.github/scripts/smoke_gateway_image.sh +++ b/.github/scripts/smoke_gateway_image.sh @@ -13,6 +13,9 @@ canary_paths=( gateway/.amw-image-smoke.db-shm gateway/.amw-image-smoke.log gateway/.amw-image-smoke.pem + gateway/.agents/amw-image-smoke.txt + gateway/.claude/amw-image-smoke.txt + gateway/.envrc sdk/python/.amw-image-smoke.key ) for path in "${canary_paths[@]}"; do @@ -34,7 +37,11 @@ cleanup() { } trap cleanup EXIT -for dir in gateway/data gateway/data/quickstart; do +for dir in gateway/data gateway/data/quickstart gateway/.agents gateway/.claude; do + if [[ -L "$dir" ]]; then + echo "Canary parent is a symlink: $dir" >&2 + exit 1 + fi if [[ ! -d "$dir" ]]; then mkdir "$dir" created_dirs+=("$dir") @@ -58,6 +65,9 @@ image_canaries=( /app/.amw-image-smoke.db-shm /app/.amw-image-smoke.log /app/.amw-image-smoke.pem + /app/.agents/amw-image-smoke.txt + /app/.claude/amw-image-smoke.txt + /app/.envrc /sdk/python/.amw-image-smoke.key ) stamp="$(git rev-parse HEAD)" From 144faeacfc08d5d4652c8ce2c260d834cbd16fba Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:21:30 -0700 Subject: [PATCH 10/14] Test nested workstation exclusions in gateway context --- gateway/tests/test_gateway_image_sdk.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gateway/tests/test_gateway_image_sdk.py b/gateway/tests/test_gateway_image_sdk.py index dcc85fde6..e11cb4992 100644 --- a/gateway/tests/test_gateway_image_sdk.py +++ b/gateway/tests/test_gateway_image_sdk.py @@ -111,6 +111,9 @@ def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): assert "**/*.key" in lines assert "gateway/data" in lines assert "*.db-wal" in lines + assert "**/.agents" in lines + assert "**/.claude" in lines + assert "**/.envrc" in lines assert "**/*.db-wal" in lines assert "*.db-shm" in lines assert "**/*.db-shm" in lines From 380caee93bdb39dc24fb333b5492b3cd1e928641 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:41:09 -0700 Subject: [PATCH 11/14] fix: validate gateway image commit stamp Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- .dockerignore | 23 +-- .github/scripts/smoke_gateway_image.sh | 67 ++++++++- gateway/Dockerfile | 18 ++- gateway/app/core/build_metadata.py | 4 +- gateway/scripts/write_build_commit_sha.py | 85 +++++++++++ gateway/tests/test_build_provenance.py | 2 +- gateway/tests/test_gateway_image_sdk.py | 34 ++++- .../tests/test_stale_commit_sha_prevention.py | 22 ++- gateway/tests/test_write_build_commit_sha.py | 132 ++++++++++++++++++ 9 files changed, 365 insertions(+), 22 deletions(-) create mode 100644 gateway/scripts/write_build_commit_sha.py create mode 100644 gateway/tests/test_write_build_commit_sha.py diff --git a/.dockerignore b/.dockerignore index 91b0226ae..73a28c656 100644 --- a/.dockerignore +++ b/.dockerignore @@ -11,6 +11,18 @@ **/.vercel .railway **/.railway +.aws +**/.aws +.ssh +**/.ssh +.npmrc +**/.npmrc +.pypirc +**/.pypirc +.netrc +**/.netrc +.secrets +**/.secrets .venv **/.venv .venv-local @@ -21,16 +33,6 @@ env **/env node_modules **/node_modules -.aws -**/.aws -.ssh -**/.ssh -.netrc -**/.netrc -.npmrc -**/.npmrc -.pypirc -**/.pypirc .pytest_cache **/.pytest_cache .ruff_cache @@ -63,6 +65,7 @@ railway.json **/railway.json railway.toml **/railway.toml +gateway/.build_commit_sha gateway/tests gateway/data gateway/docker-compose.yml diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh index 07480da6b..4887a0847 100644 --- a/.github/scripts/smoke_gateway_image.sh +++ b/.github/scripts/smoke_gateway_image.sh @@ -6,6 +6,10 @@ if [[ -e .build_commit_sha || -L .build_commit_sha ]]; then echo '.build_commit_sha already exists; refusing to replace it' >&2 exit 1 fi +if [[ -e gateway/.build_commit_sha || -L gateway/.build_commit_sha ]]; then + echo 'gateway/.build_commit_sha already exists; refusing to replace it' >&2 + exit 1 +fi canary_paths=( gateway/data/quickstart/signing-seed.b64 @@ -71,8 +75,11 @@ image_canaries=( /sdk/python/.amw-image-smoke.key ) stamp="$(git rev-parse HEAD)" +other=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb printf '%s\n' "$stamp" > .build_commit_sha +printf '%s\n' "$other" > gateway/.build_commit_sha stamp_created=true +created_files+=(gateway/.build_commit_sha) docker build -f gateway/Dockerfile -t amw-gateway:ci-release . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-release -c ' @@ -80,10 +87,26 @@ import sys from pathlib import Path import app.main import b2a_sdk.receipt_verifier -assert Path("/app/.build_commit_sha").read_text().strip() == sys.argv[1] +assert Path("/app/.build_commit_sha").read_bytes() == (sys.argv[1] + "\n").encode() assert all(not Path(path).exists() for path in sys.argv[2:]) ' "$stamp" "${image_canaries[@]}" +docker build --target build-metadata -f gateway/Dockerfile -t amw-gateway:ci-metadata . +docker run --rm --network none --read-only --user 65534:65534 \ + --entrypoint python amw-gateway:ci-metadata -c ' +import sys +from pathlib import Path +root = Path("/context") +expected = (sys.argv[1] + "\n").encode() +assert (root / ".build_commit_sha").read_bytes() == expected +assert Path("/stamp/.build_commit_sha").read_bytes() == expected +assert (root / "sdk/python/src/b2a_sdk/receipt_verifier.py").is_file() +assert (root / "gateway/scripts/write_build_commit_sha.py").is_file() +assert not (root / "gateway/data").exists() +assert not (root / "gateway/.build_commit_sha").exists() +assert all(not (root / path).exists() for path in sys.argv[2:]) +' "$stamp" "${canary_paths[@]}" + rm .build_commit_sha docker build -f gateway/Dockerfile.dev -t amw-gateway:ci-dev . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-dev -c ' @@ -94,3 +117,45 @@ import b2a_sdk.receipt_verifier assert not Path("/app/.build_commit_sha").exists() assert all(not Path(path).exists() for path in sys.argv[1:]) ' "${image_canaries[@]}" + +# Negative cases build only the small metadata stage. The nested stamp remains +# on disk but is excluded from the root Docker context by .dockerignore. +expect_metadata_failure() { + if docker build --target build-metadata -f gateway/Dockerfile "$@" .; then + echo "metadata stage accepted invalid provenance: $*" >&2 + exit 1 + fi +} + +check_metadata_stamp() { + local image="$1" + docker run --rm --network none --read-only --user 65534:65534 \ + --entrypoint python "$image" -c ' +import sys +from pathlib import Path +assert Path("/stamp/.build_commit_sha").read_bytes() == (sys.argv[1] + "\n").encode() +' "$stamp" +} + +# A gateway-local stamp cannot supply provenance, even when valid. +expect_metadata_failure + +# Argument-only provenance is accepted and written in canonical lowercase. +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 + +rm gateway/.build_commit_sha +expect_metadata_failure # neither root stamp nor argument exists +COMMIT_SHA="$stamp" BUILD_COMMIT_SHA="$stamp" expect_metadata_failure + +printf '%s\n' "${stamp^^}" > .build_commit_sha +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 + +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$other" +expect_metadata_failure --build-arg RELEASE_COMMIT_SHA=not-a-sha + +printf 'not-a-sha\n' > .build_commit_sha +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$stamp" diff --git a/gateway/Dockerfile b/gateway/Dockerfile index 5a1b9e4dd..5bf9c00c7 100644 --- a/gateway/Dockerfile +++ b/gateway/Dockerfile @@ -1,3 +1,16 @@ +FROM python:3.12-slim AS build-metadata + +# The release archive may carry a gitignored stamp at its context root. +# Copying the context lets the writer validate that optional input without a +# named COPY that fails on clean trees. .dockerignore excludes local secrets. +WORKDIR /context +COPY . /context/ +ARG RELEASE_COMMIT_SHA +RUN mkdir /stamp \ + && STAGED_SHA_PATH=/context/.build_commit_sha \ + BUILD_SHA_PATH=/stamp/.build_commit_sha \ + python /context/gateway/scripts/write_build_commit_sha.py + FROM python:3.12-slim WORKDIR /app @@ -24,8 +37,9 @@ RUN pip install --no-cache-dir -r /tmp/requirements.txt \ # Copy application code COPY gateway/ /app/ -# Release contexts must carry a commit stamp generated from the exact Git tree. -COPY .build_commit_sha /app/.build_commit_sha +# Transfer only the validated stamp, after the app copy. A stale stamp under +# gateway/ cannot bypass validation or overwrite this output. +COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha RUN chmod +x scripts/docker_entrypoint.sh \ && groupadd --system app \ diff --git a/gateway/app/core/build_metadata.py b/gateway/app/core/build_metadata.py index d3259246b..75200b2e8 100644 --- a/gateway/app/core/build_metadata.py +++ b/gateway/app/core/build_metadata.py @@ -57,7 +57,9 @@ def get_build_provenance() -> str: The documented Railway release path builds a temporary context from ``git archive`` at the exact release SHA and adds a stamp file before - upload. The Dockerfile requires that file at build time. Railway sets + upload. The production image build writes that same path from the staged + file or, when the file is absent, from the ``RELEASE_COMMIT_SHA`` build + arg. A missing, invalid, or disagreeing stamp fails the build. Railway sets ``RAILWAY_GIT_COMMIT_SHA`` only for GitHub-triggered deployments, so a local ``railway up`` release relies on the baked stamp. A disagreement — or a missing stamp — is the signature of a build that did not come through diff --git a/gateway/scripts/write_build_commit_sha.py b/gateway/scripts/write_build_commit_sha.py new file mode 100644 index 000000000..8e567e811 --- /dev/null +++ b/gateway/scripts/write_build_commit_sha.py @@ -0,0 +1,85 @@ +"""Validate a repository-root release stamp for the production image. + +``.build_commit_sha`` is gitignored. A named Docker COPY of that path fails on a +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. + +``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 +image so a stray ``gateway/.build_commit_sha`` cannot become an input. +""" + +from __future__ import annotations + +import os +import re +import sys +from pathlib import Path + +# Same shape as app.core.build_metadata._GIT_SHA_RE. Kept local so image +# build does not import application settings. +_GIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,64}$") +_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)." +) + + +def _valid(value: str) -> bool: + return _GIT_SHA_RE.fullmatch(value) is not None + + +def resolve_stamp(staged: str | None, build_arg: str) -> str: + """Return the lowercase SHA to write. + + ``staged`` is the file contents, or ``None`` when the file is absent. + """ + + 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() + + +def main() -> int: + path = Path(os.environ.get("BUILD_SHA_PATH", str(_DEFAULT_PATH))) + staged_path = Path(os.environ.get("STAGED_SHA_PATH", str(path))) + staged: str | None + try: + staged = staged_path.read_text(encoding="utf-8") + except FileNotFoundError: + staged = None + except OSError as exc: + raise SystemExit(f"Cannot read {staged_path}: {exc}") from exc + + sha = resolve_stamp(staged, os.environ.get("RELEASE_COMMIT_SHA", "")) + path.write_text(sha + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/gateway/tests/test_build_provenance.py b/gateway/tests/test_build_provenance.py index deb8beb34..679c40517 100644 --- a/gateway/tests/test_build_provenance.py +++ b/gateway/tests/test_build_provenance.py @@ -50,7 +50,7 @@ def test_stamped_is_case_insensitive(baked, monkeypatch): def test_stamped_tolerates_trailing_newline(baked, monkeypatch): - # The Dockerfile writes the stamp with `echo`, so it carries a newline. + # The image stamp is written with a trailing newline. baked(SHA_A + "\n") monkeypatch.setenv("RAILWAY_GIT_COMMIT_SHA", SHA_A) assert get_build_provenance() == "stamped" diff --git a/gateway/tests/test_gateway_image_sdk.py b/gateway/tests/test_gateway_image_sdk.py index 1f6ef6ab1..e11cb4992 100644 --- a/gateway/tests/test_gateway_image_sdk.py +++ b/gateway/tests/test_gateway_image_sdk.py @@ -73,10 +73,24 @@ def test_images_install_sdk_and_put_it_on_pythonpath(name: str): assert requirements < install -def test_release_dockerfile_still_requires_the_context_root_stamp(): +def test_release_dockerfile_validates_root_stamp_before_final_copy(): text = _dockerfile("Dockerfile") - assert "COPY .build_commit_sha /app/.build_commit_sha" in text - assert "COPY .build_commit_sha" not in _dockerfile("Dockerfile.dev") + assert "COPY . /context/" in text + assert "STAGED_SHA_PATH=/context/.build_commit_sha" in text + assert "BUILD_SHA_PATH=/stamp/.build_commit_sha" in text + assert "python /context/gateway/scripts/write_build_commit_sha.py" in text + assert "COPY .build_commit_sha /app/.build_commit_sha" not in text + assert text.index("COPY gateway/ /app/") < text.index( + "COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha" + ) + + +def test_development_image_does_not_require_or_copy_a_stamp(): + text = _dockerfile("Dockerfile.dev") + assert "RELEASE_COMMIT_SHA" not in text + assert "write_build_commit_sha.py" not in text + assert "COPY --from=build-metadata" not in text + assert "COPY .build_commit_sha" not in text def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): @@ -91,6 +105,20 @@ def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): assert ".build_commit_sha" not in lines assert "gateway/tests" in lines assert ".env" in lines + assert "**/.env" in lines + assert "gateway/.build_commit_sha" in lines + assert "*.pem" in lines + assert "**/*.key" in lines + assert "gateway/data" in lines + assert "*.db-wal" in lines + assert "**/.agents" in lines + assert "**/.claude" in lines + assert "**/.envrc" in lines + assert "**/*.db-wal" in lines + assert "*.db-shm" in lines + assert "**/*.db-shm" in lines + assert "*.log" in lines + assert "**/*.log" in lines def _package_not_installed(_name: str): diff --git a/gateway/tests/test_stale_commit_sha_prevention.py b/gateway/tests/test_stale_commit_sha_prevention.py index e50f61e0b..5691bb541 100644 --- a/gateway/tests/test_stale_commit_sha_prevention.py +++ b/gateway/tests/test_stale_commit_sha_prevention.py @@ -253,11 +253,25 @@ async def test_deployment_without_baked_stamp_reports_null_not_stale( get_settings.cache_clear() -def test_dockerfile_requires_staged_build_commit_sha_file(): - """Dockerfile must reject a release upload that lacks the staged stamp.""" - # Use relative path from test file location to repo root +def test_dockerfile_bakes_commit_stamp_without_copying_gitignored_file(): + """Production image build must not COPY a gitignored stamp that is absent. + + A named COPY fails on a clean tree before the build starts. The image + still refuses to finish without a staged file or RELEASE_COMMIT_SHA. + The arg must not be COMMIT_SHA or BUILD_COMMIT_SHA: those names match + untrusted Railway service variables. + """ repo_root = Path(__file__).parent.parent dockerfile = (repo_root / "Dockerfile").read_text(encoding="utf-8") - assert "COPY .build_commit_sha /app/.build_commit_sha" in dockerfile + assert "COPY .build_commit_sha" not in dockerfile + assert "COPY . /context/" in dockerfile + assert "ARG RELEASE_COMMIT_SHA" in dockerfile + assert "STAGED_SHA_PATH=/context/.build_commit_sha" in dockerfile + assert "BUILD_SHA_PATH=/stamp/.build_commit_sha" in dockerfile + assert "python /context/gateway/scripts/write_build_commit_sha.py" in dockerfile + assert dockerfile.index("COPY gateway/ /app/") < dockerfile.index( + "COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha" + ) assert "ARG COMMIT_SHA" not in dockerfile + assert "ARG BUILD_COMMIT_SHA" not in dockerfile diff --git a/gateway/tests/test_write_build_commit_sha.py b/gateway/tests/test_write_build_commit_sha.py new file mode 100644 index 000000000..2219885ab --- /dev/null +++ b/gateway/tests/test_write_build_commit_sha.py @@ -0,0 +1,132 @@ +"""Production image stamp: staged file or RELEASE_COMMIT_SHA, never a missing COPY.""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from scripts.write_build_commit_sha import resolve_stamp + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "write_build_commit_sha.py" +SHA = "abcdef0123456789abcdef0123456789abcdef01" +OTHER = "1234567890abcdef1234567890abcdef12345678" + + +def _run( + tmp_path: Path, + staged: str | None, + build_arg: str | None, + nested: str | None = None, +): + context = tmp_path / "context" + context.mkdir() + stamp = context / ".build_commit_sha" + output = tmp_path / ".build_commit_sha" + if staged is not None: + stamp.write_text(staged, encoding="utf-8") + if nested is not None: + (context / "gateway").mkdir() + (context / "gateway" / ".build_commit_sha").write_text(nested, encoding="utf-8") + env = os.environ.copy() + env["STAGED_SHA_PATH"] = str(stamp) + env["BUILD_SHA_PATH"] = str(output) + if build_arg is None: + env.pop("RELEASE_COMMIT_SHA", None) + else: + env["RELEASE_COMMIT_SHA"] = build_arg + result = subprocess.run( + [sys.executable, str(SCRIPT)], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + return result, output + + +def test_build_arg_writes_lowercase_stamp_with_newline(tmp_path): + result, output = _run(tmp_path, None, SHA.upper()) + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_missing_stamp_and_empty_arg_fails(tmp_path): + result, output = _run(tmp_path, None, "") + assert result.returncode != 0 + assert "Release commit stamp missing" in result.stderr + assert not output.exists() + + +def test_invalid_build_arg_fails(tmp_path): + result, output = _run(tmp_path, None, "not-a-sha") + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA" in result.stderr + assert not output.exists() + + +def test_staged_file_is_authoritative(tmp_path): + result, output = _run(tmp_path, SHA + "\n", "") + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_staged_and_arg_may_differ_only_by_case(tmp_path): + result, output = _run(tmp_path, SHA.upper() + "\n", SHA) + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_disagreement_fails_and_leaves_staged_file(tmp_path): + result, output = _run(tmp_path, SHA + "\n", OTHER) + assert result.returncode != 0 + assert "disagrees" in result.stderr + assert not output.exists() + assert (tmp_path / "context" / ".build_commit_sha").read_text() == SHA + "\n" + + +def test_invalid_staged_file_is_not_replaced_by_build_arg(tmp_path): + result, output = _run(tmp_path, "not-a-sha\n", SHA) + assert result.returncode != 0 + assert "Staged .build_commit_sha" in result.stderr + assert not output.exists() + + +def test_invalid_arg_does_not_override_valid_staged_file(tmp_path): + result, output = _run(tmp_path, SHA + "\n", "not-a-sha") + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA" in result.stderr + assert not output.exists() + + +def test_nested_stamp_alone_cannot_supply_provenance(tmp_path): + result, output = _run(tmp_path, None, None, nested=SHA + "\n") + assert result.returncode != 0 + assert "Release commit stamp missing" in result.stderr + assert not output.exists() + + +def test_root_stamp_overwrites_conflicting_nested_stamp(tmp_path): + result, output = _run(tmp_path, SHA + "\n", None, nested=OTHER + "\n") + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_stale_service_variables_cannot_supply_provenance(tmp_path, monkeypatch): + monkeypatch.setenv("COMMIT_SHA", SHA) + monkeypatch.setenv("BUILD_COMMIT_SHA", SHA) + result, output = _run(tmp_path, None, None) + assert result.returncode != 0 + assert not output.exists() + + +def test_short_sha_rejected(): + with pytest.raises(SystemExit): + resolve_stamp(None, "abc123") + + +def test_seven_char_sha_accepted(): + assert resolve_stamp(None, "abc1234") == "abc1234" From f8c55ad82a7f81a023e22ba6bcdd38176948f6a4 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:37:20 -0700 Subject: [PATCH 12/14] fix: retain gateway image and stamp proof on current main Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- .dockerignore | 23 +-- .github/scripts/smoke_gateway_image.sh | 67 ++++++++- gateway/Dockerfile | 18 ++- gateway/app/core/build_metadata.py | 4 +- gateway/scripts/write_build_commit_sha.py | 85 +++++++++++ gateway/tests/test_build_provenance.py | 2 +- gateway/tests/test_gateway_image_sdk.py | 34 ++++- .../tests/test_stale_commit_sha_prevention.py | 22 ++- gateway/tests/test_write_build_commit_sha.py | 132 ++++++++++++++++++ 9 files changed, 365 insertions(+), 22 deletions(-) create mode 100644 gateway/scripts/write_build_commit_sha.py create mode 100644 gateway/tests/test_write_build_commit_sha.py diff --git a/.dockerignore b/.dockerignore index 91b0226ae..73a28c656 100644 --- a/.dockerignore +++ b/.dockerignore @@ -11,6 +11,18 @@ **/.vercel .railway **/.railway +.aws +**/.aws +.ssh +**/.ssh +.npmrc +**/.npmrc +.pypirc +**/.pypirc +.netrc +**/.netrc +.secrets +**/.secrets .venv **/.venv .venv-local @@ -21,16 +33,6 @@ env **/env node_modules **/node_modules -.aws -**/.aws -.ssh -**/.ssh -.netrc -**/.netrc -.npmrc -**/.npmrc -.pypirc -**/.pypirc .pytest_cache **/.pytest_cache .ruff_cache @@ -63,6 +65,7 @@ railway.json **/railway.json railway.toml **/railway.toml +gateway/.build_commit_sha gateway/tests gateway/data gateway/docker-compose.yml diff --git a/.github/scripts/smoke_gateway_image.sh b/.github/scripts/smoke_gateway_image.sh index 07480da6b..4887a0847 100644 --- a/.github/scripts/smoke_gateway_image.sh +++ b/.github/scripts/smoke_gateway_image.sh @@ -6,6 +6,10 @@ if [[ -e .build_commit_sha || -L .build_commit_sha ]]; then echo '.build_commit_sha already exists; refusing to replace it' >&2 exit 1 fi +if [[ -e gateway/.build_commit_sha || -L gateway/.build_commit_sha ]]; then + echo 'gateway/.build_commit_sha already exists; refusing to replace it' >&2 + exit 1 +fi canary_paths=( gateway/data/quickstart/signing-seed.b64 @@ -71,8 +75,11 @@ image_canaries=( /sdk/python/.amw-image-smoke.key ) stamp="$(git rev-parse HEAD)" +other=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb printf '%s\n' "$stamp" > .build_commit_sha +printf '%s\n' "$other" > gateway/.build_commit_sha stamp_created=true +created_files+=(gateway/.build_commit_sha) docker build -f gateway/Dockerfile -t amw-gateway:ci-release . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-release -c ' @@ -80,10 +87,26 @@ import sys from pathlib import Path import app.main import b2a_sdk.receipt_verifier -assert Path("/app/.build_commit_sha").read_text().strip() == sys.argv[1] +assert Path("/app/.build_commit_sha").read_bytes() == (sys.argv[1] + "\n").encode() assert all(not Path(path).exists() for path in sys.argv[2:]) ' "$stamp" "${image_canaries[@]}" +docker build --target build-metadata -f gateway/Dockerfile -t amw-gateway:ci-metadata . +docker run --rm --network none --read-only --user 65534:65534 \ + --entrypoint python amw-gateway:ci-metadata -c ' +import sys +from pathlib import Path +root = Path("/context") +expected = (sys.argv[1] + "\n").encode() +assert (root / ".build_commit_sha").read_bytes() == expected +assert Path("/stamp/.build_commit_sha").read_bytes() == expected +assert (root / "sdk/python/src/b2a_sdk/receipt_verifier.py").is_file() +assert (root / "gateway/scripts/write_build_commit_sha.py").is_file() +assert not (root / "gateway/data").exists() +assert not (root / "gateway/.build_commit_sha").exists() +assert all(not (root / path).exists() for path in sys.argv[2:]) +' "$stamp" "${canary_paths[@]}" + rm .build_commit_sha docker build -f gateway/Dockerfile.dev -t amw-gateway:ci-dev . docker run --rm --network none --read-only --entrypoint python amw-gateway:ci-dev -c ' @@ -94,3 +117,45 @@ import b2a_sdk.receipt_verifier assert not Path("/app/.build_commit_sha").exists() assert all(not Path(path).exists() for path in sys.argv[1:]) ' "${image_canaries[@]}" + +# Negative cases build only the small metadata stage. The nested stamp remains +# on disk but is excluded from the root Docker context by .dockerignore. +expect_metadata_failure() { + if docker build --target build-metadata -f gateway/Dockerfile "$@" .; then + echo "metadata stage accepted invalid provenance: $*" >&2 + exit 1 + fi +} + +check_metadata_stamp() { + local image="$1" + docker run --rm --network none --read-only --user 65534:65534 \ + --entrypoint python "$image" -c ' +import sys +from pathlib import Path +assert Path("/stamp/.build_commit_sha").read_bytes() == (sys.argv[1] + "\n").encode() +' "$stamp" +} + +# A gateway-local stamp cannot supply provenance, even when valid. +expect_metadata_failure + +# Argument-only provenance is accepted and written in canonical lowercase. +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 + +rm gateway/.build_commit_sha +expect_metadata_failure # neither root stamp nor argument exists +COMMIT_SHA="$stamp" BUILD_COMMIT_SHA="$stamp" expect_metadata_failure + +printf '%s\n' "${stamp^^}" > .build_commit_sha +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 + +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$other" +expect_metadata_failure --build-arg RELEASE_COMMIT_SHA=not-a-sha + +printf 'not-a-sha\n' > .build_commit_sha +expect_metadata_failure --build-arg "RELEASE_COMMIT_SHA=$stamp" diff --git a/gateway/Dockerfile b/gateway/Dockerfile index 5a1b9e4dd..5bf9c00c7 100644 --- a/gateway/Dockerfile +++ b/gateway/Dockerfile @@ -1,3 +1,16 @@ +FROM python:3.12-slim AS build-metadata + +# The release archive may carry a gitignored stamp at its context root. +# Copying the context lets the writer validate that optional input without a +# named COPY that fails on clean trees. .dockerignore excludes local secrets. +WORKDIR /context +COPY . /context/ +ARG RELEASE_COMMIT_SHA +RUN mkdir /stamp \ + && STAGED_SHA_PATH=/context/.build_commit_sha \ + BUILD_SHA_PATH=/stamp/.build_commit_sha \ + python /context/gateway/scripts/write_build_commit_sha.py + FROM python:3.12-slim WORKDIR /app @@ -24,8 +37,9 @@ RUN pip install --no-cache-dir -r /tmp/requirements.txt \ # Copy application code COPY gateway/ /app/ -# Release contexts must carry a commit stamp generated from the exact Git tree. -COPY .build_commit_sha /app/.build_commit_sha +# Transfer only the validated stamp, after the app copy. A stale stamp under +# gateway/ cannot bypass validation or overwrite this output. +COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha RUN chmod +x scripts/docker_entrypoint.sh \ && groupadd --system app \ diff --git a/gateway/app/core/build_metadata.py b/gateway/app/core/build_metadata.py index d3259246b..75200b2e8 100644 --- a/gateway/app/core/build_metadata.py +++ b/gateway/app/core/build_metadata.py @@ -57,7 +57,9 @@ def get_build_provenance() -> str: The documented Railway release path builds a temporary context from ``git archive`` at the exact release SHA and adds a stamp file before - upload. The Dockerfile requires that file at build time. Railway sets + upload. The production image build writes that same path from the staged + file or, when the file is absent, from the ``RELEASE_COMMIT_SHA`` build + arg. A missing, invalid, or disagreeing stamp fails the build. Railway sets ``RAILWAY_GIT_COMMIT_SHA`` only for GitHub-triggered deployments, so a local ``railway up`` release relies on the baked stamp. A disagreement — or a missing stamp — is the signature of a build that did not come through diff --git a/gateway/scripts/write_build_commit_sha.py b/gateway/scripts/write_build_commit_sha.py new file mode 100644 index 000000000..8e567e811 --- /dev/null +++ b/gateway/scripts/write_build_commit_sha.py @@ -0,0 +1,85 @@ +"""Validate a repository-root release stamp for the production image. + +``.build_commit_sha`` is gitignored. A named Docker COPY of that path fails on a +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. + +``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 +image so a stray ``gateway/.build_commit_sha`` cannot become an input. +""" + +from __future__ import annotations + +import os +import re +import sys +from pathlib import Path + +# Same shape as app.core.build_metadata._GIT_SHA_RE. Kept local so image +# build does not import application settings. +_GIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,64}$") +_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)." +) + + +def _valid(value: str) -> bool: + return _GIT_SHA_RE.fullmatch(value) is not None + + +def resolve_stamp(staged: str | None, build_arg: str) -> str: + """Return the lowercase SHA to write. + + ``staged`` is the file contents, or ``None`` when the file is absent. + """ + + 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() + + +def main() -> int: + path = Path(os.environ.get("BUILD_SHA_PATH", str(_DEFAULT_PATH))) + staged_path = Path(os.environ.get("STAGED_SHA_PATH", str(path))) + staged: str | None + try: + staged = staged_path.read_text(encoding="utf-8") + except FileNotFoundError: + staged = None + except OSError as exc: + raise SystemExit(f"Cannot read {staged_path}: {exc}") from exc + + sha = resolve_stamp(staged, os.environ.get("RELEASE_COMMIT_SHA", "")) + path.write_text(sha + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/gateway/tests/test_build_provenance.py b/gateway/tests/test_build_provenance.py index deb8beb34..679c40517 100644 --- a/gateway/tests/test_build_provenance.py +++ b/gateway/tests/test_build_provenance.py @@ -50,7 +50,7 @@ def test_stamped_is_case_insensitive(baked, monkeypatch): def test_stamped_tolerates_trailing_newline(baked, monkeypatch): - # The Dockerfile writes the stamp with `echo`, so it carries a newline. + # The image stamp is written with a trailing newline. baked(SHA_A + "\n") monkeypatch.setenv("RAILWAY_GIT_COMMIT_SHA", SHA_A) assert get_build_provenance() == "stamped" diff --git a/gateway/tests/test_gateway_image_sdk.py b/gateway/tests/test_gateway_image_sdk.py index 1f6ef6ab1..e11cb4992 100644 --- a/gateway/tests/test_gateway_image_sdk.py +++ b/gateway/tests/test_gateway_image_sdk.py @@ -73,10 +73,24 @@ def test_images_install_sdk_and_put_it_on_pythonpath(name: str): assert requirements < install -def test_release_dockerfile_still_requires_the_context_root_stamp(): +def test_release_dockerfile_validates_root_stamp_before_final_copy(): text = _dockerfile("Dockerfile") - assert "COPY .build_commit_sha /app/.build_commit_sha" in text - assert "COPY .build_commit_sha" not in _dockerfile("Dockerfile.dev") + assert "COPY . /context/" in text + assert "STAGED_SHA_PATH=/context/.build_commit_sha" in text + assert "BUILD_SHA_PATH=/stamp/.build_commit_sha" in text + assert "python /context/gateway/scripts/write_build_commit_sha.py" in text + assert "COPY .build_commit_sha /app/.build_commit_sha" not in text + assert text.index("COPY gateway/ /app/") < text.index( + "COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha" + ) + + +def test_development_image_does_not_require_or_copy_a_stamp(): + text = _dockerfile("Dockerfile.dev") + assert "RELEASE_COMMIT_SHA" not in text + assert "write_build_commit_sha.py" not in text + assert "COPY --from=build-metadata" not in text + assert "COPY .build_commit_sha" not in text def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): @@ -91,6 +105,20 @@ def test_root_dockerignore_keeps_sdk_sources_and_the_stamp(): assert ".build_commit_sha" not in lines assert "gateway/tests" in lines assert ".env" in lines + assert "**/.env" in lines + assert "gateway/.build_commit_sha" in lines + assert "*.pem" in lines + assert "**/*.key" in lines + assert "gateway/data" in lines + assert "*.db-wal" in lines + assert "**/.agents" in lines + assert "**/.claude" in lines + assert "**/.envrc" in lines + assert "**/*.db-wal" in lines + assert "*.db-shm" in lines + assert "**/*.db-shm" in lines + assert "*.log" in lines + assert "**/*.log" in lines def _package_not_installed(_name: str): diff --git a/gateway/tests/test_stale_commit_sha_prevention.py b/gateway/tests/test_stale_commit_sha_prevention.py index e50f61e0b..5691bb541 100644 --- a/gateway/tests/test_stale_commit_sha_prevention.py +++ b/gateway/tests/test_stale_commit_sha_prevention.py @@ -253,11 +253,25 @@ async def test_deployment_without_baked_stamp_reports_null_not_stale( get_settings.cache_clear() -def test_dockerfile_requires_staged_build_commit_sha_file(): - """Dockerfile must reject a release upload that lacks the staged stamp.""" - # Use relative path from test file location to repo root +def test_dockerfile_bakes_commit_stamp_without_copying_gitignored_file(): + """Production image build must not COPY a gitignored stamp that is absent. + + A named COPY fails on a clean tree before the build starts. The image + still refuses to finish without a staged file or RELEASE_COMMIT_SHA. + The arg must not be COMMIT_SHA or BUILD_COMMIT_SHA: those names match + untrusted Railway service variables. + """ repo_root = Path(__file__).parent.parent dockerfile = (repo_root / "Dockerfile").read_text(encoding="utf-8") - assert "COPY .build_commit_sha /app/.build_commit_sha" in dockerfile + assert "COPY .build_commit_sha" not in dockerfile + assert "COPY . /context/" in dockerfile + assert "ARG RELEASE_COMMIT_SHA" in dockerfile + assert "STAGED_SHA_PATH=/context/.build_commit_sha" in dockerfile + assert "BUILD_SHA_PATH=/stamp/.build_commit_sha" in dockerfile + assert "python /context/gateway/scripts/write_build_commit_sha.py" in dockerfile + assert dockerfile.index("COPY gateway/ /app/") < dockerfile.index( + "COPY --from=build-metadata /stamp/.build_commit_sha /app/.build_commit_sha" + ) assert "ARG COMMIT_SHA" not in dockerfile + assert "ARG BUILD_COMMIT_SHA" not in dockerfile diff --git a/gateway/tests/test_write_build_commit_sha.py b/gateway/tests/test_write_build_commit_sha.py new file mode 100644 index 000000000..2219885ab --- /dev/null +++ b/gateway/tests/test_write_build_commit_sha.py @@ -0,0 +1,132 @@ +"""Production image stamp: staged file or RELEASE_COMMIT_SHA, never a missing COPY.""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from scripts.write_build_commit_sha import resolve_stamp + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "write_build_commit_sha.py" +SHA = "abcdef0123456789abcdef0123456789abcdef01" +OTHER = "1234567890abcdef1234567890abcdef12345678" + + +def _run( + tmp_path: Path, + staged: str | None, + build_arg: str | None, + nested: str | None = None, +): + context = tmp_path / "context" + context.mkdir() + stamp = context / ".build_commit_sha" + output = tmp_path / ".build_commit_sha" + if staged is not None: + stamp.write_text(staged, encoding="utf-8") + if nested is not None: + (context / "gateway").mkdir() + (context / "gateway" / ".build_commit_sha").write_text(nested, encoding="utf-8") + env = os.environ.copy() + env["STAGED_SHA_PATH"] = str(stamp) + env["BUILD_SHA_PATH"] = str(output) + if build_arg is None: + env.pop("RELEASE_COMMIT_SHA", None) + else: + env["RELEASE_COMMIT_SHA"] = build_arg + result = subprocess.run( + [sys.executable, str(SCRIPT)], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + return result, output + + +def test_build_arg_writes_lowercase_stamp_with_newline(tmp_path): + result, output = _run(tmp_path, None, SHA.upper()) + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_missing_stamp_and_empty_arg_fails(tmp_path): + result, output = _run(tmp_path, None, "") + assert result.returncode != 0 + assert "Release commit stamp missing" in result.stderr + assert not output.exists() + + +def test_invalid_build_arg_fails(tmp_path): + result, output = _run(tmp_path, None, "not-a-sha") + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA" in result.stderr + assert not output.exists() + + +def test_staged_file_is_authoritative(tmp_path): + result, output = _run(tmp_path, SHA + "\n", "") + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_staged_and_arg_may_differ_only_by_case(tmp_path): + result, output = _run(tmp_path, SHA.upper() + "\n", SHA) + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_disagreement_fails_and_leaves_staged_file(tmp_path): + result, output = _run(tmp_path, SHA + "\n", OTHER) + assert result.returncode != 0 + assert "disagrees" in result.stderr + assert not output.exists() + assert (tmp_path / "context" / ".build_commit_sha").read_text() == SHA + "\n" + + +def test_invalid_staged_file_is_not_replaced_by_build_arg(tmp_path): + result, output = _run(tmp_path, "not-a-sha\n", SHA) + assert result.returncode != 0 + assert "Staged .build_commit_sha" in result.stderr + assert not output.exists() + + +def test_invalid_arg_does_not_override_valid_staged_file(tmp_path): + result, output = _run(tmp_path, SHA + "\n", "not-a-sha") + assert result.returncode != 0 + assert "RELEASE_COMMIT_SHA" in result.stderr + assert not output.exists() + + +def test_nested_stamp_alone_cannot_supply_provenance(tmp_path): + result, output = _run(tmp_path, None, None, nested=SHA + "\n") + assert result.returncode != 0 + assert "Release commit stamp missing" in result.stderr + assert not output.exists() + + +def test_root_stamp_overwrites_conflicting_nested_stamp(tmp_path): + result, output = _run(tmp_path, SHA + "\n", None, nested=OTHER + "\n") + assert result.returncode == 0, result.stderr + assert output.read_text(encoding="utf-8") == SHA + "\n" + + +def test_stale_service_variables_cannot_supply_provenance(tmp_path, monkeypatch): + monkeypatch.setenv("COMMIT_SHA", SHA) + monkeypatch.setenv("BUILD_COMMIT_SHA", SHA) + result, output = _run(tmp_path, None, None) + assert result.returncode != 0 + assert not output.exists() + + +def test_short_sha_rejected(): + with pytest.raises(SystemExit): + resolve_stamp(None, "abc123") + + +def test_seven_char_sha_accepted(): + assert resolve_stamp(None, "abc1234") == "abc1234" From b46086f3d0704fd346b9c6534bb5a4e78af677de Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:59:31 -0700 Subject: [PATCH 13/14] fix: resolve CI and update with main (SEL-285 retry pass, codex) --- .../services/mcp_dispatch_reconciliation.py | 4 +- .../tests/test_mcp_dispatch_reconciliation.py | 62 +++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/gateway/app/services/mcp_dispatch_reconciliation.py b/gateway/app/services/mcp_dispatch_reconciliation.py index 9ed7dc0ae..c79848567 100644 --- a/gateway/app/services/mcp_dispatch_reconciliation.py +++ b/gateway/app/services/mcp_dispatch_reconciliation.py @@ -56,7 +56,7 @@ } ) _LEGACY_UNSNAPSHOTTED_OUTCOMES = frozenset( - {"failed_refunded", "delivery_uncertain", "response_rejected"} + {"success", "failed_refunded", "delivery_uncertain", "response_rejected"} ) @@ -842,7 +842,7 @@ def _assert_receipt_match( signed_constraints = receipt.constraints_evaluated expected_constraints = constraints_evaluated or {} if canonical_json(signed_constraints) != canonical_json(expected_constraints): - # Older direct failure paths signed valid receipts before permit-v2 + # Older direct finalization paths signed valid receipts before permit-v2 # snapshots were attached. Recover only that exact legacy shape; # a receipt with any signed permit evidence must match in full. legacy_omission = ( diff --git a/gateway/tests/test_mcp_dispatch_reconciliation.py b/gateway/tests/test_mcp_dispatch_reconciliation.py index 1610a300f..52081c5d2 100644 --- a/gateway/tests/test_mcp_dispatch_reconciliation.py +++ b/gateway/tests/test_mcp_dispatch_reconciliation.py @@ -989,8 +989,12 @@ async def test_existing_receipt_missing_idempotency_completion_replays_full_resu state="succeeded", result_payload=upstream_result, idempotency_endpoint=GOVERNED_MCP_IDEMPOTENCY_ENDPOINT, + max_calls_per_tool=5, ) attempt = await _attempt(seed.attempt_id) + assert await McpDispatchReconciliationService()._permit_constraints_snapshot( + seed.permit_id + ) == {"max_calls_per_tool": {seed.tool_name: 5}} audit = await record_audit_event( event="mcp.invoke", wallet_id=seed.wallet_id, @@ -1027,6 +1031,7 @@ async def test_existing_receipt_missing_idempotency_completion_replays_full_resu outcome="success", audit_event_id=audit.event_id, ) + assert receipt.constraints_evaluated == {} await get_idempotency_service().mark_charged( wallet_id=seed.wallet_id, endpoint=seed.idempotency_endpoint, @@ -1074,6 +1079,63 @@ async def test_existing_receipt_missing_idempotency_completion_replays_full_resu assert int(audit_count or 0) == 1 +@pytest.mark.anyio +async def test_existing_success_receipt_rejects_conflicting_signed_permit_snapshot( + client: AsyncClient, + clean_database, +) -> None: + upstream_result = {"content": [{"type": "text", "text": "confirmed"}]} + seed = await _seed_attempt( + client, + suffix="success-conflicting-snapshot", + state="succeeded", + result_payload=upstream_result, + max_calls_per_tool=5, + ) + attempt = await _attempt(seed.attempt_id) + audit = await record_audit_event( + event="mcp.invoke", + wallet_id=seed.wallet_id, + tool=seed.tool_name, + endpoint=ENDPOINT, + auth_source="db", + key_id=seed.key_id, + ok=True, + metadata={"dispatch_attempt_id": seed.attempt_id}, + ) + receipt = await get_receipt_service().create_receipt( + idempotency_record_id=attempt.idempotency_record_id, + dispatch_attempt_id=attempt.attempt_id, + response_hash_override=attempt.response_hash, + permit_id=attempt.permit_id, + wallet_id=attempt.wallet_id, + key_id=attempt.key_id, + tool=attempt.public_tool_id, + request_payload=None, + request_hash=attempt.request_hash, + response_payload=upstream_result, + ledger_entry_id=attempt.ledger_entry_id, + credits_authorized=attempt.credits_authorized, + credits_charged=attempt.credits_charged, + outcome="success", + audit_event_id=audit.event_id, + constraints_evaluated={"max_calls_per_tool": {seed.tool_name: 4}}, + ) + valid, reason, _ = await get_receipt_service().verify_receipt(receipt.receipt_id) + assert (valid, reason) == (True, None) + + with pytest.raises( + DispatchAttemptError, match="^dispatch_receipt_linkage_conflict$" + ): + await McpDispatchReconciliationService()._get_or_create_receipt( + attempt=attempt, + result_payload=upstream_result, + outcome="success", + audit_event_id=audit.event_id, + constraints_evaluated={"max_calls_per_tool": {seed.tool_name: 5}}, + ) + + @pytest.mark.anyio async def test_existing_receipt_adoption_matches_effective_jev_constraints( client: AsyncClient, From 02a0d5adaa11a1c1ca694f4485f2e711ee22d7d7 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Mon, 19 Oct 2026 07:01:39 -0700 Subject: [PATCH 14/14] ci: retrigger checks after GitHub startup_failure (SEL-285)