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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions emule_workspace/prepared_native_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import subprocess
import tomllib
import time
import urllib.error
import urllib.request
from uuid import uuid4

Expand All @@ -23,6 +24,7 @@
from .linux_containers import LinuxDocker, _builder_user, run_owned_container

SIGNER = "https://github.com/emulebb/emulebb-build/.github/workflows/ci-linux-images.yml@refs/heads/main"
REPOSITORY_METADATA_URL = "https://api.github.com/repos/emulebb/emulebb-build"
BUNDLED_TOOLS = Path("/opt/emulebb/tools")
FORWARD = ("EMULEBB_WORKSPACE_ROOT", "EMULEBB_WORKSPACE_OUTPUT_ROOT", "CARGO_TARGET_DIR",
"EMULEBB_RUST_REPO", "EMULEBB_TOOLING_REPO", "MINIUPNP_ROOT", "PCPNATPMP_ROOT",
Expand Down Expand Up @@ -53,12 +55,41 @@ def query(*args):
return result


def build_repository_metadata(*, token: str, deadline: float) -> dict:
"""Read the fixed GitHub authority within the metadata request budget."""
request = urllib.request.Request(REPOSITORY_METADATA_URL, headers={
"Accept": "application/vnd.github+json", "User-Agent": "emulebb-ci-image-verifier"})
if token:
# WHY: hosted runners share the small anonymous API quota. Use their
# existing credential on this exact request and strip it on redirects.
request.add_unredirected_header("Authorization", "Bearer " + token)
for attempt in range(3):
try:
return json.loads(public_metadata_bytes(request, deadline=deadline))
except urllib.error.HTTPError as error:
with error:
headers = error.headers or {}
retry_after = headers.get("Retry-After", "")
remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset", "")
retryable = error.code == 429 or (
error.code == 403 and (retry_after or remaining == "0")
)
if not retryable:
raise RuntimeError(f"GitHub Build repository metadata request failed (HTTP {error.code})") from None
delay = max(2 ** attempt, int(retry_after) if re.fullmatch(r"[0-9]{1,10}", retry_after) else 0)
if remaining == "0" and re.fullmatch(r"[0-9]{1,10}", reset):
delay = max(delay, int(reset) - time.time())
if attempt == 2 or time.monotonic() + delay >= deadline:
raise RuntimeError("GitHub Build repository metadata rate limit exceeded its retry budget") from None
time.sleep(delay)


def verify_attestation(image: str, builder_sha: str, *, timeout: int = 180) -> dict:
"""Require cryptographic Build producer identity before pulling/executing code."""
deadline = time.monotonic() + timeout
request = urllib.request.Request("https://api.github.com/repos/emulebb/emulebb-build", headers={
"Accept": "application/vnd.github+json", "User-Agent": "emulebb-ci-image-verifier"})
repository = json.loads(public_metadata_bytes(request, deadline=min(deadline, time.monotonic() + 20)))
token = os.environ.get("GH_TOKEN", "").strip()
repository = build_repository_metadata(token=token, deadline=min(deadline, time.monotonic() + 20))
owner = repository.get("owner", {})
# WHY: OCI-bundle mode skips GitHub's current-name lookup. Binding the
# current immutable repository/owner IDs to the verified certificate rejects
Expand All @@ -67,6 +98,8 @@ def verify_attestation(image: str, builder_sha: str, *, timeout: int = 180) -> d
or str(repository.get("id")) != "499553807" or str(owner.get("id")) != "281581430"
or owner.get("html_url") != "https://github.com/emulebb"):
raise RuntimeError("Public Build repository identity differs from the reviewed immutable authority")
if token:
print("Verified Build repository identity through the authenticated GitHub API.", flush=True)
remaining = deadline - time.monotonic()
if remaining <= 0:
raise RuntimeError("Prepared image attestation deadline expired")
Expand Down
49 changes: 49 additions & 0 deletions tests/test_prepared_native_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import os
from pathlib import Path
from types import SimpleNamespace
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler
from click.testing import CliRunner

import pytest
Expand Down Expand Up @@ -277,6 +279,7 @@ def test_verified_baked_runtime_seeds_existing_cache_without_download(tmp_path,

@pytest.fixture
def certificate(monkeypatch):
monkeypatch.delenv("GH_TOKEN", raising=False)
source = "b" * 40
image = prepared.PREPARED + "@sha256:" + "1" * 64
certificate = {"subjectAlternativeName": prepared.SIGNER, "sourceRepositoryDigest": source,
Expand Down Expand Up @@ -315,6 +318,52 @@ def test_oci_bundle_verification_restores_immutable_certificate_identity(certifi
assert command[command.index("--source-digest") + 1] == certificate.source


def test_repository_lookup_retries_a_rate_limit_with_the_scoped_credential(certificate, monkeypatch):
monkeypatch.setenv("GH_TOKEN", "synthetic-actions-token")
monkeypatch.setattr(prepared.time, "monotonic", lambda: 100)
attempts, delays = [], []

def metadata(request, *, deadline):
assert request.full_url == prepared.REPOSITORY_METADATA_URL
assert request.get_header("Authorization") == "Bearer synthetic-actions-token"
redirected = HTTPRedirectHandler().redirect_request(
request, None, 302, "Found", {}, "https://example.invalid/metadata",
)
assert not redirected.has_header("Authorization")
attempts.append(deadline)
if len(attempts) == 1:
raise HTTPError(request.full_url, 403, "rate limit exceeded", {"Retry-After": "2"}, None)
return json.dumps(certificate.repository).encode()

monkeypatch.setattr(prepared, "public_metadata_bytes", metadata)
monkeypatch.setattr(prepared.time, "sleep", delays.append)
result = prepared.verify_attestation(certificate.image, certificate.source)
assert result["cryptographicallyVerified"] is True
assert attempts == [120, 120]
assert delays == [2]


@pytest.mark.parametrize(("headers", "message"), [
({}, "HTTP 403"),
({"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "1500"}, "rate limit exceeded its retry budget"),
])
def test_repository_lookup_fails_closed_outside_the_retry_budget(certificate, monkeypatch, headers, message):
monkeypatch.setattr(prepared.time, "monotonic", lambda: 100)
monkeypatch.setattr(prepared.time, "time", lambda: 1000)
calls = []

def denied(request, *, deadline):
calls.append(deadline)
raise HTTPError(request.full_url, 403, "synthetic forbidden", headers, None)

monkeypatch.setattr(prepared, "public_metadata_bytes", denied)
monkeypatch.setattr(prepared.time, "sleep", lambda _: pytest.fail("Unexpected retry delay"))
with pytest.raises(RuntimeError, match=message):
prepared.verify_attestation(certificate.image, certificate.source)
assert calls == [120]
assert not certificate.calls


@pytest.mark.parametrize("field,value", [
("sourceRepositoryIdentifier", "999"), ("sourceRepositoryOwnerIdentifier", "999"),
("sourceRepositoryURI", "https://github.com/foreign/repository"),
Expand Down