Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 20 min · revision 3

Securing the pipeline itself: lessons from compromised actions

Reduce the risk of supply-chain attacks on CI: pin actions to verified commit SHAs, give tokens minimal permissions, keep untrusted input out of shell steps and keep fork code away from secrets.

Contentsand lesson path

What you will learn

  • Harden a pipeline with least-privilege job tokens, third-party actions pinned to commit SHAs, and secrets kept away from untrusted pull requests.

Prerequisites: Git Workflow, Build & Test Pipeline

01. Why attackers target the pipeline

CI pipelines hold powerful credentials for cloud accounts, package and container registries, and source repositories. That makes the pipeline an attractive target, often easier to reach than hardened production systems. Two well-known incidents show what a compromised build can do: a modified Codecov uploader sent the credentials in CI environment variables to attackers, and the SolarWinds build system was changed to insert a backdoor into a product that was then signed as usual.

The primary attack vectors targeting CI workflows include:

  • Compromised Third-Party Actions: Many repositories reference third-party actions using mutable tags like uses: actions/checkout@v4 or community actions like uses: author/action@v1. Because Git tags are mutable pointers, a malicious maintainer or an attacker who compromises the author's account can overwrite the tag with malicious code that exfiltrates repository secrets.

  • Over-Privileged Automatic Tokens: Hosted CI platforms inject an automatic authentication token (such as ${{ secrets.GITHUB_TOKEN }}) into every runner. By default, legacy repository configurations grant this token broad read-and-write permissions across code, issues, packages, and releases, allowing compromised jobs to alter repository content.

  • Script Injection via Untrusted Context Variables: When pipelines concatenate untrusted user inputs (such as pull request titles, issue comments, or Git commit messages) directly into inline shell scripts, attackers can execute arbitrary shell commands inside the runner.

  • Persistent Long-Lived Cloud Credentials: Storing long-lived AWS IAM access keys or service account JSON files inside repository secret vaults creates severe exposure risks. If a runner environment variable leaks via an unmasked diagnostic command or compromised build dependency, the static credentials keep working for anyone who copied them until someone notices and revokes them.

02. Four controls: SHA pins, minimal permissions, OIDC and fork isolation

Four controls reduce these risks:

  1. Pinning Actions to 40-Character Commit SHAs: Every external action should be referenced by a full commit SHA with the release tag as a comment (actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1). A tag can be moved to different code; a full SHA always resolves to the same commit, because a commit cannot change without changing its hash. Pinning has limits. It freezes only the action's own repository content, not what the action downloads at run time (a container image by tag, a nested uses: other/action@v1, a script fetched with curl), so prefer actions that pin their own dependencies. A SHA can also point to an imposter commit that exists only in a fork of the action's repository, so take the SHA from a tagged release of the official repository (for example with git ls-remote --tags https://github.com/actions/checkout). Let Dependabot or Renovate propose SHA updates so pins do not go stale.

  2. Top-Level Read-Only Token Permissions: Declare permissions: at the top of every workflow, usually just contents: read, and grant more only on the job that needs it (for example packages: write on the publishing job). Leaving the block out is not a safe default: the token's default access depends on repository and organisation settings, and older repositories still default to read and write. Checkout needs only contents: read, and actions/upload-artifact stores files in the Actions artifact store, not in the repository, so it needs no contents: write. Once you list any permission, every permission you did not list is set to none.

  3. OpenID Connect (OIDC) Instead of Stored Cloud Keys: With OIDC, the job asks GitHub for a short-lived signed token (a JSON Web Token, JWT) that names the repository, branch or environment and workflow it runs for, and the cloud provider exchanges that token for temporary credentials. The job can request the token only if it is granted id-token: write. Because a permissions block sets every unlisted permission to none, list contents: read beside it, or checkout stops working. id-token: write gives no write access to the repository; it only allows requesting the token. On the cloud side, the role's trust policy must check the token's sub (subject) claim, for example repo:corp/payments:environment:production; otherwise a workflow in any repository could assume the role. The credentials last as long as the session the job requests, not until the job ends: aws-actions/configure-aws-credentials asks for one hour unless role-duration-seconds says otherwise (15 minutes to 12 hours, capped by the role's maximum session duration). Keyless CI and rotating credentials shows the full trust policy.

  4. Keeping Untrusted Pull Request Code Away From Secrets: A pull_request run for a fork gets a read-only token and no secrets, so running the fork's code there is safe. pull_request_target and workflow_run runs get the base repository's secrets and a token that can write, which is acceptable only because they normally run trusted code from the default branch. GitHub Security Lab calls the dangerous combination a pwn request: a privileged workflow that checks out the pull request's head commit and then runs anything from it. The workflow file still comes from the base branch, but make test, npm install (which runs install scripts), a test file or a build script now come from the attacker and run with your secrets. A workflow_run job that downloads an artifact built from a fork and executes it has the same flaw. Since v7.0.0 (June 2026), and in the backport releases v6.1.0, v5.1.0 and v4.4.0, actions/checkout refuses to check out fork pull request code under these two triggers unless you set allow-unsafe-pr-checkout: true. Older pins such as v4.3.1 do not have this guard. The guard also has limits: fetching the code with git fetch or gh pr checkout, or running a downloaded artifact, is not covered by that check.

Examine the hardened workflow below, then the pwn request and its safe replacement.

YAML · Hardened pipeline with immutable SHA pinning and minimal permissions
name: Hardened Production Pipeline

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

# Read-only token for every job unless a job asks for more
permissions:
  contents: read

jobs:
  audit-and-build:
    runs-on: ubuntu-latest
    # A job that publishes would add its own block, e.g. packages: write
    steps:
      # Pinned to a full 40-character commit SHA (tag in the comment)
      - name: Checkout repository code
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false

      # Defense against script injection via environment variable
      - name: Safely evaluate pull request title
        env:
          PR_TITLE: ${{ github.event.pull_request.title }}
        run: |
          echo "Validating pull request title conventions..."
          python -c 'import os, sys; print("PR:", os.environ.get("PR_TITLE", ""))'
YAML · INSECURE example of a pwn request: do not copy
# INSECURE: an example of a pwn request. Do not copy.
name: PR tests with secrets
on: pull_request_target
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ github.event.pull_request.head.sha }}  # the fork's commit
          allow-unsafe-pr-checkout: true  # turns off checkout's fork guard
      - run: make test  # runs the fork's Makefile with the secret below
        env:
          REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}

