|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | +from typing import NoReturn |
| 6 | + |
| 7 | +from pypi_attestations import Attestation, Distribution |
| 8 | +from sigstore.oidc import IdentityError, IdentityToken, detect_credential |
| 9 | +from sigstore.sign import Signer, SigningContext |
| 10 | + |
| 11 | +# Be very verbose. |
| 12 | +sigstore_logger = logging.getLogger('sigstore') |
| 13 | +sigstore_logger.setLevel(logging.DEBUG) |
| 14 | +sigstore_logger.addHandler(logging.StreamHandler()) |
| 15 | + |
| 16 | +_GITHUB_STEP_SUMMARY = Path(os.getenv('GITHUB_STEP_SUMMARY')) |
| 17 | + |
| 18 | +# The top-level error message that gets rendered. |
| 19 | +# This message wraps one of the other templates/messages defined below. |
| 20 | +_ERROR_SUMMARY_MESSAGE = """ |
| 21 | +Attestation generation failure: |
| 22 | +
|
| 23 | +{message} |
| 24 | +
|
| 25 | +You're seeing this because the action attempted to generated PEP 740 |
| 26 | +attestations for its inputs, but failed to do so. |
| 27 | +""" |
| 28 | + |
| 29 | +# Rendered if OIDC identity token retrieval fails for any reason. |
| 30 | +_TOKEN_RETRIEVAL_FAILED_MESSAGE = """ |
| 31 | +OpenID Connect token retrieval failed: {identity_error} |
| 32 | +
|
| 33 | +This failure occurred after a successful Trusted Publishing Flow, |
| 34 | +suggesting a transient error. |
| 35 | +""" # noqa: S105; not a password |
| 36 | + |
| 37 | + |
| 38 | +def die(msg: str) -> NoReturn: |
| 39 | + with _GITHUB_STEP_SUMMARY.open('a', encoding='utf-8') as io: |
| 40 | + print(_ERROR_SUMMARY_MESSAGE.format(message=msg), file=io) |
| 41 | + |
| 42 | + # HACK: GitHub Actions' annotations don't work across multiple lines naively; |
| 43 | + # translating `\n` into `%0A` (i.e., HTML percent-encoding) is known to work. |
| 44 | + # See: https://github.com/actions/toolkit/issues/193 |
| 45 | + msg = msg.replace('\n', '%0A') |
| 46 | + print(f'::error::Attestation generation failure: {msg}', file=sys.stderr) |
| 47 | + sys.exit(1) |
| 48 | + |
| 49 | + |
| 50 | +def debug(msg: str): |
| 51 | + print(f'::debug::{msg}', file=sys.stderr) |
| 52 | + |
| 53 | + |
| 54 | +def collect_dists(packages_dir: Path) -> list[Path]: |
| 55 | + # Collect all sdists and wheels. |
| 56 | + dist_paths = [sdist.resolve() for sdist in packages_dir.glob('*.tar.gz')] |
| 57 | + dist_paths.extend(whl.resolve() for whl in packages_dir.glob('*.whl')) |
| 58 | + |
| 59 | + # Make sure everything that looks like a dist actually is one. |
| 60 | + # We do this up-front to prevent partial signing. |
| 61 | + if (invalid_dists := [path for path in dist_paths if path.is_file()]): |
| 62 | + invalid_dist_list = ', '.join(map(str, invalid_dists)) |
| 63 | + die( |
| 64 | + 'The following paths look like distributions but ' |
| 65 | + f'are not actually files: {invalid_dist_list}', |
| 66 | + ) |
| 67 | + |
| 68 | + return dist_paths |
| 69 | + |
| 70 | + |
| 71 | +def attest_dist(dist_path: Path, signer: Signer) -> None: |
| 72 | + # We are the publishing step, so there should be no pre-existing publish |
| 73 | + # attestation. The presence of one indicates user confusion. |
| 74 | + attestation_path = Path(f'{dist_path}.publish.attestation') |
| 75 | + if attestation_path.exists(): |
| 76 | + die(f'{dist_path} already has a publish attestation: {attestation_path}') |
| 77 | + |
| 78 | + dist = Distribution.from_file(dist_path) |
| 79 | + attestation = Attestation.sign(signer, dist) |
| 80 | + |
| 81 | + attestation_path.write_text(attestation.model_dump_json(), encoding='utf-8') |
| 82 | + debug(f'saved publish attestation: {dist_path=} {attestation_path=}') |
| 83 | + |
| 84 | + |
| 85 | +def get_identity_token() -> IdentityToken: |
| 86 | + # Will raise `sigstore.oidc.IdentityError` if it fails to get the token |
| 87 | + # from the environment or if the token is malformed. |
| 88 | + # NOTE: audience is always sigstore. |
| 89 | + oidc_token = detect_credential() |
| 90 | + return IdentityToken(oidc_token) |
| 91 | + |
| 92 | + |
| 93 | +def main() -> None: |
| 94 | + packages_dir = Path(sys.argv[1]) |
| 95 | + |
| 96 | + try: |
| 97 | + identity = get_identity_token() |
| 98 | + except IdentityError as identity_error: |
| 99 | + # NOTE: We only perform attestations in trusted publishing flows, so we |
| 100 | + # don't need to re-check for the "PR from fork" error mode, only |
| 101 | + # generic token retrieval errors. We also render a simpler error, |
| 102 | + # since permissions can't be to blame at this stage. |
| 103 | + die(_TOKEN_RETRIEVAL_FAILED_MESSAGE.format(identity_error=identity_error)) |
| 104 | + |
| 105 | + dist_paths = collect_dists(packages_dir) |
| 106 | + |
| 107 | + with SigningContext.production().signer(identity, cache=True) as s: |
| 108 | + debug(f'attesting to dists: {dist_paths}') |
| 109 | + for dist_path in dist_paths: |
| 110 | + attest_dist(dist_path, s) |
| 111 | + |
| 112 | + |
| 113 | +if __name__ == '__main__': |
| 114 | + main() |
0 commit comments