TExcelTAD
Home › Python Packaging: pip, venv, Poetry & uv › TestPyPI & Trusted Publishing

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.

bash
# 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.0

The --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.dev1 or 0.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:

  1. 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, workflow release.yml, environment pypi. GitLab CI/CD, Google Cloud and ActiveState are supported too.
  2. When that workflow runs, GitHub issues it an OIDC identity token signed by GitHub, stating which repository, workflow, ref and environment it is.
  3. 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.
  4. The tool uploads with it. There is no secret to store or rotate.

A release workflow with GitHub Actions (non-run):

yaml
# .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 always

Design 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-publish also 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 publish and poetry publish detect trusted-publishing environments as well (uv: --trusted-publishing automatic is 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:

python · try it yourself
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?

  1. A stored API token
  2. A short-lived OIDC identity token from the CI provider, which PyPI exchanges for a ~15-minute upload token
  3. The maintainer's password
  4. An SSH key

Why is pip install --extra-index-url https://test.pypi.org/simple/ … risky outside experiments?

  1. It's slow
  2. pip picks the best version across all indexes, so a same-named package on the other index can win (dependency confusion)
  3. TestPyPI is read-only
  4. It disables hashes

In the workflow, why does only the publish job get id-token: write?

  1. GitHub requires it
  2. To keep the job that runs project code and build backends away from the ability to mint publishing credentials
  3. To make builds faster
  4. It doesn't matter