"""Evidence provenance verifier (Issue #124): binds a Geargrafx evidence artifact to a GitHub attestation. The artifact is build//cdread-probe/cdread-evidence.json, written by tests/integration/geargrafx_cdread.py inside the BIOS DEV workflow (api-source.yml). That workflow signs it, together with the probe ROM, with actions/attest-build-provenance. CI then runs (push to main only, see api-source.yml): gh attestation verify ARTIFACT --repo OWNER/REPO --signer-workflow OWNER/REPO/.github/workflows/api-source.yml \ --source-ref refs/heads/main --source-digest SHA --deny-self-hosted-runners --format json > VERIFY.json gh api repos/OWNER/REPO/actions/runs/RUN_ID/attempts/ATTEMPT > RUN.json python3 tools/evidence_provenance.py ARTIFACT --repo OWNER/REPO --commit SHA --attestation VERIFY.json \ --run RUN.json --rom ROM verify() takes the gh outputs as injected inputs and never runs gh or the network. Self-declared JSON fields, hashes, and environment variables (GITHUB_ACTIONS, GITHUB_SHA, ...) are never proof of origin. The ROM hash and the synthetic CD fixture hashes are recomputed here (ROM file bytes; fixture regenerated by tools/make_cd_image.py at this checkout) and compared with the artifact, so they are not taken from the attested JSON. Results: PASS content is consistent (pinned Geargrafx, every SCENARIO_KIND scenario has its exact kind, primary RUN is one cold + one warm halt, recomputed ROM/fixture hashes) AND one verified attestation has this file and the ROM as subjects and was signed by api-source.yml at refs/heads/main of the expected repository and commit, on a GitHub-hosted runner via push or workflow_dispatch, AND its runInvocationURI names the supplied workflow run, which ran that workflow on main at that commit in the same repository. FAIL content contradicts the pins or the recomputed hashes, OR the producer is not the trusted one (PR head, fork, other workflow/ref/repo/commit/run), OR the digest does not match. BLOCKED attestation given but the gh output, the run record, the ROM, or the fixture hashes are missing/unusable. LOCAL_ONLY no attestation: local, unsigned, or forged JSON. Never compatibility evidence. PASS means attested *emulator diagnostic* evidence only: result['compatibility'] is always NOT_PROMOTED. It does not promote any BIOS compatibility stage. Not checked: branch protection on main (a repository setting, not visible in the attestation). Without it anyone with write access can push to main, so a main attestation proves "ran on main", not "reviewed". """ import argparse import hashlib import json import re import sys import tempfile from pathlib import Path from provenance_guard import load_denylist # same denylist file and parser as the provenance guard (#117) ROOT = Path(__file__).resolve().parents[1] PASS, FAIL, BLOCKED, LOCAL_ONLY = 'PASS', 'FAIL', 'BLOCKED', 'LOCAL_ONLY' TRUSTED_TRIGGERS = ('push', 'workflow_dispatch') TRUSTED_REF = 'refs/heads/main' NOT_PROMOTED = 'NOT_PROMOTED: attested emulator diagnostic only, never a BIOS compatibility PASS' _EXPECTED_FAILURES = ( 'wrong_sector_requested_lba6', 'invalid_sector_lba16', 'invalid_sector_lba_max', 'read_past_disc_end_lba14_x3', 'tampered_identity_byte3', 'tampered_last_byte2047', 'zero_sector_count', 'oversized_sector_count', 'selection_never_answered_timeout', 'drive_abort_at_data_in_entry', 'judge_observation_mutations', 'halt_unconfirmed_cut_0_steps_after_arrival', 'halt_unconfirmed_cut_1_steps_after_arrival', 'halt_unconfirmed_cut_63_steps_after_arrival', 'budget_exhausted_before_any_halt', 'no_media_loaded', 'blank_data_disc') REQUIRED_SCENARIOS = ('single_sector_lba5', 'first_sector_lba0', 'last_sector_lba15', 'three_sectors_lba5', 'disc_end_boundary_lba13_x3') # Exact result kind of every scenario tests/integration/geargrafx_cdread.py records (a superset of the #118 # tools/cd_read_contract.py table). The artifact must carry exactly these names with exactly these kinds: a missing, # extra, or re-kinded scenario (a bad request recorded as PASS, a positive read as PASS_EXPECTED_FAILURE) is FAIL. SCENARIO_KIND = {**dict.fromkeys(REQUIRED_SCENARIOS, 'PASS'), 'halt_confirmation_exact_window': 'PASS', **dict.fromkeys(_EXPECTED_FAILURES, 'PASS_EXPECTED_FAILURE'), 'read6_on_audio_track_lba': 'OBSERVED_EMULATOR_BEHAVIOUR', 'empty_disc_image': 'OBSERVED_EMULATOR_BEHAVIOUR'} SIGNER_WORKFLOW = '.github/workflows/api-source.yml' HEX40 = re.compile(r'[0-9a-f]{40}') HEX64 = re.compile(r'[0-9a-f]{64}') REPO = re.compile(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+') LOCAL_TRUST = 'LOCAL_ONLY: no GitHub artifact attestation; local or unsigned output is not evidence' def _get(value, *keys): """Nested dict lookup that returns None instead of raising on a missing key or a non-dict level.""" for key in keys: if not isinstance(value, dict): return None value = value.get(key) return value def artifact_findings(artifact, policy, rom_bytes=None, fixture=None): """Content checks against the pins, SCENARIO_KIND, and the independently recomputed ROM/fixture hashes.""" if not isinstance(artifact, dict): return ['artifact is not a JSON object'] errors = [] if artifact.get('status') != 'PASS': errors.append('artifact status is not PASS') if artifact.get('geargrafx_revision') != policy['geargrafx_revision']: errors.append('geargrafx_revision differs from the pinned tools/dependencies.json revision') if artifact.get('source_archive_sha256') != policy['geargrafx_sha256']: errors.append('source_archive_sha256 differs from the pinned Geargrafx archive hash') rom_sha = artifact.get('rom_sha256') if not isinstance(rom_sha, str) or not HEX64.fullmatch(rom_sha): errors.append('rom_sha256 missing or not SHA-256') elif rom_bytes is not None and hashlib.sha256(rom_bytes).hexdigest() != rom_sha: errors.append('recomputed ROM sha256 does not match rom_sha256') for key in ('bin_sha256', 'cue_sha256'): value = _get(artifact, 'disc', key) if not isinstance(value, str) or not HEX64.fullmatch(value): errors.append(f'disc.{key} missing or not SHA-256') elif fixture is not None and fixture.get(key) != value: errors.append(f'recomputed synthetic fixture {key} does not match disc.{key}') denied = policy.get('denied_sha256', set()) hashes = (rom_sha, _get(artifact, 'disc', 'bin_sha256'), _get(artifact, 'disc', 'cue_sha256')) if any(isinstance(value, str) and value in denied for value in hashes): errors.append('ROM or disc sha256 is on the denylist') tests = artifact.get('tests') if not isinstance(tests, dict): errors.append('tests missing') else: for name, kind in SCENARIO_KIND.items(): got = _get(tests, name, 'status') if got != kind: errors.append(f'scenario {name} must be {kind}, got {got!r}') extra = sorted(str(name) for name in tests if name not in SCENARIO_KIND) if extra: errors.append(f"unexpected scenarios (not in SCENARIO_KIND): {', '.join(extra)}") runs = _get(artifact, 'primary_observations', 'RUN') if not isinstance(runs, list) or sorted(str(_get(run, 'cycle')) for run in runs) != ['cold', 'warm']: errors.append('primary RUN observations must be exactly one cold and one warm run') elif any(_get(run, 'reason') != 'cd_halt_ok' for run in runs): errors.append('primary RUN observations did not both halt at cd_halt_ok') return errors def _statements(attestation): """Return verificationResult objects from gh attestation verify --format json, or None if unusable.""" if not isinstance(attestation, list): return None results = [_get(entry, 'verificationResult') for entry in attestation] results = [result for result in results if isinstance(result, dict)] return results or None def _subject_digests(result): subjects = _get(result, 'statement', 'subject') if not isinstance(subjects, list): return set() return {digest for digest in (_get(subject, 'digest', 'sha256') for subject in subjects) if isinstance(digest, str)} def certificate_findings(result, policy): """Producer identity: the attested run must be api-source.yml on refs/heads/main at the expected commit.""" certificate = _get(result, 'signature', 'certificate') if not isinstance(certificate, dict): return ['attestation has no signing certificate'] repo, commit = policy['repository'], policy['commit'] findings = [] if certificate.get('sourceRepositoryURI') != f'https://github.com/{repo}': findings.append('attested source repository differs from policy repository') if certificate.get('sourceRepositoryDigest') != commit: findings.append('attested commit SHA differs from checkout commit') if certificate.get('sourceRepositoryRef') != TRUSTED_REF: findings.append(f'attested source ref is not {TRUSTED_REF} (PR head, fork or other branch)') if certificate.get('buildSignerURI') != f"https://github.com/{repo}/{policy['signer_workflow']}@{TRUSTED_REF}": findings.append('signing workflow identity differs from policy') if certificate.get('buildSignerDigest') != commit: findings.append('signing workflow file is not the one at the checkout commit') triggers = [certificate[key] for key in ('githubWorkflowTrigger', 'buildTrigger') if key in certificate] if not triggers or any(trigger not in TRUSTED_TRIGGERS for trigger in triggers): findings.append(f'producer trigger {triggers!r} is not a trusted push or workflow_dispatch') if certificate.get('runnerEnvironment') != 'github-hosted': findings.append('producer did not run on a GitHub-hosted runner') return findings def run_findings(result, run, policy): """runInvocationURI must name the supplied workflow-run attempt, and that run must be main's signing workflow.""" repo, commit = policy['repository'], policy['commit'] uri = _get(result, 'signature', 'certificate', 'runInvocationURI') match = re.fullmatch(rf'https://github\.com/{re.escape(repo)}/actions/runs/([0-9]+)/attempts/([0-9]+)', str(uri)) if not match: return [f'runInvocationURI {uri!r} is not a workflow run of {repo}'] findings = [] if str(run.get('id')) != match[1] or str(run.get('run_attempt')) != match[2]: findings.append('runInvocationURI does not name the supplied workflow run attempt') if run.get('head_sha') != commit: findings.append('workflow run head_sha differs from checkout commit') if run.get('head_branch') != TRUSTED_REF.removeprefix('refs/heads/'): findings.append('workflow run did not run on main') if run.get('event') not in TRUSTED_TRIGGERS: findings.append(f"workflow run event {run.get('event')!r} is not push or workflow_dispatch") if run.get('path') != policy['signer_workflow']: findings.append('workflow run is not the signing workflow') if _get(run, 'repository', 'full_name') != repo or _get(run, 'head_repository', 'full_name') != repo: findings.append('workflow run belongs to another repository or a fork') return findings def verify(artifact_bytes, attestation, policy, rom_bytes=None, run=None, fixture=None): """Return {'result', 'reasons', 'trust', 'compatibility'} for the artifact and the injected gh outputs. policy: {'repository', 'commit' (checkout SHA), 'signer_workflow', 'geargrafx_revision', 'geargrafx_sha256', 'denied_sha256' (optional set)} attestation: parsed `gh attestation verify --format json`, or None for a local run. run: parsed `gh api repos/R/actions/runs/ID/attempts/N`. fixture: recomputed {'bin_sha256', 'cue_sha256'}. """ def out(result, reasons, trust): return {'result': result, 'reasons': reasons, 'trust': trust, 'compatibility': NOT_PROMOTED} try: artifact = json.loads(artifact_bytes.decode('utf-8')) except (UnicodeDecodeError, ValueError, RecursionError) as error: # ValueError covers JSONDecodeError return out(FAIL, [f'artifact is not JSON: {error}'], LOCAL_TRUST) errors = artifact_findings(artifact, policy, rom_bytes, fixture) if errors: return out(FAIL, errors, LOCAL_TRUST) if attestation is None: return out(LOCAL_ONLY, ['no attestation supplied'], LOCAL_TRUST) results = _statements(attestation) missing = [label for label, value in (('gh attestation verification array', results), ('ROM file', rom_bytes), ('recomputed fixture hashes', fixture), ('workflow run record', run)) if value is None or (label == 'workflow run record' and not isinstance(value, dict))] if missing: return out(BLOCKED, [f"missing or unusable: {', '.join(missing)}"], 'attestation required; not verifiable') wanted = {hashlib.sha256(artifact_bytes).hexdigest(), hashlib.sha256(rom_bytes).hexdigest()} matched = [result for result in results if wanted <= _subject_digests(result)] if not matched: return out(FAIL, ['no verified attestation has both this artifact and the ROM as subjects ' '(forged, tampered, or another artifact)'], 'attestation present; subject mismatch') findings = [certificate_findings(result, policy) + run_findings(result, run, policy) for result in matched] if any(not finding for finding in findings): return out(PASS, [], f"attested by {TRUSTED_REF} {policy['signer_workflow']} at {policy['commit']} " f"(run {run.get('id')}); main is NOT branch-protected unless the repository says so") return out(FAIL, findings[0], 'attestation present; producer not trusted') def recompute_fixture(): """Regenerate the synthetic CD fixture with this checkout's generator and hash the files on disk.""" from make_cd_image import BIN_NAME, CUE_NAME, build_image with tempfile.TemporaryDirectory(prefix='provenance-fixture-') as tmp: build_image(Path(tmp)) return {key: hashlib.sha256((Path(tmp) / name).read_bytes()).hexdigest() for key, name in (('bin_sha256', BIN_NAME), ('cue_sha256', CUE_NAME))} def _load_json(path): try: with open(path, encoding='utf-8') as handle: return json.load(handle) except (OSError, ValueError, RecursionError): return None def main(argv): parser = argparse.ArgumentParser(description='Verify a Geargrafx evidence artifact against gh attestation output.') parser.add_argument('artifact') parser.add_argument('--repo', required=True, help='owner/repo expected to have produced the artifact') parser.add_argument('--commit', required=True, help='40-hex checkout commit (git rev-parse HEAD)') parser.add_argument('--deps', default='tools/dependencies.json', help='pinned dependencies at the checkout') parser.add_argument('--attestation', help='saved output of gh attestation verify --format json') parser.add_argument('--run', help='saved output of gh api repos/R/actions/runs/ID/attempts/N') parser.add_argument('--rom', help='probe ROM file; its sha256 is recomputed and must be an attested subject') parser.add_argument('--root', default=str(ROOT), help='checkout whose provenance/denylist.sha256 is enforced') args = parser.parse_args(argv[1:]) if not HEX40.fullmatch(args.commit) or not REPO.fullmatch(args.repo): print('refused: --commit must be a 40-hex SHA and --repo owner/repo', file=sys.stderr) return 2 with open(args.deps, encoding='utf-8') as handle: geargrafx = json.load(handle)['geargrafx'] with open(args.artifact, 'rb') as handle: artifact_bytes = handle.read() try: rom_bytes = Path(args.rom).read_bytes() if args.rom else None except OSError: rom_bytes = None # unreadable ROM -> BLOCKED attestation = _load_json(args.attestation) if args.attestation else None if args.attestation and attestation is None: attestation = [] # unreadable gh output -> BLOCKED, never LOCAL_ONLY run = _load_json(args.run) if args.run else None policy = {'repository': args.repo, 'commit': args.commit, 'signer_workflow': SIGNER_WORKFLOW, 'geargrafx_revision': geargrafx['revision'], 'geargrafx_sha256': geargrafx['sha256'], 'denied_sha256': load_denylist(Path(args.root))} result = verify(artifact_bytes, attestation, policy, rom_bytes, run, recompute_fixture()) print(json.dumps(result, indent=2)) return 0 if result['result'] == PASS else 1 if __name__ == '__main__': raise SystemExit(main(sys.argv))