Debian Codegraph @

utils/convert_attestations.py

raw
1 """Convert Sigstore attestations to PEP 740.
2
3 See https://github.com/trailofbits/pypi-attestations.
4 """
5
6 # /// script
7 # requires-python = ">=3.12"
8 # dependencies = [
9 # "pypi-attestations==0.0.28",
10 # ]
11 # ///
12
13 from __future__ import annotations
14
15 import json
16 import sys
17 from base64 import b64decode
18 from pathlib import Path
19
20 from pypi_attestations import Attestation, Distribution
21 from sigstore.models import Bundle
22 from sigstore.verify.policy import Identity
23
24 ROOT = Path(__file__).resolve().parent.parent
25 DIST = ROOT / 'dist'
26 bundle_path = Path(sys.argv[1])
27 signer_identity = sys.argv[2]
28
29 for line in bundle_path.read_bytes().splitlines():
30 dsse_envelope_payload = json.loads(line)['dsseEnvelope']['payload']
31 subjects = json.loads(b64decode(dsse_envelope_payload))['subject']
32 for subject in subjects:
33 filename = subject['name']
34 assert (DIST / filename).is_file()
35
36 # Convert attestation from Sigstore to PEP 740
37 print(f'Converting attestation for {filename}')
38 sigstore_bundle = Bundle.from_json(line)
39 attestation = Attestation.from_bundle(sigstore_bundle)
40 attestation_path = DIST / f'{filename}.publish.attestation'
41 attestation_path.write_text(attestation.model_dump_json())
42 print(f'Attestation for {filename} written to {attestation_path}')
43 print()
44
45 # Validate attestation
46 dist = Distribution.from_file(DIST / filename)
47 attestation = Attestation.model_validate_json(attestation_path.read_bytes())
48 identity = Identity(identity=signer_identity)
49 attestation.verify(identity=identity, dist=dist)
50 print(f'Verified {attestation_path}')