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