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/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/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_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, 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"