TestPyPI & Trusted Publishing
Two habits separate a careful release process from an anxious one: rehearse on TestPyPI, and publish from CI without long-lived secrets using trusted publishing. Neither can run in this course's offline container, so this lesson shows the configuration as non-run blocks and models the trust check in Python.
TestPyPI: a rehearsal index
TestPyPI is a separate instance of PyPI for experiments: separate accounts, separate tokens, and it's wiped occasionally. Use it for your first upload of a new project, after changing the build configuration, or to test a release workflow.
# upload
twine upload -r testpypi dist/* # with a [testpypi] section in ~/.pypirc
uv publish --publish-url https://test.pypi.org/legacy/ --token "$TEST_PYPI_TOKEN"
poetry config repositories.testpypi https://test.pypi.org/legacy/ && poetry publish -r testpypi
# install what you uploaded, in a fresh environment
python -m venv /tmp/try && /tmp/try/bin/pip install \
--index-url https://test.pypi.org/simple/ \
--extra-index-url https://pypi.org/simple/ \
tadcalc==0.2.0The --extra-index-url is needed because your package's dependencies usually aren't on TestPyPI. Use it only for this kind of experiment: with two indexes pip takes whichever has the best version, so anyone can upload a same-named package to TestPyPI and win ("dependency confusion"). uv's default, taking a package from the first index that has it, exists precisely to prevent that.
Note: A version number is burned on TestPyPI too. Rehearse with throwaway versions such as
0.2.0.dev1or0.2.0rc1.
Trusted publishing
The classic CI setup stores a PyPI API token as a repository secret. It never expires, it can leak through logs or a compromised workflow, and whoever holds it can publish anywhere its scope allows. Trusted publishing replaces it with short-lived credentials based on OpenID Connect:
- On PyPI, in the project's settings (or as a "pending publisher" for a project that doesn't exist yet), you register a trusted publisher: GitHub repository
ada/tadcalc, workflowrelease.yml, environmentpypi. GitLab CI/CD, Google Cloud and ActiveState are supported too. - When that workflow runs, GitHub issues it an OIDC identity token signed by GitHub, stating which repository, workflow, ref and environment it is.
- The upload tool sends that token to PyPI, which checks the signature and compares the claims with the registered publisher. If they match, PyPI returns an API token valid for about 15 minutes and scoped to that one project.
- The tool uploads with it. There is no secret to store or rotate.
A release workflow with GitHub Actions (non-run):
# .github/workflows/release.yml
name: release
on:
push:
tags: ["v*"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: astral-sh/setup-uv@v6
- run: uv build # sdist + wheel into dist/
- run: uvx twine check dist/*
- uses: actions/upload-artifact@v4
with: { name: dist, path: dist/ }
publish:
needs: build
runs-on: ubuntu-latest
environment: pypi # must match the trusted publisher on PyPI
permissions:
id-token: write # lets the job request an OIDC token
steps:
- uses: actions/download-artifact@v4
with: { name: dist, path: dist/ }
- uses: pypa/gh-action-pypi-publish@release/v1
# or: - uses: astral-sh/setup-uv@v6
# - run: uv publish --trusted-publishing alwaysDesign points:
- Build and publish are separate jobs. Only the small publish job gets
id-token: write; the build job, which runs your project's code and build backend, never sees credentials. - A GitHub environment (
pypi) can require a manual approval and restrict which branches or tags may deploy. pypa/gh-action-pypi-publishalso generates and uploads attestations (PEP 740): signed statements linking each file to the workflow run that built it, shown on PyPI as provenance. The supply-chain security course goes deeper.uv publishandpoetry publishdetect trusted-publishing environments as well (uv:--trusted-publishing automaticis the default on GitHub Actions).
A runnable model: matching OIDC claims
The core of trusted publishing is a comparison between the claims in a (signature-checked) token and the publisher configuration registered for the project. This model skips the cryptography and shows the matching rules and the short-lived token:
publishers = {
"tadcalc": {"repository": "ada/tadcalc", "workflow": "release.yml", "environment": "pypi"},
}
def exchange(project, claims, now):
pub = publishers.get(project)
if pub is None:
return "403: no trusted publisher for this project"
if claims["repository"] != pub["repository"]:
return f"403: repository {claims['repository']} is not trusted"
workflow = claims["job_workflow_ref"].split("@")[0].rsplit("/", 1)[-1]
if workflow != pub["workflow"]:
return f"403: workflow {workflow} is not trusted"
if pub["environment"] and claims.get("environment") != pub["environment"]:
return f"403: environment {claims.get('environment')!r} is not trusted"
return f"200: token for {project!r}, expires at t={now + 900}"
good = {"repository": "ada/tadcalc",
"job_workflow_ref": "ada/tadcalc/.github/workflows/release.yml@refs/tags/v0.2.0",
"environment": "pypi"}
print(exchange("tadcalc", good, now=1000))
print(exchange("tadcalc", {**good, "repository": "mallory/tadcalc"}, now=1000))
print(exchange("tadcalc", {**good, "job_workflow_ref": "ada/tadcalc/.github/workflows/test.yml@refs/heads/main"}, now=1000))
print(exchange("tadcalc", {k: v for k, v in good.items() if k != "environment"}, now=1000))
print(exchange("otherpkg", good, now=1000))200: token for 'tadcalc', expires at t=1900
403: repository mallory/tadcalc is not trusted
403: workflow test.yml is not trusted
403: environment None is not trusted
403: no trusted publisher for this project
A fork, a different workflow in the same repository, or a job outside the protected environment all fail; and even a successful token is useless 15 minutes later and for any other project.
Test yourself
What does a CI job send to PyPI in trusted publishing?
- A stored API token
- A short-lived OIDC identity token from the CI provider, which PyPI exchanges for a ~15-minute upload token
- The maintainer's password
- An SSH key
Why is pip install --extra-index-url https://test.pypi.org/simple/ … risky outside experiments?
- It's slow
- pip picks the best version across all indexes, so a same-named package on the other index can win (dependency confusion)
- TestPyPI is read-only
- It disables hashes
In the workflow, why does only the publish job get id-token: write?
- GitHub requires it
- To keep the job that runs project code and build backends away from the ability to mint publishing credentials
- To make builds faster
- It doesn't matter