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
20 changes: 14 additions & 6 deletions .github/workflows/attested-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,27 @@ jobs:
--deny-self-hosted-runners
done

- name: Prove anonymous clean-VPS verification works (no token/login)
# This tests the PUBLIC API + Sigstore bundle fallback used on a VPS.
# The workflow token is deliberately not exposed to this subprocess.
- name: Verify signed release in isolated CLI without anonymous API IP exhaustion
# GitHub-hosted runners share the unauthenticated REST rate limit by
# egress IP (60/hour). Only GET /attestations/sha256:... receives this
# short-lived Actions token; downloaded artifacts and bundles remain
# UNTRUSTED until the same offline signature, certificate identity,
# main ref and exact SHA checks all pass.
# This is NOT an anonymous-network clean-VPS acceptance test. That
# separate deployment gate remains required before a production rollout.
env:
GH_CONFIG_DIR: ${{ runner.temp }}/isolated-anonymous-gh
GH_CONFIG_DIR: ${{ runner.temp }}/isolated-release-gh
XMESH_ATTESTATION_INDEX_TOKEN: ${{ github.token }}
run: |
unset GH_TOKEN GITHUB_TOKEN
python3 - <<'PY'
import os,tempfile
from pathlib import Path
import release_verify
with tempfile.TemporaryDirectory() as temp:
files=release_verify.stage_revision(os.environ['GITHUB_SHA'],Path(temp))
files=release_verify.stage_revision(
os.environ['GITHUB_SHA'], Path(temp),
attestations_read_token=os.environ['XMESH_ATTESTATION_INDEX_TOKEN'])
assert set(files)==set(release_verify.FILES)
print('Clean VPS verified all four public release files with no Github login')
print('Verified exact signed release: isolated CLI, offline OIDC proof, scoped API reads')
PY
41 changes: 29 additions & 12 deletions release_verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import hashlib
import json
import os
import tempfile
from urllib.parse import urlparse
from pathlib import Path
Expand All @@ -32,17 +33,29 @@ def redirect_request(self, req, fp, code, msg, headers, newurl):
return None


def fetch_bytes(url: str, limit: int) -> bytes:
def fetch_bytes(url: str, limit: int, *, attestations_read_token: str | None = None) -> bytes:
if not url.startswith(("https://api.github.com/", "https://raw.githubusercontent.com/")):
raise ValueError("Untrusted source host")
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler(context=ssl.create_default_context()),
NoRedirect(),
)
with opener.open(urllib.request.Request(url, headers={
"User-Agent": "XMesh-Sub-Release-Verifier/1",
"Accept": "application/vnd.github+json",
}), timeout=25) as reply:
headers = {
"User-Agent": "XMesh-Sub-Release-Verifier/1",
"Accept": "application/vnd.github+json",
}
# GitHub Actions shares its unauthenticated 60/hour IP quota with other
# runners. Its short-lived token can fetch the *public attestation index*
# without granting the attestation any trust. This is never used for raw
# source downloads and never passed to the offline signature verifier.
index_prefix = f"https://api.github.com/repos/{REPO}/attestations/sha256:"
if attestations_read_token is not None:
if not url.startswith(index_prefix) or not attestations_read_token.isascii() or not (
1 <= len(attestations_read_token) <= 1024
) or any(not (ch.isalnum() or ch in "-_.") for ch in attestations_read_token):
raise ValueError("Invalid attestation index read credential or endpoint")
headers["Authorization"] = "Bearer " + attestations_read_token
with opener.open(urllib.request.Request(url, headers=headers), timeout=25) as reply:
data = reply.read(limit + 1)
if len(data) > limit:
raise ValueError("Oversized release response")
Expand All @@ -68,15 +81,16 @@ def latest_source_sha() -> str:
return sha


def public_bundles(file: Path) -> list[dict]:
def public_bundles(file: Path, *, attestations_read_token: str | None = None) -> list[dict]:
"""Fetch public Sigstore bundles without a GitHub login or access token.

The API response and bundle URLs are untrusted. The actual signature,
signer identity, artifact digest and source SHA are checked by gh offline.
"""
digest = hashlib.sha256(file.read_bytes()).hexdigest()
index = json.loads(fetch_bytes(
f"https://api.github.com/repos/{REPO}/attestations/sha256:{digest}", 256 * 1024))
f"https://api.github.com/repos/{REPO}/attestations/sha256:{digest}", 256 * 1024,
attestations_read_token=attestations_read_token))
entries = index.get("attestations") if isinstance(index, dict) else None
if not isinstance(entries, list) or not 1 <= len(entries) <= 30:
raise ValueError("No public attestation bundles")
Expand Down Expand Up @@ -112,11 +126,11 @@ def public_bundles(file: Path) -> list[dict]:
return bundles


