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