Skip to content

Commit 19c22db

Browse files
Merge pull request #3 from Infinitode/arena/b2a526eb-localsitemap
Release 2.1.0: bug fixes, CLI, and Trusted Publishing with provenance
2 parents 362397b + f15fc99 commit 19c22db

15 files changed

Lines changed: 1864 additions & 378 deletions
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
#!/usr/bin/env python3
2+
"""Verify that every file of a PyPI release carries PEP 740 provenance.
3+
4+
The script talks to the public PyPI Integrity API:
5+
6+
https://pypi.org/integrity/{project}/{version}/{filename}/provenance
7+
8+
For each distribution file of the given release it checks that at least one
9+
attestation bundle is present and prints the trusted publisher identity the
10+
attestations are bound to. This is what makes the "provenance" indicator on
11+
the PyPI project page show up, so the release workflow runs it after every
12+
upload.
13+
14+
Exit codes:
15+
0 - every file is attested (or --allow-missing was given)
16+
1 - at least one file has no provenance
17+
2 - the release could not be queried at all
18+
19+
Usage:
20+
python .github/scripts/verify_provenance.py --project localsitemap --version 2.1.0
21+
"""
22+
23+
import argparse
24+
import json
25+
import sys
26+
import time
27+
import urllib.error
28+
import urllib.request
29+
30+
PYPI_JSON = "https://pypi.org/pypi/{project}/{version}/json"
31+
PYPI_INTEGRITY = "https://pypi.org/integrity/{project}/{version}/{filename}/provenance"
32+
USER_AGENT = "localsitemap-release-check/1.0"
33+
34+
35+
def _get_json(url, timeout=30):
36+
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
37+
with urllib.request.urlopen(request, timeout=timeout) as response:
38+
return json.loads(response.read().decode("utf-8"))
39+
40+
41+
def _release_files(project, version):
42+
data = _get_json(PYPI_JSON.format(project=project, version=version))
43+
return [item["filename"] for item in data.get("urls", [])]
44+
45+
46+
def _provenance(project, version, filename):
47+
url = PYPI_INTEGRITY.format(project=project, version=version, filename=filename)
48+
try:
49+
return _get_json(url)
50+
except urllib.error.HTTPError as error:
51+
if error.code == 404:
52+
return None
53+
raise
54+
55+
56+
def _describe(bundles):
57+
descriptions = []
58+
for bundle in bundles:
59+
publisher = bundle.get("publisher") or {}
60+
parts = [
61+
str(publisher.get("kind", "unknown")),
62+
str(publisher.get("repository", "")),
63+
str(publisher.get("workflow", "")),
64+
]
65+
environment = publisher.get("environment")
66+
if environment:
67+
parts.append("env=%s" % environment)
68+
descriptions.append(" ".join(part for part in parts if part))
69+
return "; ".join(descriptions)
70+
71+
72+
def main(argv=None):
73+
parser = argparse.ArgumentParser(description=__doc__)
74+
parser.add_argument("--project", default="localsitemap")
75+
parser.add_argument("--version", required=True)
76+
parser.add_argument(
77+
"--allow-missing",
78+
action="store_true",
79+
help="do not fail when a file has no provenance",
80+
)
81+
parser.add_argument(
82+
"--attempts", type=int, default=5,
83+
help="how many times to retry while PyPI propagates a new release",
84+
)
85+
parser.add_argument("--delay", type=float, default=6.0, help="seconds between retries")
86+
args = parser.parse_args(argv)
87+
88+
filenames = []
89+
for attempt in range(1, max(1, args.attempts) + 1):
90+
try:
91+
filenames = _release_files(args.project, args.version)
92+
if filenames:
93+
break
94+
except (urllib.error.URLError, ValueError) as error:
95+
print("could not query PyPI (%s), attempt %d" % (error, attempt))
96+
if attempt < args.attempts:
97+
time.sleep(args.delay)
98+
99+
if not filenames:
100+
print(
101+
"error: no files found for %s %s on PyPI" % (args.project, args.version),
102+
file=sys.stderr,
103+
)
104+
return 2
105+
106+
missing = []
107+
for filename in filenames:
108+
data = None
109+
for attempt in range(1, max(1, args.attempts) + 1):
110+
try:
111+
data = _provenance(args.project, args.version, filename)
112+
if data:
113+
break
114+
except (urllib.error.URLError, ValueError) as error:
115+
print(" %s: query failed (%s), attempt %d" % (filename, error, attempt))
116+
if attempt < args.attempts:
117+
time.sleep(args.delay)
118+
119+
bundles = (data or {}).get("attestation_bundles") or []
120+
if bundles:
121+
print("OK %s -> %s" % (filename, _describe(bundles)))
122+
else:
123+
print("MISS %s has no provenance on PyPI" % filename)
124+
missing.append(filename)
125+
126+
if missing:
127+
if args.allow_missing:
128+
print("warning: %d file(s) without provenance" % len(missing))
129+
return 0
130+
print(
131+
"error: %d file(s) were published without provenance: %s"
132+
% (len(missing), ", ".join(missing)),
133+
file=sys.stderr,
134+
)
135+
return 1
136+
137+
print("All %d file(s) are attested with verifiable provenance." % len(filenames))
138+
return 0
139+
140+
141+
if __name__ == "__main__":
142+
sys.exit(main())
Lines changed: 133 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,142 @@
11
name: Publish Python 🐍 distributions 📦 to PyPI
22

