CI/CD

This chapter describes the CI/CD pipelines used in the project. The pipelines automate various tasks such as testing, building, and deploying.

Overview

GitHub Actions and Read the Docs manage the automated workflows. Below is an overview of the key workflows included in the project:

  • Documentation Pipeline: Builds HTML with strict references and treats warnings as failures.

  • Behave Pipeline: Runs behave tests and uploads the results.

  • Codecov Pipeline: Runs unit tests via pytest and uploads the test coverage. codecov-badge

  • CodeQL Pipeline: Runs CodeQL security analysis on the codebase. codeql-badge

  • Pytest Pipeline: Runs unit tests via pytest and uploads the results. pytest-badge

  • mypy Pipeline: Runs mypy checks and uploads the results. mypy-badge

  • Ruff Pipeline: Runs ruff checks and uploads the results. ruff-badge

  • ZAP Pipeline: Runs OWASP ZAP security scans on the web application. zap-badge

Sequence Diagram CI/CD Pipeline

@startuml
    actor Developer
    database "GitHub\n Repo" as Repo
    collections "GitHub\n Actions" as GA
    control Behave
    control Codecov
    control MyPy
    control Pytest
    control Ruff
    collections "GitHub\n Readme" as Readme
    entity "Codecov\n Service" as CodecovService

    Developer -> Repo: Pull Request
    activate Repo
    Repo -> GA: Trigger workflows
    activate GA

    alt#Yellow #LightGreen All Tests Successful
        GA -> Behave: Run behave tests
        activate Behave
        Behave --> GA: Upload behave results
        Behave --> Readme: update Badges
        destroy Behave
        activate Readme

        GA -> Codecov: Run pytests \n with coverage report
        activate Codecov
        Codecov --> CodecovService: Upload coverage report
        destroy Codecov
        activate CodecovService
        CodecovService --> Readme: update Badge
        destroy CodecovService

        GA -> MyPy: Run mypy checks
        activate MyPy
        MyPy --> GA: Upload type-check results
        MyPy --> Readme: update Badge
        destroy MyPy

        GA -> Pytest: Run pytests
        activate Pytest
        Pytest --> GA: Upload test results
        Pytest --> Readme: update Badge
        destroy Pytest

        GA -> Ruff: Run ruff checks
        activate Ruff
        Ruff --> GA: Upload linting results
        Ruff --> Readme: update Badge
        destroy Ruff
        deactivate Readme
    else #Red Some Tests Not Successful
        GA --> Developer: Report Failing Tests
    end
    GA --> Repo: Pull-Request allowed
    deactivate GA
    deactivate Repo
@enduml

Sequence Diagram of the automatically triggered pipelines

Component Diagram CI/CD Pipeline

@startuml
    package "GitHub" {
      [Repository]
      [Actions]
    }

    package "CI/CD Pipelines" {
      [Codecov]
      [Behave]
      [MyPy]
      [Pytest]
      [Ruff]
    }

    [Repository] --> [CI/CD Pipelines] : Triggers Pipelines

    Codecov --> [Codecov Service] : Upload Coverage
    Behave --> [Actions] : Update Badge
    [Codecov Service] --> [Actions] : Update Badge
    MyPy --> [Actions] : Update Badge
    Pytest --> [Actions] : Update Badge
    Ruff --> [Actions] : Update Badge

    [Actions] --> [Repository] : Display Badges in README
@enduml

Component Diagram of the automatically triggered pipelines

Composite Setup action

Since we are using uv as package manager and the setup is the same everytime, it makes sense to create a separate action that can be used from every other action. The so called “composite action” looks like the following:

Setup uv composite action
name: Setup Environment
description: Checks out code and installs the current uv version and it's dependencies defined inside the pyproject.toml file.
inputs:
  python-version:
    description: "Python version used by CI, matching the Docker runtime."
    required: false
    default: '3.14'
  run_migrations:
    description: "Boolean to run the database migrations or not."
    required: false
    default: 'false'
