Whoever can upload to your PyPI project can run code on every machine that installs it, so a PyPI API token or a loosely configured Trusted Publisher is a software supply chain credential, not a convenience setting. Python packages have repeatedly been poisoned through stolen or forgotten upload tokens and through release workflows that trusted the wrong input. This guide explains how authentication and roles work on PyPI, how classic API tokens differ from Trusted Publishing, how to lock down the GitHub Actions, GitLab CI/CD and Google Cloud publishers PyPI supports, what attestations add, and how to detect and respond to a leaked token. It is written for maintainers, release engineers and platform teams who publish Python packages, whether as open source projects or from an organisation account. It complements the npm Tokens Security Guide and the Package Registry Security Comparison Guide, which compare registries rather than going deep on PyPI.
This is an independent guide from NHI Mgmt Group, based on PyPI's public documentation as of November 2026. It is not sponsored or reviewed by PyPI. Product features change, so confirm settings against PyPI's current documentation.
Key takeaways
- Trusted Publishing is PyPI's recommended upload method. A CI job exchanges an OIDC token for a project-scoped PyPI token that expires no more than 15 minutes later, so there is no stored secret to leak.
- A Trusted Publisher is a credential in disguise. PyPI's own security model says to treat it as if it were an API token: anyone who can change or trigger the trusted workflow can publish.
- Old tokens outlive migrations. Moving to Trusted Publishing does nothing until you revoke every account-wide and project token that can still upload.
- Scope what remains. Where a token is unavoidable, scope it to one project, store it as a CI secret in a protected environment and never use an account-wide token in automation.
- Attestations prove where a file came from. PEP 740 attestations, generated by default by the PyPA publish action under Trusted Publishing, bind each wheel and sdist to the workflow identity that published it.
How identity and access work in PyPI
PyPI has three layers of identity: the human account, the project collaborator role and, optionally, an organisation account. Since early 2024 two-factor authentication has been mandatory for every account. Before enabling 2FA a user must generate and verify recovery codes; PyPI supports WebAuthn security devices and one TOTP application per account, and its documentation prefers a security device because it resists phishing. PyPI also asks users to re-confirm their password before sensitive actions such as generating API tokens or adding and removing maintainers, if more than 30 minutes have passed since the last confirmation.
Uploads, however, are not made with the account password and 2FA. They use one of two machine credentials:
| Property | Classic API token | Trusted Publishing |
|---|---|---|
| What it is | A macaroon serialised as pypi- followed by a base64 string of at least 85 characters | An OIDC trust relationship between a project and a CI identity |
| Scope | Entire account (all projects) or one project | One project; the minted token behaves like a project-scoped token |
| Lifetime | Long-lived until revoked | Minted token valid no more than 15 minutes |
| Where the secret lives | CI secret store, .pypirc, developer machines | Nowhere: the job requests it at run time |
| Used as | Username __token__, password the full token including pypi- | Handled by pypa/gh-action-pypi-publish or twine |
| Bound to | The account that created it and that account's project roles | The project: publishers are registered to projects, not users, so they survive maintainer removal |
| Main risk | Theft from CI, images, logs or laptops | Abuse of the trusted workflow or repository |
| Supports attestations | No | Yes (GitHub Actions, GitLab CI/CD, Google Cloud, ActiveState) |
The OIDC exchange works like this: the CI provider issues a signed identity token describing the repository, workflow and environment; the job submits it to PyPI; PyPI verifies the signature, matches the claims against every Trusted Publisher configured on PyPI and, if one matches, returns a short-lived API token for that project. For GitHub, PyPI checks the immutable repository_owner_id claim as well as the owner name, which defeats "account resurrection", where an attacker re-registers a deleted or renamed GitHub username. The general pattern is covered in the Workload Identity Federation Guide.
Admin roles and privileged access
| Level | Role | Can do | Control to apply |
|---|---|---|---|
| Project | Owner | Upload, add or remove owners and maintainers, delete files, releases or the project, configure Trusted Publishers | At least two owners with security keys; no more than needed |
| Project | Maintainer | Upload releases only | Default role for people who release |
| Organisation | Owner | Manage members, roles, team permissions, projects and billing; delete the organisation | Treat as privileged access; review quarterly |
| Organisation | Manager | Manage teams and team permissions, manage and create projects | Limit to release leads |
| Organisation | Member | Manage projects it is granted through teams | Grant per team, not per person |
| Organisation | Billing manager | Billing, invoices and subscriptions only | No project rights |
- Owner is the real admin: PyPI warns that a new owner can remove you from the project. Granting ownership to a bot or a shared account is equivalent to handing over the project.
- Offboarding must cover publishers: removing a user does not remove the Trusted Publishers they registered, nor tokens scoped to the project that someone else created. Review both when a maintainer leaves.
- Account security is still upstream: an owner's account can add a new Trusted Publisher pointing at an attacker's repository, so phishing-resistant 2FA on owner accounts protects the publishing path too. See the Phishing-Resistant MFA Guide.
Integrations, API tokens and service accounts
Hardening a GitHub Actions publisher
PyPI's security model notes that any workflow in a repository can request an OIDC token if it has the id-token: write permission, and that the claims are bound to the workflow file name. That gives you these controls, in order of impact:
- Trust one workflow: register a single, minimal release workflow (PyPI suggests
release.yml) and not a general CI file. - Require an environment: name a GitHub environment such as
pypiin the publisher. PyPI calls this optional but strongly recommended, because environments support required reviewers, so a release needs a human approval. - Grant
id-token: writeper job: set it only on the publish job, never at workflow level. - Split build and publish: the publish job should only download artefacts from a separate build job and run
pypa/gh-action-pypi-publish, so build scripts and dependencies never see the OIDC token. - Avoid dangerous triggers:
pull_request_targetandissue_commentare forbidden triggers for PyPI Trusted Publishing; reusable workflows cannot currently be used as the trusted workflow. - Protect tags: if releases trigger on tags such as
v*, restrict who can create them.
Two failure modes deserve attention: a release workflow that runs on outside pull requests and expands untrusted input such as a branch name into a shell command, and a long-lived API token left over from before a project adopted Trusted Publishing. Stolen repository credentials can also approve a release through the project's own pipeline. Trusted Publishing moves the trust boundary to the repository, and the repository then needs the controls in the GitHub and GitHub Actions Security Guide.
GitLab CI/CD and Google Cloud publishers
- GitLab: OIDC claims are bound to the top-level pipeline (usually
.gitlab-ci.yml) and GitLab does not tell PyPI which job requested the token, so any job in that pipeline can mint a valid token. Use a protected environment with approvers and protected tags, and keep publish in its own job. PyPI also warns that if a GitLab namespace is deleted and recreated with the same name, tokens from the new namespace will still match. - Google Cloud: any service running as the configured service account can obtain a token, so never configure a default service account; optionally set the subject to restrict the identity further. See the Google Cloud IAM and Service Accounts Guide.
When a classic token is still needed
Some CI systems are not supported Trusted Publishing providers, and some internal mirrors or tools still upload with a token. In that case: create a project-scoped token (never account-wide) from a dedicated maintainer account, store it only in the CI platform's secret store bound to a protected environment, name it after the pipeline, and set a rotation date in your inventory, since PyPI tokens have no built-in expiry. The CI/CD Pipeline Identity Security Guide covers secret placement in pipelines.
Logging and detection
| Signal | Source | What it tells you |
|---|---|---|
pypi_api_token alert | GitHub secret scanning (partner pattern, push protection supported) | A token was committed; PyPI revokes tokens reported on public sites |
pypi-upload-token rule | Gitleaks default config (matches the pypi-AgEIcHlwaS5vcmc macaroon header) | Tokens in private repositories, images and logs, which public scanning never sees |
| Compromised token email | PyPI security alerts | A token was found publicly (GitHub and deps.dev report to PyPI) and has already been revoked |
| Security history | PyPI account settings | Token creation, 2FA changes, logins and other account events to review after any alert |
| Unexpected release | Your own release monitoring against the project's file list | A version that did not come from your tagged pipeline run |
| Missing or wrong attestation | PEP 740 attestations on uploaded files | A file not published by the expected Trusted Publisher identity |
The format is distinctive: PyPI documents tokens as pypi- followed by at least 85 base64 characters, and the string can be longer because caveats may be added to the macaroon. All users with tokens are opted in to PyPI's secret reporting by default. Pair public scanning with your own scanning of private code and build output; see the Git Secret Scanning Guide. Published packages can contain secrets too, so scan the built sdist and wheel, not just the repository.
Metrics that show it is working:
- Share of projects publishing only through Trusted Publishing (target 100% of supported CI).
- Number of live account-wide tokens (target zero) and project tokens older than their rotation date.
- Share of release files carrying attestations.
- Number of Trusted Publishers without a required environment.
- Time from token leak alert to revocation and re-issue.
Hardening baseline
- Inventory: for every project, list owners, maintainers, Trusted Publishers (provider, repository, workflow, environment) and API tokens (scope, creator, where stored). Most organisations find tokens they cannot explain.
- Secure the humans: confirm every owner uses a WebAuthn security key, keeps recovery codes offline and that each project has at least two owners.
- Add the Trusted Publisher in parallel: configure the publisher with an environment, publish a release (or a TestPyPI release first) and confirm it succeeds while the old token still exists.
- Harden the workflow: job-level
id-token: write, separate build job, required reviewers on the environment, protected tags, pinned actions. - Revoke old tokens: delete every token that can upload to the project, including account-wide tokens on owner accounts, and remove the matching CI secrets. Rollback is simple: a new project-scoped token can be issued if the publisher fails.
- Keep attestations on: the PyPA action generates them by default under Trusted Publishing; do not set
attestations: falsewithout a reason. - Review on change: re-check publishers and tokens whenever a maintainer leaves, a repository moves or a workflow is renamed (renaming a trusted workflow file breaks or shifts trust).
Single-maintainer projects get most of the benefit from steps 2, 3 and 5. Organisations should use a PyPI organisation account with team-based roles, require Trusted Publishing by policy, and monitor releases centrally.
Leak response
- Revoke the token in account settings straight away, even if PyPI says it already has.
- Review the account's security history and each project's release list for files you did not publish; yank or remove them and notify users if any exist.
- If a Trusted Publisher workflow was abused, remove the publisher, fix the workflow, then re-add it.
- Rotate CI secrets that shared the same runner or environment, and find how the token escaped (logs, images, artefacts).
- Record the incident in the CI/CD Pipeline Compromise Playbook format if a malicious release was published.
Framework mapping
| Control area | NIST SP 800-53 Rev 5 | NIST CSF 2.0 | ISO/IEC 27001:2022 Annex A | MITRE ATT&CK |
|---|---|---|---|---|
| Replace stored tokens with short-lived OIDC credentials | IA-5, IA-5(7) | PR.AA-01 | A.5.17 Authentication information | T1552.001 Credentials In Files |
| Owner and maintainer roles, publisher review | AC-2, AC-6 | PR.AA-05 | A.8.2 Privileged access rights | T1078 Valid Accounts |
| Release workflow integrity | SA-10 Developer Configuration Management | PR.PS-06 | A.8.25 Secure development life cycle | T1195.002 Compromise Software Supply Chain |
| Attestations and provenance | SR-4 Provenance, SR-11 Component Authenticity | GV.SC-07 | A.5.21 Managing information security in the ICT supply chain | T1195.002 |
| Token and release monitoring | SI-4, AU-6 | DE.CM-09 | A.8.16 Monitoring activities | T1528 Steal Application Access Token |
Common misconfigurations
- Token kept "just in case" after migration: exactly the Ultralytics pattern; a forgotten token is a second, unmonitored publishing path.
- Account-wide token in CI: one leaked secret can publish to every project the account owns.
- Publisher without an environment: anyone who can push to the repository can edit the workflow to add a
workflow_dispatchtrigger and publish without review. - Build and publish in one job: every build dependency and test script runs with access to the OIDC token.
- Trusting a fork or a repository you do not control: that repository can then upload to your project.
- Offboarding that forgets publishers: removing a maintainer leaves the publishers they registered in place.
Practitioner checklist
- Enable Trusted Publishing for every project built on GitHub Actions, GitLab CI/CD, Google Cloud or ActiveState.
- Require a named environment with required reviewers on every GitHub or GitLab publisher.
- Set
id-token: writeonly on the publish job and keep build in a separate job. - Revoke all account-wide tokens and every project token made redundant by Trusted Publishing.
- Scope any remaining token to one project, store it in a protected CI environment and track its rotation date.
- Require security keys for owners and keep at least two owners per project.
- Scan repositories, images, logs and built distributions for
pypi-tokens. - Keep attestations enabled and check that release files carry them.
- Review owners, maintainers, publishers and tokens whenever a maintainer leaves.
Standards and references
- PyPI: Publishing to PyPI with a Trusted Publisher
- PyPI: Trusted Publishing security model and considerations
- PyPI: Introduction to attestations
- PyPI: Secret reporting API and token format
- PyPI: Security alerts and suspicious activity
- Python: PEP 740, Index support for digital attestations
- PyPA: gh-action-pypi-publish
- GitHub Docs: Supported secret scanning patterns
Related NHI Mgmt Group resources: npm Trusted Publishing and Provenance Guide · RubyGems, NuGet and Crates.io Publishing Tokens Guide · GitHub Actions OIDC Federation Hardening Guide · CI/CD Security Guide