PyPI Trusted Publishing

Definition

PyPI Trusted Publishing is a security feature that allows package maintainers to securely publish Python packages to the Python Package Index (PyPI) by using trusted third-party services. This mechanism leverages OpenID Connect (OIDC) to authenticate and authorize publishing actions, reducing the need for long-lived API tokens and enhancing the security posture of the package publishing process.

Secure Settings Example

# GitHub Actions workflow example for secure PyPI publishing
name: Publish Python Package

on:
  push:
    branches:
      - main

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write  # Required for OIDC authentication

    steps:
      - uses: actions/checkout@v2

      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.x'

      - name: Install dependencies
        run: pip install build twine

      - name: Build package
        run: python -m build

      - name: Publish to PyPI
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: |
          python -m twine upload --repository pypi dist/*

Insecure Settings Example

# GitHub Actions workflow example with insecure PyPI publishing
name: Publish Python Package

on:
  push:
    branches:
      - main

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.x'

      - name: Install dependencies
        run: pip install build twine

      - name: Build package
        run: python -m build

      - name: Publish to PyPI
        env:
          TWINE_USERNAME: __token__
          # Hardcoding API token directly in the workflow is insecure
          TWINE_PASSWORD: my-insecure-hardcoded-token
        run: |
          python -m twine upload --repository pypi dist/*