runs:
  using: "composite"
  steps:
    - name: Install and setup uv
      uses: astral-sh/setup-uv@v10.3.3  # Sets up `uv` package manager.
      with:
        enable-cache: true  # Caches `uv` installation for faster runs.
        cache-dependency-glob: "uv.lock" # Invalidate cache when the lockfile changes.

    - name: Set up Python
      id: python
      uses: actions/setup-python@v7  # Sets up Python environment.
      with:
        python-version: ${{ inputs.python-version }}

    - name: Pin uv to the selected interpreter
      shell: bash
      env:
        PYTHON_PATH: ${{ steps.python.outputs.python-path }}
      run: echo "UV_PYTHON=${PYTHON_PATH}" >> "$GITHUB_ENV"

    - name: Initialize software KEK for database tests
      if: ${{ inputs.run_migrations == 'true' }}
      shell: bash
      run: |
        # Native CI commands run as the runner user, rather than container www-data.
        # Keep one key for this job's setup commands, tests, and server processes.
        kek_path="${RUNNER_TEMP}/trustpoint-ci-secrets/trustpoint_software_kek"
        sudo python3 docker/init_secret.py --type kek \
          --path "$kek_path" --group-id "$(id -g)"
        printf 'TRUSTPOINT_SOFTWARE_KEK_FILE=%s\n' "$kek_path" >> "$GITHUB_ENV"

    - name: Run database migrations # Resets the database before running tests.
      if: ${{ inputs.run_migrations == 'true' }} # Only run migrations if input is true.
      shell: bash
      run: |
        uv run trustpoint/manage.py reset_db --force --keep-all-migrations

As said, this action sets up the environment by installing uv via Astrals github action setup-uv and uses a pinned version, as well as caching. After this, the setup-python action is called with the shared action’s python-version input (currently Python 3.14), matching the Docker runtime. pyproject.toml defines the supported minimum, not that CI input. At the time of writing this, that action may be faster than uv’s own action because of GitHubs caching mechanism. With run_migrations=true, the action provisions a synthetic software KEK for the job and resets its disposable database while preserving tracked migrations. That destructive setup is for isolated CI, not an installation or upgrade recipe.

Documentation Pipeline

Read the Docs builds and publishes the documentation using the repository’s .readthedocs.yaml configuration. It installs the frozen documentation dependencies with uv and provides Java/PlantUML and Graphviz for diagrams. sphinx.fail_on_warning: true makes documentation warnings fail the hosted build, and nitpicky = True in docs/source/conf.py enables unresolved reference warnings for both hosted and local builds. No database reset is required. Pull-request previews and build-status reporting depend on the Read the Docs project’s integration settings.

Read the Docs configuration
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Exclude PDF and ePub builds as latexmk times out after 15 min
formats:
  - htmlzip

# Set the OS, Python version, and other tools you might need
build:
  os: ubuntu-24.04
  tools:
    python: "3.13"
  apt_packages:
    - graphviz
    - plantuml
  jobs:
    pre_create_environment:
      - asdf plugin add uv
      - asdf install uv latest
      - asdf global uv latest
    create_environment:
      - uv venv "${READTHEDOCS_VIRTUALENV_PATH}"
    install:
      - UV_PROJECT_ENVIRONMENT="${READTHEDOCS_VIRTUALENV_PATH}" uv sync --frozen --group docs

# Build documentation in the "docs/" directory with Sphinx
sphinx:
  configuration: docs/source/conf.py
  fail_on_warning: true

Behave Pipeline

The following workflow file is a reusable template workflow with one result per capability directory selected by the matrix. The template accepts a path below trustpoint/features/ and uploads a report for the selected scenarios. First of all, we checkout the code via actions/checkout. Then, we are using the previously defined action (see Composite Setup action) to make uv usable inside this workflow. Having uv activated, the behave action is triggered for the given feature file. Note that we need to use uv run trustpoint/manage.py behave instead of uv run behave to make Django available for behave. Once the tests are ran, an artifact with the test reports is uploaded.

Behave template workflow
name: Tests / Behave Template

on:
  workflow_call:
    inputs:
      feature_path:
        description: "Feature file or capability directory below trustpoint/features"
        required: true
        type: string

jobs:
  behave:
    runs-on: ubuntu-latest

    permissions:
      contents: read

    steps:
      - name: Checkout Code
        uses: actions/checkout@v7

      - name: Setup uv environment
        uses: ./.github/actions/setup-uv-action
        with:
          run_migrations: true

      - name: Run Behave tests
        run: |
          uv run trustpoint/manage.py behave \
            --format behave_html_pretty_formatter:PrettyHTMLFormatter \
            --outfile behave-report.html \
            trustpoint/features/${{ inputs.feature_path }}

      - name: Upload Test Report
        uses: actions/upload-artifact@v7
        if: always()
        with:
          name: behave-${{ inputs.feature_path }}-report
          path: behave-report.html