The safe replacement splits the work in two, as GitHub Security Lab recommends. The first workflow runs the fork's code under pull_request, with a read-only token and no secrets, and uploads its result as an artifact. The second runs on workflow_run with the permissions needed to comment, downloads that artifact outside the workspace and only reads it. Everything in the artifact came from the fork, including the pull request number, so the privileged job treats it as data and never executes a file from it. It checks that the number is numeric, asks the API for that pull request's current head commit (headRefOid) and comments only if it equals workflow_run.head_sha, the commit the tests ran on. Without that check, a fork could write another pull request's number into the file and make the bot comment there. If the pull request got a new commit in the meantime, the check fails and the run for the newer commit comments instead. What the check cannot stop: the comment text itself comes from the fork, so it can contain anything, for example a misleading link. Static checkers such as zizmor flag both privileged triggers for review, which is a useful prompt to check each such workflow by hand.

YAML · .github/workflows/pr-tests.yml: untrusted code, no secrets
name: PR tests
on: pull_request
permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - name: Run the fork's tests without secrets
        run: |
          set -o pipefail  # fail the step if make fails, not only tee
          make test 2>&1 | tee summary.txt
      - name: Save the pull request number next to the summary
        if: always()  # also when the tests failed
        env:
          PR_NUMBER: ${{ github.event.number }}
        run: echo "$PR_NUMBER" > pr-number.txt
      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        if: always()  # a failing run is the one that most needs a comment
        with:
          name: test-summary
          path: |
            summary.txt
            pr-number.txt
YAML · .github/workflows/pr-comment.yml: privileged, reads data only
name: Comment the test summary
on:
  workflow_run:
    workflows: ["PR tests"]
    types: [completed]
permissions:
  actions: read
  pull-requests: write