3+
# Publishing uses PyPI Trusted Publishing (OIDC) - no API token is stored in
4+
# this repository. The publisher configured on PyPI must match:
5+
# owner/repository : Infinitode/LocalSiteMap
6+
# workflow : build_and_publish.yml
7+
# environment : (left blank - therefore no `environment:` key below)
8+
#
9+
# Every upload is signed with PEP 740 attestations, which is what powers the
10+
# "provenance" indicator on the PyPI project page.
11+
312
on:
413
push:
514
tags:
6-
- '*'
15+
- 'v[0-9]*'
16+
- '[0-9]*'
17+
workflow_dispatch:
18+
19+
permissions:
20+
contents: read
721

822
jobs:
9-
build-n-publish:
10-
name: Build and publish Python 🐍 distributions 📦 to PyPI
23+
build:
24+
name: Build distribution 📦
25+
runs-on: ubuntu-latest
26+
outputs:
27+
version: ${{ steps.version.outputs.version }}
28+
steps:
29+
- name: Check out the repository
30+
uses: actions/checkout@v4
31+
32+
- name: Set up Python 3.12
33+
uses: actions/setup-python@v5
34+
with:
35+
python-version: '3.12'
36+
37+
- name: Install build tooling
38+
run: >-
39+
python -m pip install --upgrade
40+
build
41+
twine
42+
setuptools
43+
wheel
44+
45+
- name: Run the test suite
46+
run: python -m unittest -v test_localsitemap
47+
48+
- name: Determine the release version
49+
id: version
50+
run: |
51+
set -euo pipefail
52+
if [[ "${GITHUB_REF}" == refs/tags/* ]]; then
53+
VERSION="${GITHUB_REF_NAME#v}"
54+
else
55+
VERSION="$(python -c 'from localsitemap._version import __version__; print(__version__)')"
56+
fi
57+
python - "${VERSION}" <<'PY'
58+
import pathlib
59+
import re
60+
import sys
61+
62+
version = sys.argv[1].strip()
63+
pattern = r"^[0-9]+(\.[0-9]+)*((a|b|rc)[0-9]+)?(\.post[0-9]+)?(\.dev[0-9]+)?$"
64+
if not re.match(pattern, version):
65+
sys.exit("Invalid release version: %r" % version)
66+
67+
target = pathlib.Path("localsitemap/_version.py")
68+
target.write_text(
69+
'"""Single source of truth for the LocalSiteMap version.\n\n'
70+
"The release workflow rewrites this file from the pushed git tag, so the\n"
71+
'version published to PyPI always matches the tag.\n"""\n\n'
72+
'__version__ = "%s"\n' % version,
73+
encoding="utf-8",
74+
)
75+
print("Building version", version)
76+
PY
77+
echo "version=${VERSION}" >> "${GITHUB_OUTPUT}"
78+
79+
- name: Build sdist and wheel
80+
run: python -m build
81+
82+
- name: Check the distribution metadata
83+
run: python -m twine check --strict dist/*
84+
85+
- name: Upload the distribution artifacts
86+
uses: actions/upload-artifact@v4
87+
with:
88+
name: python-package-distributions
89+
path: dist/
90+
if-no-files-found: error
91+
92+
publish:
93+
name: Publish distribution 📦 to PyPI
94+
needs: build
95+
# Only real tag pushes publish. A manual "Run workflow" therefore builds,
96+
# tests and validates the distributions without touching PyPI, which also
97+
# makes it safe to run before Trusted Publishing is configured.
98+
if: startsWith(github.ref, 'refs/tags/')
99+
runs-on: ubuntu-latest
100+
# NOTE: intentionally no `environment:` key. The PyPI trusted publisher is
101+
# configured with a blank environment name, and adding one here would make
102+
# the OIDC token claim mismatch and the upload fail.
103+
permissions:
104+
id-token: write # required for Trusted Publishing and attestations
105+
steps:
106+
- name: Download the distribution artifacts
107+
uses: actions/download-artifact@v4
108+
with:
109+
name: python-package-distributions
110+
path: dist/
111+
112+
- name: Publish distribution 📦 to PyPI
113+
uses: pypa/gh-action-pypi-publish@release/v1
114+
with:
115+
attestations: true
116+
print-hash: true
117+
118+
verify-provenance:
119+
name: Verify published provenance 🛡️
120+
needs:
121+
- build
122+
- publish
123+
if: startsWith(github.ref, 'refs/tags/')
11124
runs-on: ubuntu-latest
125+
permissions:
126+
contents: read
12127
steps:
13-
- uses: actions/checkout@master
14-
- name: Set up Python 3.12
15-
uses: actions/setup-python@v3
16-
with:
17-
python-version: '3.12'
18-
- name: Install pypa/setuptools
19-
run: >-
20-
python -m
21-
pip install setuptools wheel
22-
- name: Extract tag name
23-
id: tag
24-
run: echo ::set-output name=TAG_NAME::$(echo $GITHUB_REF | cut -d / -f 3)
25-
- name: Update version in setup.py
26-
run: >-
27-
sed -i "s/{{VERSION_PLACEHOLDER}}/${{ steps.tag.outputs.TAG_NAME }}/g" setup.py
28-
- name: Build a binary wheel
29-
run: >-
30-
python setup.py sdist bdist_wheel
31-
- name: Publish distribution 📦 to PyPI
32-
uses: pypa/gh-action-pypi-publish@master
33-
with:
34-
password: ${{ secrets.PYPI_API_TOKEN }}
128+
- name: Check out the repository
129+
uses: actions/checkout@v4
130+
131+
- name: Set up Python 3.12
132+
uses: actions/setup-python@v5
133+
with:
134+
python-version: '3.12'
135+
136+
- name: Confirm every published file carries provenance
137+
env:
138+
VERSION: ${{ needs.build.outputs.version }}
139+
run: >-
140+
python .github/scripts/verify_provenance.py
141+
--project localsitemap
142+
--version "${VERSION}"

0 commit comments

Comments
 (0)