We provide an example on how to use this workflow below:

Behave capability matrix
name: Tests / Behave

on:
  pull_request:
  push:
    branches:
      - main

jobs:
  capability-tests:
    name: Behave / ${{ matrix.capability }}
    strategy:
      fail-fast: false
      matrix:
        capability:
          - devices
          - pki
          - api
          - security
          - system

    uses: ./.github/workflows/behave-test-template.yml
    permissions:
      contents: read
    with:
      feature_path: ${{ matrix.capability }}

Codecov Pipeline

We are using Codecov for analyzing our pytest code coverage and showing this with a badge. This workflow is also setting up uv as in Composite Setup action and using it to run pytest with a coverage report. Coverage XML and JUnit results are retained as artifacts, including for fork pull requests where Codecov upload is skipped. There is no numeric coverage threshold enforced by this workflow.

Upload to codecov workflow
name: Tests / Code Coverage

on:
  pull_request:
  push:
    branches:
      - main

jobs:
  codecov-upload:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout Code
        uses: actions/checkout@v7

      - name: Setup uv environment
        uses: ./.github/actions/setup-uv-action
        with:
          run_migrations: true

      - name: Run Pytest with Coverage
        run: uv run pytest --cov=trustpoint --cov-report=xml --junitxml=junit.xml -o junit_family=legacy trustpoint/ tests/

      - name: Retain coverage and test reports
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: coverage-reports
          path: |
            coverage.xml
            junit.xml
          if-no-files-found: error

      - name: Upload coverage to Codecov
        if: >
          github.event_name != 'pull_request' ||
          github.event.pull_request.head.repo.full_name == github.repository
        uses: codecov/codecov-action@v7
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          fail_ci_if_error: true

      - name: Upload test results to Codecov
        if: >
          !cancelled() &&
          (
            github.event_name != 'pull_request' ||
            github.event.pull_request.head.repo.full_name == github.repository
          )
        uses: codecov/codecov-action@v7
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          file: ./junit.xml
          report_type: test_results

Pytest Pipeline

This pipeline/workflow is kind of the same as the coverage pipeline except from not running the coverage reports and therefore also not uploading them. Here, we use a git flavored markdown report for printing the report nicely to the job summary. After this, there is the full report uploaded first and lastly, if one or more tests fail, we add a comment to the current pull request.

Pytest workflow
name: Tests / Pytest

on:
  pull_request:
  push:
    branches:
      - main

jobs:
  pytest:
    runs-on: ubuntu-latest

    permissions:
      contents: read
      pull-requests: write

    steps:
      - name: Checkout Code
        uses: actions/checkout@v7

      - name: Setup uv environment
        uses: ./.github/actions/setup-uv-action
        with:
          run_migrations: true

      - name: Run Pytest and create reports
        run: |
          uv run python tests/scripts/build_redoc_csp.py --check
          mkdir -p reports
          uv run pytest \
          --md-report-flavor github \
          --md-report-color never \
          --html=reports/pytest-report.html \
          --junitxml=reports/junit-report.xml \
          trustpoint/ tests/

      - name: Display Summary in GitHub Actions even if tests fail
        if: always()
        run: |
          echo "<details><summary>Pytest Report</summary>" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          cat "md-report.md" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "</details>" >> $GITHUB_STEP_SUMMARY

      - name: Upload Test Reports even if tests fail
        uses: actions/upload-artifact@v7
        if: always()
        with:
          name: pytest-reports
          path: reports/

      - name: Render the report to the PR
        uses: marocchino/sticky-pull-request-comment@v3
        if: >
          always() &&
          github.event_name == 'pull_request' &&
          github.event.pull_request.head.repo.full_name == github.repository
        with:
          header: test-report
          recreate: true
          path: md-report.md

mypy Pipeline

We use mypy for static type checking in python. This pipeline sets up uv through Composite Setup action and runs uv run --frozen mypy . in the locked project environment, matching the local hook.

mypy workflow
name: Code Quality / MyPy

on:
  pull_request:
  push:
    branches:
      - main
    tags:
      - 'v*'

jobs:
  mypy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout Code
        uses: actions/checkout@v7

      - name: Setup uv environment
        uses: ./.github/actions/setup-uv-action

      - name: Run MyPy
        run: uv run --frozen mypy .

Ruff Pipeline

