Join our Newsletter — 33% off our NHI Course
Home› Guides› PyPI API Tokens and Trusted Publishing Security Guide:…
Guide Secrets Management

PyPI API Tokens and Trusted Publishing Security Guide: Scoped Tokens, OIDC Publishing and Attestations

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 8 November 2026 13 min read
On this page

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:

PropertyClassic API tokenTrusted Publishing
What it isA macaroon serialised as pypi- followed by a base64 string of at least 85 charactersAn OIDC trust relationship between a project and a CI identity
ScopeEntire account (all projects) or one projectOne project; the minted token behaves like a project-scoped token
LifetimeLong-lived until revokedMinted token valid no more than 15 minutes
Where the secret livesCI secret store, .pypirc, developer machinesNowhere: the job requests it at run time
Used asUsername __token__, password the full token including pypi-Handled by pypa/gh-action-pypi-publish or twine
Bound toThe account that created it and that account's project rolesThe project: publishers are registered to projects, not users, so they survive maintainer removal
Main riskTheft from CI, images, logs or laptopsAbuse of the trusted workflow or repository
Supports attestationsNoYes (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

LevelRoleCan doControl to apply
ProjectOwnerUpload, add or remove owners and maintainers, delete files, releases or the project, configure Trusted PublishersAt least two owners with security keys; no more than needed
ProjectMaintainerUpload releases onlyDefault role for people who release
OrganisationOwnerManage members, roles, team permissions, projects and billing; delete the organisationTreat as privileged access; review quarterly
OrganisationManagerManage teams and team permissions, manage and create projectsLimit to release leads
OrganisationMemberManage projects it is granted through teamsGrant per team, not per person
OrganisationBilling managerBilling, invoices and subscriptions onlyNo 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 pypi in the publisher. PyPI calls this optional but strongly recommended, because environments support required reviewers, so a release needs a human approval.
  • Grant id-token: write per 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_target and issue_comment are 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

SignalSourceWhat it tells you
pypi_api_token alertGitHub secret scanning (partner pattern, push protection supported)A token was committed; PyPI revokes tokens reported on public sites
pypi-upload-token ruleGitleaks default config (matches the pypi-AgEIcHlwaS5vcmc macaroon header)Tokens in private repositories, images and logs, which public scanning never sees
Compromised token emailPyPI security alertsA token was found publicly (GitHub and deps.dev report to PyPI) and has already been revoked
Security historyPyPI account settingsToken creation, 2FA changes, logins and other account events to review after any alert
Unexpected releaseYour own release monitoring against the project's file listA version that did not come from your tagged pipeline run
Missing or wrong attestationPEP 740 attestations on uploaded filesA 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

  1. 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.
  2. Secure the humans: confirm every owner uses a WebAuthn security key, keeps recovery codes offline and that each project has at least two owners.
  3. 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.
  4. Harden the workflow: job-level id-token: write, separate build job, required reviewers on the environment, protected tags, pinned actions.
  5. 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.
  6. Keep attestations on: the PyPA action generates them by default under Trusted Publishing; do not set attestations: false without a reason.
  7. 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

  1. Revoke the token in account settings straight away, even if PyPI says it already has.
  2. 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.
  3. If a Trusted Publisher workflow was abused, remove the publisher, fix the workflow, then re-add it.
  4. Rotate CI secrets that shared the same runner or environment, and find how the token escaped (logs, images, artefacts).
  5. Record the incident in the CI/CD Pipeline Compromise Playbook format if a malicious release was published.

Framework mapping

Control areaNIST SP 800-53 Rev 5NIST CSF 2.0ISO/IEC 27001:2022 Annex AMITRE ATT&CK
Replace stored tokens with short-lived OIDC credentialsIA-5, IA-5(7)PR.AA-01A.5.17 Authentication informationT1552.001 Credentials In Files
Owner and maintainer roles, publisher reviewAC-2, AC-6PR.AA-05A.8.2 Privileged access rightsT1078 Valid Accounts
Release workflow integritySA-10 Developer Configuration ManagementPR.PS-06A.8.25 Secure development life cycleT1195.002 Compromise Software Supply Chain
Attestations and provenanceSR-4 Provenance, SR-11 Component AuthenticityGV.SC-07A.5.21 Managing information security in the ICT supply chainT1195.002
Token and release monitoringSI-4, AU-6DE.CM-09A.8.16 Monitoring activitiesT1528 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_dispatch trigger 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: write only 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

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

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 8 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.