Automated Token Rotation Strategy
Because PyPI does not offer native Time-to-Live (TTL) settings or automatic expiration for API tokens, the recommended strategy is to shift the lifecycle management to a dedicated Secret Management System (SMS) (such as HashiCorp Vault, AWS Secrets Manager, or GitHub Actions Secrets) combined with a scheduled rotation pipeline.
Implementation Workflow
Since PyPI lacks a public API for creating or rotating tokens programmatically, a fully automated "zero-touch" rotation is not natively possible. Instead, implement a Scheduled Manual Rotation or a Managed Secret Rotation pattern:
- Scheduled Rotation: Set a calendar trigger (e.g., every 90 days) to prompt an administrator to generate a new scoped token via the PyPI web interface and update the CI/CD secret store.
- Secret Versioning: Use a secret manager that supports versioning. Deploy the new token as a new version, verify the deployment pipeline succeeds, and then deprecate the previous token version.
- Least-Privilege Scoping: Always use scoped tokens rather than account-level tokens. This ensures that if a token is leaked, the attacker can only affect specific projects, not the entire account.
Auditing and Identifying Stale Credentials
There are currently no documented programmatic methods (via public API) to audit token usage, check the "last used" date of a token, or list active tokens for a user. PyPI's token management is primarily handled through the account settings UI.
Practical Audit Workarounds
To identify and revoke stale credentials, you must implement tracking on the client side:
- Metadata Tagging: When creating a token, name it with a clear convention (e.g.,
ci-prod-project-name-2026-Q3). This allows you to identify which tokens are outdated by looking at the names in the PyPI dashboard.
- Centralized Secret Inventory: Maintain a registry in your SMS that maps tokens to their creation date and the specific pipeline they serve.
Verification and Safety
To verify that a token has been successfully rotated and the old one revoked, execute a scoped upload test using twine:
# Use the reserved username '__token__' for API token authentication
twine upload --username __token__ --password $PYPI_TOKEN dist/*
If the old token was revoked, any pipeline still utilizing the previous secret will fail with a 401 Unauthorized error, confirming the revocation was effective.
Missing Diagnostic: To refine this recommendation, please specify if you are using a self-hosted PyPI mirror (like Devpi or Nexus) or the official PyPI.org registry, as private registries often provide the programmatic APIs that PyPI.org lacks.