jobs:
  comment:
    if: github.event.workflow_run.event == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      # v8.0.2. In your repo, put `# v8.0.2` at the end of the uses: line: Dependabot
      # and Renovate update only a same-line comment. Moved here to fit the page.
      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333
        with:
          name: test-summary
          path: ${{ runner.temp }}/summary  # outside the workspace; read as data
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ github.token }}
      - name: Post the summary (never execute anything from the artifact)
        env:
          GH_TOKEN: ${{ github.token }}
          HEAD_SHA: ${{ github.event.workflow_run.head_sha }}  # the tested commit
        run: |
          pr=$(cat "$RUNNER_TEMP/summary/pr-number.txt")
          [[ "$pr" =~ ^[0-9]+$ ]] || { echo "bad PR number"; exit 1; }
          # The fork chose this number: accept it only for a PR at the tested commit
          head=$(gh pr view "$pr" --repo "$GITHUB_REPOSITORY" \
            --json headRefOid --jq .headRefOid)
          [[ "$head" == "$HEAD_SHA" ]] || { echo "PR $pr is not at $HEAD_SHA"; exit 1; }
          gh pr comment "$pr" --repo "$GITHUB_REPOSITORY" \
            --body-file "$RUNNER_TEMP/summary/summary.txt"

03. Where jobs run, and what log masking can and cannot hide

Where a job runs matters as much as what it runs. Hosted and self-hosted runners carry different risks:

  • Ephemeral Cloud Runners: Hosted runner virtual machines are deleted when the job ends. Malware that a job installs on the runner is deleted together with the VM's disk, so it cannot wait on that machine for the next job. It can still steal secrets or tamper with outputs during the job itself, and it can reach later jobs through state that outlives the VM, such as a poisoned entry in the Actions cache or an uploaded artifact that a later job trusts.

  • Self-Hosted Runner Risks: If your organization deploys self-hosted runners on persistent bare-metal servers or long-lived Kubernetes pods, a malicious job can install backdoors in the local filesystem, sniff neighboring container network traffic, or extract Docker socket credentials. If you need self-hosted runners, prefer ephemeral runners, for example Actions Runner Controller on Kubernetes, which deletes the runner pod after one job.

  • Secret Masking Hygiene: CI platforms replace known secret values in job logs with ***. Masking is a safety net, not a control: it matches the exact value and a few fixed encodings of it (the GitHub runner also masks its Base64, URL-escaped and JSON-escaped forms), but not a secret that was split, reversed, hex-encoded or used to derive a new value such as a signed token. Register a derived value with echo "::add-mask::$VALUE" before it can reach the log, and do not print secrets at all: masking cannot stop a script from sending a secret elsewhere.

  • Attestation and SLSA Provenance: Pipelines that need strong assurance generate signed SLSA (Supply-chain Levels for Software Artifacts) provenance documents during the build. Using cryptographic keys managed by Sigstore or GitHub Artifact Attestations, the build signs a record of the source commit, workflow and build parameters that produced the binary, so later changes to that record can be detected.

04. Check your understanding

Practice check · 3 questions

Fork commits, untrusted input and fork artifacts

Three questions on pipeline attacks from the lesson.

Q1. Why take an action's commit SHA from a tagged release of its official repository, for example with `git ls-remote --tags`?
Q2. What is the secure pattern for referencing user-controlled strings (such as issue titles or pull request bodies) within a shell execution step?
Q3. A `workflow_run` job holds a deploy token. It downloads the `dist/` artifact that a fork's `pull_request` run built, then runs `./dist/check.sh` to decide what to comment on the pull request. Which change removes the risk?
Practice only: not graded, not saved, not evidence.

05. Apply it

Apply these controls to your own repositories:

  • Pin Every Action to a 40-Character SHA: Audit all workflow files and replace mutable semver tags with verified commit hashes.
  • Declare Explicit Minimal Permissions: Define permissions: { contents: read } at the root of every workflow; elevate only when publishing releases.
  • Defend Against Script Injection: Never interpolate ${{ github.event... }} into shell strings; always pass untrusted values through env: variables.
  • Adopt OIDC for Cloud Authentication: Give only the deploy job id-token: write and contents: read, pin the role's trust policy to your repository and environment through sub, and set a short role-duration-seconds.
  • Audit Privileged Triggers: List every workflow on pull_request_target or workflow_run and confirm that none of them runs code or artifacts from a fork; move such work to pull_request.
  • Use Ephemeral Runners: Ensure runner VMs or pods are recycled after each job, so nothing persists on the machine between jobs. A job can still steal secrets while it runs, or poison the cache and artifacts that later jobs use, so treat those as untrusted input too.
  • Disable Credential Persistence: Configure persist-credentials: false in actions/checkout so later steps cannot reuse the token that checkout stores for git.

06. Review prompt

Without looking back, explain what a pwn request is, which two triggers make it possible and how the two-workflow pattern avoids it. Then list the permissions a job needs to request an OIDC token, say which claim the cloud trust policy must check, and what decides how long the issued credentials stay valid.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check