def verify_file(file: Path, sha: str) -> None:
def verify_file(file: Path, sha: str, *, attestations_read_token: str | None = None) -> None:
if not SHA_RE.fullmatch(sha) or not file.is_file() or file.is_symlink():
raise ValueError("Invalid release artifact")
ensure_gh()
bundles = public_bundles(file)
bundles = public_bundles(file, attestations_read_token=attestations_read_token)
with tempfile.TemporaryDirectory(prefix="xmesh-attestation-") as tmp:
path = Path(tmp) / "bundles.jsonl"
path.write_text("".join(json.dumps(x, separators=(",", ":")) + "\n" for x in bundles))
Expand All @@ -130,9 +144,12 @@ def verify_file(file: Path, sha: str) -> None:
"--source-digest", sha,
"--deny-self-hosted-runners",
], check=True, timeout=90, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
stderr=subprocess.DEVNULL,
# Even the optional CI GET token must not reach the gh process.
env={key: value for key, value in os.environ.items()
if key not in ("GH_TOKEN", "GITHUB_TOKEN", "XMESH_ATTESTATION_INDEX_TOKEN")})

def stage_revision(sha: str, directory: Path) -> dict[str, Path]:
def stage_revision(sha: str, directory: Path, *, attestations_read_token: str | None = None) -> dict[str, Path]:
if not SHA_RE.fullmatch(sha) or not directory.is_dir() or directory.is_symlink():
raise ValueError("Invalid release staging")
result = {}
Expand All @@ -145,7 +162,7 @@ def stage_revision(sha: str, directory: Path) -> dict[str, Path]:
if file.exists() or file.is_symlink():
raise ValueError("Refusing existing release staging target")
file.write_bytes(data)
verify_file(file, sha)
verify_file(file, sha, attestations_read_token=attestations_read_token)
result[name] = file
version = result["VERSION"].read_text("ascii").strip()
if not re.fullmatch(r"\d+\.\d+\.\d+", version):
Expand Down
61 changes: 61 additions & 0 deletions tests/test-release-verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,67 @@ def test_untrusted_public_bundle_url_is_rejected(self):
with self.assertRaises(ValueError):
release.public_bundles(file)

def test_ci_token_is_restricted_to_attestation_index_get(self):
index = ("https://api.github.com/repos/" + release.REPO
+ "/attestations/sha256:" + "a" * 64)
with patch.object(release.urllib.request, "build_opener") as make_opener:
reply = make_opener.return_value.open.return_value.__enter__.return_value
reply.read.return_value = b'{"attestations":[]}'
self.assertEqual(
release.fetch_bytes(index, 1024,
attestations_read_token="ghs_test-safe_123"),
b'{"attestations":[]}')
req = make_opener.return_value.open.call_args.args[0]
self.assertEqual(req.full_url, index)
self.assertEqual(req.get_header("Authorization"),
"Bearer ghs_test-safe_123")
make_opener.return_value.open.reset_mock()
release.fetch_bytes(index, 1024)
unauthenticated = make_opener.return_value.open.call_args.args[0]
self.assertIsNone(unauthenticated.get_header("Authorization"))
for url in (
"https://raw.githubusercontent.com/" + release.REPO + "/main/VERSION",
"https://api.github.com/repos/" + release.REPO + "/commits/main",
"http://api.github.com/repos/" + release.REPO + "/attestations/sha256:" + "a" * 64,
):
with self.assertRaises(ValueError):
release.fetch_bytes(url, 1024,
attestations_read_token="ghs_test-safe_123")
self.assertEqual(make_opener.return_value.open.call_count, 1)
for invalid in ("token with spaces", "bad\r\nInjected: true", ""):
with self.assertRaises(ValueError):
release.fetch_bytes(index, 1024,
attestations_read_token=invalid)

def test_optional_api_token_never_reaches_offline_verifier(self):
sha = "f" * 40
with tempfile.TemporaryDirectory() as d:
file = Path(d) / "install.sh"
file.write_text("release")
with patch.object(release, "ensure_gh"), patch.object(
release, "public_bundles",
return_value=[{"verificationMaterial": {}, "dsseEnvelope": {}}]
) as bundles, patch.object(release.subprocess, "run") as runner, patch.dict(
release.os.environ,
{"XMESH_ATTESTATION_INDEX_TOKEN": "ghs_test-safe_123",
"GH_TOKEN": "fake-gh", "GITHUB_TOKEN": "fake-github"},
):
release.verify_file(
file, sha, attestations_read_token="ghs_test-safe_123")
bundles.assert_called_once_with(
file, attestations_read_token="ghs_test-safe_123")
args = runner.call_args.args[0]
self.assertIn("--bundle", args)
self.assertEqual(args[args.index("--source-digest") + 1], sha)
self.assertEqual(args[args.index("--cert-identity") + 1],
release.CERT_IDENTITY)
self.assertEqual(args[args.index("--source-ref") + 1],
release.SOURCE_REF)
self.assertNotIn("XMESH_ATTESTATION_INDEX_TOKEN",
runner.call_args.kwargs["env"])
self.assertNotIn("GH_TOKEN", runner.call_args.kwargs["env"])
self.assertNotIn("GITHUB_TOKEN", runner.call_args.kwargs["env"])

def test_reject_vulnerable_cli(self):
for raw in ('gh version 2.45.0 (Ubuntu)\n','gh version 2.101.9\n','nonsense\n'):
with patch.object(release.subprocess,'run') as call:
Expand Down
Loading