Also, the ruff action is nearly as short as the mypy Pipeline. It runs uv run --frozen ruff check . across the repository. On pull requests, it also runs the Ruff formatter in check mode on added or modified Python files, honoring project exclusions. Pre-commit checks staged Python files using the same locked tools. Untouched legacy formatting is deferred to a separate cleanup; there is no repository-wide format gate.

ruff workflow
name: Code Quality / Ruff

on:
  pull_request:
  push:
    branches:
      - main
    tags:
      - 'v*'

jobs:
  ruff:
    runs-on: ubuntu-latest
    permissions:
      contents: read

    steps:
      - name: Checkout Code
        uses: actions/checkout@v7
        with:
          fetch-depth: 0

      - name: Setup uv environment
        uses: ./.github/actions/setup-uv-action

      - name: Run Ruff Linting
        run: uv run --frozen ruff check .

      - name: Check formatting of Python files changed by the pull request
        if: github.event_name == 'pull_request'
        env:
          FORMAT_BASE_SHA: ${{ github.event.pull_request.base.sha }}
        run: |
          git diff --name-only --diff-filter=ACMR -z "$FORMAT_BASE_SHA" HEAD -- '*.py' '*.pyi' |
            xargs -0 -r uv run --frozen ruff format --check --force-exclude --

CodeQL Pipeline

We use CodeQL for automated security analysis of the codebase. This pipeline runs CodeQL analysis on multiple languages including Python, JavaScript/TypeScript, and GitHub Actions. It performs static analysis to identify potential security vulnerabilities and code quality issues. The analysis is configured with a custom CodeQL configuration file and runs on a schedule as well as on pushes and pull requests to the main branch.

CodeQL workflow
name: "Security / CodeQL Advanced"

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
  schedule:
    - cron: '44 7 * * 2'

jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    # Runner size impacts CodeQL analysis time. To learn more, please see:
    #   - https://gh.io/recommended-hardware-resources-for-running-codeql
    #   - https://gh.io/supported-runners-and-hardware-resources
    #   - https://gh.io/using-larger-runners (GitHub.com only)
    # Consider using larger runners or machines with greater resources for possible analysis time improvements.
    runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
    permissions:
      # required for all workflows
      security-events: write

      # required to fetch internal or private CodeQL packs
      packages: read

      # only required for workflows in private repositories
      actions: read
      contents: read

    strategy:
      fail-fast: false
      matrix:
        include:
        - language: actions
          build-mode: none
        - language: javascript-typescript
          build-mode: none
        - language: python
          build-mode: none
        # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
        # Use `c-cpp` to analyze code written in C, C++ or both
        # Use 'java-kotlin' to analyze code written in Java, Kotlin or both
        # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
        # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
        # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
        # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
        # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
    steps:
    - name: Checkout repository
      uses: actions/checkout@v7

    # Add any setup steps before running the `github/codeql-action/init` action.
    # This includes steps like installing compilers or runtimes (`actions/setup-node`
    # or others). This is typically only required for manual builds.
    # - name: Setup runtime (example)
    #   uses: actions/setup-example@v1

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v4
      with:
        languages: ${{ matrix.language }}
        build-mode: ${{ matrix.build-mode }}
        config-file: ./.github/codeql/codeql-config.yml
        # If you wish to specify custom queries, you can do so here or in a config file.
        # By default, queries listed here will override any specified in a config file.
        # Prefix the list here with "+" to use these queries and those in the config file.

        # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
        # queries: security-extended,security-and-quality

    # If the analyze step fails for one of the languages you are analyzing with
    # "We were unable to automatically build your code", modify the matrix above
    # to set the build mode to "manual" for that language. Then modify this step
    # to build your code.
    # ℹ️ Command-line programs to run using the OS shell.
    # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
    - name: Run manual build steps
      if: matrix.build-mode == 'manual'
      shell: bash
      run: |
        echo 'If you are using a "manual" build mode for one or more of the' \
          'languages you are analyzing, replace this with the commands to build' \
          'your code, for example:'
        echo '  make bootstrap'
        echo '  make release'
        exit 1

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v4
      with:
        category: "/language:${{matrix.language}}"

ZAP Pipeline

We use OWASP ZAP for an unauthenticated baseline against a disposable deployment built from the checkout. Automatic setup must complete, an administrator must exist, and the operational login endpoint must respond before HTTP and HTTPS scans start.

Each scan retains its exit status, log, and JSON/Markdown/HTML reports. Both scans are attempted independently. The final checker rejects missing, empty, malformed or out-of-scope report evidence and scanner errors/timeouts. Medium/high alerts and configured ZAP FAIL results fail the job; informational/low alerts are reported without failing the baseline. Reports are uploaded even when validation fails, and missing artifacts are an error.

This workflow does not authenticate the spider or establish protected-page coverage. Record authenticated operational scan coverage separately as required by Release Checklist; a successful baseline is not that evidence.

ZAP workflow
name: Security / ZAP Baseline Scan

on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]
  workflow_dispatch:
  release:
    types: [published]

jobs:
  zap-baseline:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    permissions:
      contents: read
      actions: read

    steps:
      - name: Checkout Code
        uses: actions/checkout@v7

      - name: Configure disposable operational deployment
        run: |
          cp .env.example .env
          cat >> .env <<'ENV'

          TP_AUTO_SETUP=true
          TP_ADMIN_USERNAME=zap-admin
          TP_ADMIN_PASSWORD=synthetic-zap-ci-password-321
          TP_INJECT_DEMO_DATA=false
          ENV
          sudo python3 docker/init_secret.py --type all
          rm -rf reports/zap
          mkdir -p reports/zap
          chmod a+w reports/zap

      - name: Start Trustpoint from this checkout
        run: docker compose up -d --build --wait --wait-timeout 300 postgres trustpoint

      - name: Require completed setup and operational login endpoint
        id: readiness
        run: |
          for attempt in {1..60}; do
            echo "Checking operational readiness ($attempt/60)"
            if docker compose exec -T --user www-data -e TRUSTPOINT_PHASE=operational trustpoint \
              .venv/bin/python trustpoint/manage.py shell -c \
              "from setup_wizard.models import SetupWizardCompletedModel; from django.contrib.auth import get_user_model; assert SetupWizardCompletedModel.objects.filter(pk=1, setup_completed_at__isnull=False).exists(); assert get_user_model().objects.filter(username='zap-admin', is_superuser=True).exists()" \
              > reports/zap/readiness.log 2>&1 &&
              [ "$(curl -sk --max-time 5 -o /dev/null -w '%{http_code}' https://localhost/users/login/)" = 200 ]; then
              exit 0
            fi
            sleep 2
          done
          echo '::error::Operational setup/login did not become ready'
          exit 1

      - name: Check deployed security headers and HTTP enrollment routing
        run: python3 tests/docker_security/check_response_headers.py --insecure

      - name: Check CSP compatibility in Chromium
        env:
          TP_CSP_USERNAME: zap-admin
          TP_CSP_PASSWORD: synthetic-zap-ci-password-321
        run: |
          npm install --prefix "$RUNNER_TEMP/csp-browser" --no-audit --no-fund playwright@1.64.1
          "$RUNNER_TEMP/csp-browser/node_modules/.bin/playwright" install --with-deps chromium --only-shell
          node --test tests/docker_security/browser_diagnostics.test.cjs
          NODE_PATH="$RUNNER_TEMP/csp-browser/node_modules" node tests/docker_security/csp_browser.cjs

      # Browser/header failures remain blocking, but must not skip the independent
      # scans and turn their absence into misleading report-integrity failures.
      - name: Run independent HTTP and HTTPS baselines
        id: zap_baselines
        if: ${{ !cancelled() && steps.readiness.outcome == 'success' }}
        run: |
          docker pull ghcr.io/zaproxy/zaproxy:stable
          for protocol in http https; do
            status=0
            timeout 600 docker run --rm --network host \
              -v "$PWD/reports/zap:/zap/wrk:rw" \
              ghcr.io/zaproxy/zaproxy:stable zap-baseline.py \
              -t "$protocol://localhost" -a -T 5 \
              -J "$protocol.json" -w "$protocol.md" -r "$protocol.html" \
              > "reports/zap/$protocol.log" 2>&1 || status=$?
            printf '%s\n' "$status" > "reports/zap/$protocol.exit"
          done

      - name: Check scan completion, report integrity and finding policy
        if: ${{ !cancelled() && steps.readiness.outcome == 'success' }}
        run: python3 .github/check_zap_reports.py reports/zap

      - name: Upload ZAP evidence even on failure
        uses: actions/upload-artifact@v7
        if: always()
        with:
          name: zap-reports
          path: reports/zap/
          if-no-files-found: error
          retention-days: 30

      - name: Cleanup disposable deployment
        if: always()
        run: docker compose down -v --remove-orphans