A GitHub Actions Trust Boundary Audit: Fork PRs, npm Scripts, and GITHUB_TOKEN Scope

A GitHub Actions Trust Boundary Audit: Fork PRs, npm Scripts, and GITHUB_TOKEN Scope

pr0h0••33 min read•coding
AI Usage (99%)
On this page

Introduction: Keep Fork Contributions Open Without Giving PR Code Privileged Execution

This GitHub Actions trust boundary audit shows how to keep fork PR tests running without giving contributor code privileged execution. You will trace untrusted input through checkout, npm lifecycle scripts, and GITHUB_TOKEN scope, then decide whether each pairing is acceptable for your repository. Most GitHub Actions disasters do not start with a dramatic misconfiguration. They start with a small, reasonable-looking diff. Someone needs to label a PR that came from a fork, so they reach for pull_request_target. A week later someone else needs the tests to actually run against the code, so they add actions/checkout. Six lines apart, same YAML file. Neither change is wrong on its own. Together they hand a stranger's commit a job that can write to your repository.

The audit position: trace untrusted inputs to live credentials

Removing risky triggers is a real fix, and it is the one I would apply first. But as an audit it is weak, because a trigger is only the entry point. The thing you actually care about is whether contributor-controlled bytes reach an execution context holding a capability you would not hand a stranger: repository write access, a publish token, a protected environment secret, an OIDC identity, a runner that persists between jobs.

So the question I ask is not "which triggers are dangerous." It is:

  1. Enumerate every contributor-controlled input.
  2. Follow each one through checkout, install, build, and script execution.
  3. Work out which credential is live in the process at the moment that input runs.
  4. Decide whether that pairing is acceptable. Not in general — for this repository.

Stated plainly: fork PRs should keep running their full test suite in CI. Closing that off to feel safe is a contributor-experience regression that buys less than people assume, because pull_request from a fork is already an unprivileged context. The work is to keep it unprivileged on purpose — explicit permissions, no secrets, no persistent credentials, no privileged runner — instead of trusting one event type's defaults to save you.

Scope: a JavaScript repository with fork PR tests, labeling, and release publishing

Concrete and deliberately boring, because that is where the mistakes live: a JavaScript repository shaped like this.

  • a fork PR test job that runs npm ci and npm test,
  • an optional metadata job that labels PRs,
  • a separate release workflow that publishes to a registry.

Node 22.x and 24.x are the targets. Record your toolchain before you start; npm's lifecycle behaviour has moved across majors:

node -v && npm -v

Every workflow below is a fixture I wrote for this post. None of it is a reconstruction of any real organisation's configuration — more on that next.

What the Supplied PSF Report Establishes—and What It Does Not

📝

The event this post responds to comes from a single news item supplied to me. I am repeating its claim, not verifying it. Everything after this section is my own audit material.

The attributed PSF claim

The supplied item, attributed to news.lavx.hu and dated November 23, 2026, reports that the Python Software Foundation removed dangerous GitHub Actions triggers across its organizations. That is the whole of the substantive claim as it reached me. I am relaying it as reported, not as an independently confirmed finding. I have not seen the underlying diff, an advisory, a mailing-list post, or a PSF security statement.

The report's evidence limits

The material is thin in ways that matter to anyone trying to learn from it:

  • No affected repositories are named.
  • No specific triggers are named — not pull_request_target, not workflow_run, nothing.
  • There are no workflow revisions or diffs.
  • It describes no exploited vulnerability and no confirmed compromise.
  • There is no timeline beyond the publication date, and no word on what replaced the removed triggers.

That last gap bothers me most. "Removed dangerous triggers" could mean a genuine privilege-separation refactor. It could also mean someone deleted pull_request_target: types: [labeled] and moved the label step into a workflow that now runs on pull_request with a write token, which would be worse. The report cannot tell us which.

Why the report still motivates a GitHub Actions audit

An organisation-wide cleanup of this kind tells you something real even without the details: somebody looked at the trigger surface across many repositories and found enough to act on. Most organisations have never done that pass. The inventory is spread over dozens of files written by dozens of people across years, and nobody has ever held the whole picture at once.

So treat the report as a prompt to run that pass on your own repos, not as a case study to copy. Where I speculate, I will label it.

Build a Trust Map Before Editing Workflow YAML

Editing YAML first is how audits turn into whack-a-mole. Start with assets.

Identify what is worth stealing in a JavaScript CI pipeline

In a JavaScript repo with CI and a release pipeline, the capability list usually looks like this:

AssetReached viaConsequence if misused
Repository write accessGITHUB_TOKEN with contents: write, pull-requests: write, packages: writePushing code, editing releases, poisoning tags
Registry publish rightsNPM_TOKEN secret, or OIDC trusted publishingPublishing a malicious version under your name
Environment secretsGitHub Environments with required reviewersProduction credentials, cloud keys
Cloud accessOIDC (id-token: write) → cloud role assumptionLateral movement outside GitHub
Cache and artifact storageactions/cache, actions/upload-artifactSupply-chain substitution in downstream jobs
Runner filesystemSelf-hosted runnersPersistence across jobs, credential theft
Branch protection bypassAdmin apps, PATs, deploy keysForce-push, protection removal

You do not need to fix all of these. You need to know which ones exist, because the next step is matching inputs to them.

Trace contributor-controlled inputs in fork PRs

For a fork PR, assume the attacker controls:

  • every file in the PR diff, including package.json, package-lock.json, .npmrc, tsconfig.json, test files, build scripts, and anything under scripts/;
  • any new local action the PR adds under .github/actions/ — a local action is just code in the repo, so a PR can add one, and a privileged workflow running uses: ./.github/actions/foo will execute it;
  • the PR title, body, branch name, commit messages, and file paths, all of which are attacker-authored text;
  • anything uploaded as an artifact or written to a cache by an unprivileged run.

Note what is not on that list for a plain pull_request event: the workflow file itself. For pull_request, GitHub runs the workflow definition from the base branch, not the PR head. That is the single most important property of the event, and it is why pull_request is safe-ish by default while pull_request_target is dangerous by design.

Build the trust-boundary audit table

One row per workflow. Blank cells are findings, not formatting failures.

EventWorkflow def fromCode checked outEffective tokenSecretsRunnerSide effects
pull_request (fork)base branchPR merge commitread-only (default)noneGitHub-hostednone
pull_request_targetbase branchbase branch (default)read/write (default)availableGitHub-hosteddepends
workflow_rundefault branchwhatever you check outworkflow's ownavailableGitHub-hosteddepends
push (tag)tag committag commitworkflow's ownavailableGitHub-hostedpublish

The "workflow def from" column is the one people skip. If you do not know which revision of the YAML is executing, the rest of the row is guesswork.

Understand Which Boundary Each GitHub Actions Trigger Creates

pull_request: the merge ref, and the restrictions that come with forks

By default a pull_request run checks out refs/pull/<n>/merge, a synthetic merge commit GitHub builds from the PR head and the base branch. Your tests exercise what would land, not what was pushed.

For PRs from forks, two documented restrictions apply: secrets are not passed to the runner (GITHUB_TOKEN excepted), and GITHUB_TOKEN is read-only. Both are described in GitHub's events reference and the GITHUB_TOKEN documentation.

There are two exceptions to verify per repository, because they change the analysis:

  1. Repository or organisation settings can send write tokens to fork PR workflows. An Actions setting upgrades the fork-PR token to read/write. If it is on, your "unprivileged" test job is not. Check it rather than assuming.
  2. Dependabot PRs are treated like fork PRs for pull_request, push, and several other events — read-only token, no secrets. Fine for tests; surprising when someone expects a Dependabot PR to publish a lockfile update.

And the one that bites people: a pull_request from a branch in the same repository is not a fork PR. Secrets are available and the token is whatever your permissions block says. If your contributors have push access, "it's a PR, so it's unprivileged" is false.

pull_request_target: base context, privileged credentials, and one bad checkout

pull_request_target runs in the context of the base repository. That means:

  • the workflow definition comes from the base branch, so a PR cannot modify it;
  • secrets are available;
  • GITHUB_TOKEN gets read/write by default unless you declare permissions;
  • GITHUB_SHA is the base branch tip, not the PR head.

That combination exists so maintainers can do metadata work on PRs from forks, which is a reasonable design. The footgun is that the PR head SHA is right there in the payload, and actions/checkout accepts a ref:

## DO NOT USE — deliberate anti-pattern, kept short for illustration
on: pull_request_target
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<40-char-commit-sha> # resolve this yourself
        with:
          ref: ${{ github.event.pull_request.head.sha }}
      - run: npm ci

The moment that checkout lands, every other property of pull_request_target turns from a convenience into a liability. The trigger was never the vulnerability on its own; the pairing was.

workflow_run: the escalation path people forget

workflow_run fires a downstream workflow when an upstream workflow completes. It runs with the privileges of the base/default branch context, so a downstream workflow can hold secrets and a write token even though the upstream run — a fork PR test — could hold neither.

That is exactly why the pattern gets used: pull_request runs the untrusted tests, workflow_run picks up the result and posts a comment or applies a label. It is also why the pattern is dangerous. The artifact sitting between the two was produced by untrusted code. The privilege boundary got moved, not removed, and downloading that artifact crosses it.

push, workflow_dispatch, and environment-gated releases

A push to a tag you control, or a manual workflow_dispatch, is a reasonably trusted trigger. That does not make every input trusted. A tag-triggered release workflow running npm ci on a commit whose lockfile was merged from a PR is still executing code a stranger wrote. You approved it, which is a different statement from "it is safe."

Environment protection rules (environment: npm-publish with required reviewers) are the right control for the publish step, because they gate the credential rather than the trigger. Be precise about what a required reviewer does, though: it gates access to environment secrets and deployments, and it does not sandbox the job. Code before the gate still runs with whatever the job-level permissions allow.

Inventory Workflows and Follow Their Indirect Execution Paths

Read-only enumeration

Start with things you can run without touching anything.

## Every workflow file, sorted
find .github -name '*.yml' -o -name '*.yaml' | sort

## Trigger lines (incomplete by design — multiline YAML will be missed)
grep -rn --include='*.yml' --include='*.yaml' -E '^\s{0,4}(on|true):' .github/workflows

## Privileged triggers, the ones I want to review by hand
grep -rn -E 'pull_request_target|workflow_run|workflow_dispatch' .github/workflows

## Credential and checkout surface
grep -rn -E 'secrets\.|persist-credentials|ref:|token:' .github/workflows

## Reusable workflows and local actions (both are indirect execution)
grep -rn -E 'uses:\s*(\./|\.\./)|uses:\s*\S+/\S+/\.github/workflows/' .github/workflows

## Install and script execution
grep -rn -E 'npm (ci|install|test|run)|yarn |pnpm ' .github/workflows

Where grep lies to you

These searches are a starting point, and I want to be blunt about how they fail, because clean grep output is the most common false negative in this kind of audit.

  • Multiline YAML. on: followed by a list on the next lines, or permissions: spread across five lines, will not match single-line patterns.
  • Inherited permissions. A job with no permissions key inherits the workflow level; a workflow with none inherits the repository or organisation default. Grep cannot compute the effective value.
  • Reusable workflow nesting. uses: org/repo/.github/workflows/x.yml@ref can carry its own permissions and its own secrets: inherit. You have to open the called workflow at that ref.
  • Composite and local actions. uses: ./.github/actions/setup executes code from the checked-out tree. If that tree is a PR head, it is contributor code.
  • Action internals. uses: some-org/some-action@v1 is itself code, and a pinned major tag is a moving target.
  • Organisation settings. Default token permissions and the fork-token override live outside the repo. Nothing in your working tree tells you their values.

A small inventory helper

For the parts grep gets wrong, a YAML parser earns its keep. This script is read-only: it walks .github/workflows, parses each file, and prints event names plus declared permissions at workflow and job level.

tools/workflow-inventory.mjs
#!/usr/bin/env node
// Read-only inventory. No network, no writes. Run: node tools/workflow-inventory.mjs




const DIR = ".github/workflows";

function triggerNames(on) {
if (typeof on === "string") return [on];
if (Array.isArray(on)) return on.map(String);
if (on && typeof on === "object") return Object.keys(on);
return ["<unparsed>"];
}

function label(value) {
return value === undefined ? "inherited" : JSON.stringify(value);
}

const files = readdirSync(DIR)
.filter((f) => f.endsWith(".yml") || f.endsWith(".yaml"))
.sort();

for (const file of files) {
const doc = parse(readFileSync(join(DIR, file), "utf8")) ?? {};

// NB: YAML 1.1 parsers (js-yaml 3.x) resolve the bare key `on` to boolean true,
// which stringifies to "true". Read both shapes defensively.
const on = doc.on ?? doc["true"];

console.log(file);
console.log("  on: " + triggerNames(on).join(", "));
console.log("  permissions(workflow): " + label(doc.permissions));

for (const [jobId, job] of Object.entries(doc.jobs ?? {})) {
  const uses = (job.steps ?? []).filter((s) => s.uses).map((s) => s.uses);
  const runs = (job.steps ?? []).filter((s) => s.run).length;
  console.log("  job " + jobId + " permissions=" + label(job.permissions));
  console.log("    uses: " + (uses.length ? uses.join(", ") : "(none)"));
  console.log("    run steps: " + runs);
}
}

Run it against a fixture directory:

npm install --no-save yaml   # or add yaml as a devDependency
node tools/workflow-inventory.mjs

Expected output for a two-file fixture set (test.yml with pull_request + contents: read, and label.yml with pull_request_target and no permissions key):

label.yml
  on: pull_request_target
  permissions(workflow): inherited
  job label permissions=inherited
    uses: (none)
    run steps: 1
test.yml
  on: pull_request
  permissions(workflow): {"contents":"read"}
  job test permissions=inherited
    uses: actions/checkout@<40-char-commit-sha>
    run steps: 2

inherited is the value to chase. It is not proof of a problem. It is proof that the effective permission depends on something outside this file, which means the audit is not finished.

What the script does not do: resolve reusable workflows, read repository or organisation defaults, evaluate secrets: inherit, or tell you whether an inherited token ends up writable. Those need the GitHub API with admin access, or a human reading settings. Fixture results are local; settings-dependent answers are not.

Inspect the Dangerous Combination: Privileged Event, PR Checkout, npm Execution

The anti-pattern: pull_request_target, PR checkout, and npm execution

## DO NOT USE. Privileged event + PR checkout + package-manager execution.
name: pr-test
on:
  pull_request_target:
    types: [opened, synchronize, reopened]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<40-char-commit-sha>
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          fetch-depth: 1
      - uses: actions/setup-node@<40-char-commit-sha>
        with:
          node-version: 22.x
      - run: npm ci
      - run: npm test

No permissions: key, so the token carries the repository default, which for pull_request_target is read/write unless someone changed it. Secrets are in scope. And step 3 executes the PR's package.json.

The npm execution chain from PR diff to shell

The chain from PR to code execution inside that job is shorter than most people assume. npm ci runs the root package's prepare lifecycle script after installing dependencies (npm ci docs). prepare is an arbitrary shell command defined in package.json. A PR that adds one line to the scripts block gets execution before any test file is read, before lint, before anything you thought "test" meant.

That is not an npm bug. npm is working as documented. The bug is running the package manager on untrusted input in a privileged context.

Impact depends on the job's live capabilities

I am not going to claim what an attacker "would" get, because it depends entirely on the job's live capabilities. The honest version:

  • If GITHUB_TOKEN has contents: write, the process can push commits or move tags.
  • If packages: write, it can publish to GitHub Packages.
  • If a registry token is present as a secret, it can publish to that registry under your package name.
  • If id-token: write is set and the cloud trust policy is loose, it can assume a cloud role.
  • If the runner is self-hosted and persistent, it can leave something behind for the next job.

Each of those is a different finding needing different evidence. "This workflow is vulnerable" is not an impact assessment.

Expression injection is a separate bug

Independent of checkout, this pattern is unsafe whenever the event is PR-triggered:

## DO NOT USE
- run: echo "Checking PR ${{ github.event.pull_request.title }}"

The title is attacker-authored text and run: becomes a shell script. A title containing shell metacharacters changes the command, not just the argument. The fix is to stop treating GitHub expression results as source code:

- name: Echo PR title safely
  env:
    PR_TITLE: ${{ github.event.pull_request.title }}
  run: |
    set -euo pipefail
    printf '%s\n' "$PR_TITLE"

Passing through env moves the value into the process environment; printf '%s' plus correct quoting keeps it data. Do this even in metadata-only jobs. It costs nothing and removes a whole bug class.

Demonstrate npm Execution Boundaries in a Local, Credential-Free Lab

Before changing any workflow, I want a local demo of why the privileged checkout is the problem. No GitHub, no credentials, no network.

The local npm lifecycle fixture

Five files in one directory.

package.json:

{
  "name": "npm-ci-lab",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "prepare": "node scripts/marker.mjs",
    "test": "node test.js"
  }
}

package-lock.json (zero dependencies — generate with npm install --package-lock-only if yours differs):

{
  "name": "npm-ci-lab",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-ci-lab",
      "version": "1.0.0"
    }
  }
}

scripts/marker.mjs — the harmless "lifecycle marker." It writes a file and prints. No network, no environment reads beyond the event name, no side effects outside the directory:



const event = process.env.npm_lifecycle_event ?? "unknown";
appendFileSync("lifecycle.log", event + "\n");
console.log("LIFECYCLE:" + event);

test.js:

console.log("TEST_RAN pid=" + process.pid);

.npmrc:

audit=false
fund=false
update-notifier=false

The .npmrc is there to keep output stable and to prove a point later: .npmrc is contributor-controlled in a PR too.

Run 1 — plain npm ci

npm ci --foreground-scripts
cat lifecycle.log

Expected output (the trailing summary and timing line varies by npm version, so I have kept only the lines that carry the finding):

> [email protected] prepare
> node scripts/marker.mjs

LIFECYCLE:prepare
lifecycle.log        <- from cat: contains the single line "prepare"

Two things to notice. First, prepare ran. Second, --foreground-scripts was necessary to see it — npm 7+ hides lifecycle output by default, which is exactly why people do not realise their install step is executing PR code.

Run 2 — --ignore-scripts, then explicit test

rm -f lifecycle.log
npm ci --ignore-scripts
ls lifecycle.log        # expected: "No such file or directory"
npm test

Expected output:

npm error code ENOENT            <- from ls, no marker was written
TEST_RAN pid=48213               <- from npm test

The marker file was never created: --ignore-scripts suppressed prepare. Then npm test ran node test.js and executed code anyway.

⚠️

--ignore-scripts reduces the number of execution points. It does not create a trust boundary. Any later npm test, npm run build, or node ./dist/index.js in the same job is still arbitrary code execution from the same untrusted tree.

The reproducibility boundary

A lockfile constrains dependency resolution. It does not constrain your own scripts, and it does not constrain a dependency's postinstall. npm ci refuses to run when package.json and the lockfile disagree, but that is a consistency check, not a security control — an attacker editing both files together satisfies it trivially.

So the lab's conclusion is narrow and firm: script suppression and lockfile integrity are hygiene. Isolation is the control. The only reliable way to run untrusted install code is in a job with nothing worth taking.

Replace the Fork Test Job With an Explicitly Unprivileged Workflow

This is the workflow I actually want for fork PRs. Complete file:

name: fork-pr-test

on:
  pull_request:
    branches: [main]
    types: [opened, synchronize, reopened]

permissions:
  contents: read

concurrency:
  group: pr-test-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  test:
    name: node ${{ matrix.node }}
    runs-on: ubuntu-latest
    timeout-minutes: 15
    strategy:
      fail-fast: false
      matrix:
        node: ["22.x", "24.x"]
    steps:
      - name: Check out the PR merge commit
        uses: actions/checkout@<40-char-commit-sha> # v4.2.2
        with:
          persist-credentials: false

      - name: Set up Node.js
        uses: actions/setup-node@<40-char-commit-sha> # v4.1.0
        with:
          node-version: ${{ matrix.node }}

      - name: Install
        run: npm ci

      - name: Test
        run: npm test --if-present

Why each choice is there:

  • pull_request, not pull_request_target. The workflow definition comes from main, so a PR cannot rewrite its own test harness, and fork restrictions apply by default.
  • permissions: contents: read. Explicit, so the audit does not depend on a repository setting. If the org default is read/write, this block overrides it.
  • persist-credentials: false. With limits — see below.
  • GitHub-hosted runner. Ephemeral per job, no persistence between fork PRs.
  • No cache: on setup-node, no artifact upload. The job's only output is a pass/fail status. I add caching later, and only after auditing the scope rules.
  • No secrets referenced at all. Not "secrets guarded by an if" — absent.

On pinning to full commit SHAs

uses: actions/checkout@v4 resolves a mutable tag, and whoever controls that tag's target controls code that runs with your GITHUB_TOKEN. GitHub's hardening guidance says pin to a full commit SHA, and I agree. Do not copy a SHA out of a blog post, including this one. Resolve it yourself and keep the human-readable version in a trailing comment so reviewers can follow along:

## Resolve a tag to the commit it points at, then pin that
gh api repos/actions/checkout/commits/v4.2.2 --jq .sha
gh api repos/actions/setup-node/commits/v4.1.0 --jq .sha

Then in YAML:

- uses: actions/checkout@<paste-the-40-hex-characters-here> # v4.2.2

Keep pins current with Dependabot's github-actions ecosystem. It understands the # v4.2.2 comment convention and will open PRs that bump the SHA and the comment together. Those Dependabot PRs run under fork-equivalent restrictions, which is fine for a workflow that needs no secrets.

Preserve useful contributor checks

Running npm ci and npm test on PR code is correct here. The job is built to have nothing to lose: read-only token, no secrets, ephemeral runner, no persistent Git credentials, no cache write, no artifact upload, no network egress into your infrastructure. Under those conditions, executing untrusted code is the job's entire purpose.

The design rule I use: the untrusted job should be unable to produce a durable side effect even if the code it runs is hostile. If you cannot state that sentence about a job, the job is not ready.

The limits of persist-credentials: false

This flag is worth understanding precisely, because it gets oversold. By default actions/checkout writes the job token into the local Git config as an extraheader authorization value so later git commands work. persist-credentials: false stops that (checkout docs).

What it does not do:

  • revoke the token — it stays valid for the job's lifetime;
  • remove github.token from the expression context — any step can still reach ${{ github.token }} or ${{ secrets.GITHUB_TOKEN }} through gh, git, or curl;
  • reduce permissions — that is the permissions block's job.

So it defends against accidental credential leakage into a working tree that a hostile postinstall could read. It is not a capability reduction. Use it, but do not count it as the boundary. The boundary is permissions, plus absence of secrets, plus ephemerality.

Audit GITHUB_TOKEN as an Effective Capability, Not an Environment Variable

Derive the effective value

The token's effective permissions are the intersection of four things:

  1. Repository default (Settings → Actions → General → Workflow permissions), or the organisation-level default.
  2. Workflow-level permissions.
  3. Job-level permissions, which override the workflow level for that job.
  4. Event-specific restrictions — most notably read-only for pull_request from forks, subject to the repository setting mentioned earlier.

Only items 2 and 3 live in your repository's files. Items 1 and 4 live in settings you have to go look up. That asymmetry is why "we set permissions in the workflow" is not by itself an answer.

The permissions rule that surprises people

Supply a permissions map with any keys and every unspecified permission is set to none. So:

permissions:
  contents: read

does not mean "contents read, plus whatever the default was for everything else." It means "contents read, nothing else." That is the behaviour you want, and it is why I start every workflow with an explicit block instead of adding keys to a default.

permissions: {} means no permissions at all. read-all and write-all exist, but I would reject them in review: they document intent poorly and survive refactors too easily.

Audit credentials separately from GITHUB_TOKEN

GITHUB_TOKEN is one credential. These are separate:

CredentialWhere it livesReduced by tightening GITHUB_TOKEN?
GITHUB_TOKENMinted per jobYes
Repository secretsSettings → Secrets → ActionsNo
Environment secretsBehind environment protectionNo — and only released after the gate
GitHub App installation tokenactions/create-github-app-tokenNo
Personal access tokenRepository/org secretNo
OIDC cloud credentialid-token: writeNo — different permission

I have seen a review conclude "token permissions are minimal" while the same job consumed a PAT with repo scope from secrets.ADMIN_PAT. The token was minimal. The job was not.

Capability table for the fork test, label, and publish jobs

JobEventExecutes PR codeToken permissionsSecretsNotes
testpull_request (fork)Yescontents: readnoneEphemeral, no cache, no artifacts
labelpull_request_targetNopull-requests: write onlynoneMetadata only, never checks out PR head
publishpush tagNo (trusted tag)contents: write, id-token: writeenv secretEnvironment gate + ref validation

The comparison that matters: publish may have id-token: write and a registry token, while test must not. contents: write belongs only where something actually has to write content. Packaging and provenance belong only to publish. Neither permission has any business appearing in the fork test job.

Keep Privileged Automation Separate From Contributor Code

A metadata-only PR labeling workflow with pull_request_target

name: pr-label

on:
  pull_request_target:
    types: [opened, reopened]

permissions:
  pull-requests: write

jobs:
  label:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - name: Label docs-only PRs
        env:
          GH_TOKEN: ${{ github.token }}
          REPO: ${{ github.repository }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          set -euo pipefail
          case "$PR_NUMBER" in
            ''|*[!0-9]*) echo "unexpected PR number"; exit 1 ;;
          esac

          changed=$(gh api "repos/$REPO/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename')
          if [ -n "$changed" ] && ! printf '%s\n' "$changed" | grep -qvE '^(docs/|.*\.md$)'; then
            gh api -X POST "repos/$REPO/issues/$PR_NUMBER/labels" -f labels[]=docs-only
          fi

How it is built:

  • pull_request_target, no checkout. There is no actions/checkout step at all, so nothing from the PR touches the filesystem.
  • pull-requests: write only. GitHub's own documentation uses "add a label to a pull request" as the example for this permission; everything else is none by virtue of the map.
  • The PR number is validated with a case pattern before it gets near a command. It arrives from the event payload as a number, but treating it as data costs one line.
  • The file list comes from the API, not the working tree, so the PR's content never has to be trusted.

Treat PR metadata as data, not executable configuration

The labeling job is safe because those values are never evaluated. Keep it that way. Do not do this:

## DO NOT USE — a PR title becomes a shell command
- run: gh api -X POST "repos/$REPO/issues/$PR_NUMBER/labels" -f labels[]=${{ github.event.pull_request.title }}

Do not build if: conditions by string-concatenating PR text either. And never let a PR-supplied label name drive a runs-on: value, an environment name, or a reusable workflow uses:. Those are executable configuration, not data.

Put npm releases behind a distinct, environment-gated trigger

name: publish

on:
  push:
    tags: ["v[0-9]+.[0-9]+.[0-9]+"]

permissions:
  contents: read

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: npm-publish
    permissions:
      contents: write
      id-token: write
    steps:
      - name: Validate the release ref
        env:
          REF: ${{ github.ref }}
          DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
        run: |
          set -euo pipefail
          case "$REF" in
            refs/tags/v[0-9]*.[0-9]*.[0-9]*) ;;
            *) echo "not a release tag: $REF"; exit 1 ;;
          esac

      - uses: actions/checkout@<40-char-commit-sha> # v4.2.2
        with:
          persist-credentials: false

      - uses: actions/setup-node@<40-char-commit-sha> # v4.1.0
        with:
          node-version: 22.x
          registry-url: https://registry.npmjs.org

      - run: npm ci --ignore-scripts
      - run: npm test --if-present
      - run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

id-token: write is what unlocks --provenance (OIDC-signed attestation). If your registry supports short-lived OIDC-based publishing, you can drop the long-lived NPM_TOKEN entirely — but check the registry's own docs before removing it, since that flow has changed more than once.

The environment: npm-publish reference is the actual gate: required reviewers, and environment secrets released only after approval. Note that ref validation runs before anything is installed, so a mistyped or attacker-influenced tag fails fast.

Maintainer approval is a gate, not a sandbox

The "Require approval for fork pull request workflows" setting is genuinely useful. It stops drive-by PRs from burning runner minutes and gives a human a look before code executes.

Be precise about what it does not do. Approving a fork PR run does not grant it secrets, and it does not grant a write token. The run still executes in the fork-PR context with read-only credentials. Approval gates whether untrusted code runs; it does not change what that code can reach. Treating "a maintainer clicked approve" as a security boundary invites the next mistake, where someone decides the approved job can therefore be trusted with a token.

Close the Less Obvious Paths Through Artifacts, Caches, and Runners

workflow_run consumers inherit base-branch privilege

A downstream workflow triggered by workflow_run inherits privilege the upstream run did not have. Before touching any upstream output, check the association:

- name: Refuse anything that is not a PR run from this repo
  if: >
    github.event.workflow_run.event != 'pull_request' ||
    github.event.workflow_run.head_repository.full_name != github.repository
  run: |
    echo "unexpected upstream: ${{ github.event.workflow_run.event }} / ${{ github.event.workflow_run.head_repository.full_name }}"
    exit 1

That check matters. Without it, a fork can trigger the upstream workflow and, depending on trigger configuration, cause a downstream privileged run. head_repository.full_name is on the workflow_run payload precisely so you can make this comparison.

But here is the part people skip: a passing provenance check does not make the artifact safe. It tells you the artifact came from a PR in your repository. The bytes inside were still produced by executing that PR's code, in a job whose only defence was having nothing valuable. If the downstream job downloads that artifact and runs node dist/bundle.js on it, you just handed the untrusted bytes the privileged job. Attestation is not sanitisation.

If you must consume upstream output in a privileged job, consume it as data: read JSON, validate its shape and size, and never execute it.

Treat artifacts from untrusted runs as untrusted input

Rules I apply:

  • Validate the archive before extracting. Reject absolute paths and .. segments; extract into a fresh directory, not over the workspace.
  • Never chmod +x and run something from an artifact.
  • Never let an untrusted build feed a publish step. A release workflow that downloads an artifact built by a fork PR run is a laundering machine.
  • Cap artifact size and retention, and treat name collisions as suspicious rather than convenient.

Audit cache scope before claiming cache poisoning

Cache poisoning gets asserted more often than it gets verified. Before writing it up as a finding, pin down three things from GitHub's cache documentation and your own workflow:

  1. Scope. Caches are keyed by branch/ref context. A cache written by a PR run is scoped to that PR's merge ref, and the default branch generally cannot restore it. So the classic "fork PR poisons the main build cache" story usually needs a scope mistake or a shared key, not just a fork PR.
  2. Key construction. key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} is content-addressed. An attacker changing the lockfile gets a different key, poisoning a key nobody else restores. That is safer than it looks.
  3. restore-keys. This is where the risk actually lives. restore-keys: ${{ runner.os }}-node- falls back to prefix matching, so a run can restore some other ref's cache. A prefix restore that crosses a trust boundary is a real finding; a hash-based exact key usually is not.

The audit output should read like: "PR runs can restore caches from main via prefix linux-node-, and the restored cache contains node_modules, which is executed on install." That is actionable. "Caches can be poisoned" is not.

Self-hosted runners and fork PR isolation

GitHub's own guidance is to avoid self-hosted runners for public repositories, and I would go further: any untrusted-PR workload on a persistent self-hosted runner is a finding, private repositories with many contributors included.

If you need self-hosted capacity for the untrusted job, the minimum bar is an ephemeral runner per job (destroyed after one job), no ambient cloud credentials on the host, egress restricted to the registry and package mirrors you actually need, and a deliberate decision about cache directories — a shared ~/.npm across trust levels is a shared execution surface.

Verify the Refactor With Positive and Negative Checks

Positive checks: the fork PR workflow still does its job

Run this matrix on a real fork PR. Throwaway repo, your own account, your own fork.

CheckExpectedWhere you see it
Tests run on a fork PRWorkflow starts without manual approval (if settings allow)Actions tab
prepare marker presentLIFECYCLE:prepare in install logsJob log
npm test runsTEST_RAN in test logsJob log
No secretsNo secrets.* references in the jobWorkflow file + log
Token is read-onlyA write attempt returns 403Canary step
Labeling still happensdocs-only label appliedPR page
Labeling did not run PR codeNo checkout step in the label job logJob log

The canary: a live GITHUB_TOKEN permission-denial check

Only do this on a disposable repository, and only once per configuration. A negative result here is real evidence; a positive result means something is wrong.

- name: Canary — assert the token cannot write
  env:
    GH_TOKEN: ${{ github.token }}
  run: |
    set -uo pipefail
    out=$(gh api -X POST "repos/$GITHUB_REPOSITORY/git/refs" \
      -f ref="refs/heads/canary-$GITHUB_RUN_ID" \
      -f sha="$GITHUB_SHA" 2>&1) && code=0 || code=$?
    echo "exit=$code"
    printf '%s\n' "$out"
    if [ "$code" -eq 0 ]; then
      echo "::error::token unexpectedly allowed a ref write"
      # clean up immediately
      gh api -X DELETE "repos/$GITHUB_REPOSITORY/git/refs/heads/canary-$GITHUB_RUN_ID" || true
      exit 1
    fi

Expected on a fork pull_request run with contents: read:

exit=1
gh: Resource not accessible by integration (HTTP 403)

403 Resource not accessible by integration is what GitHub returns for an installation token that lacks the permission. If you instead see a 422 about an invalid SHA, your sha input was wrong. Fix the canary before drawing conclusions about the token.

Settings-dependent claims local testing cannot settle

Be honest about these in your write-up. No local run and no fixture tells you:

  • the repository or organisation default workflow permission;
  • whether "send write tokens to workflows from pull requests" is enabled;
  • which environments exist, what their reviewers and branch/tag restrictions are, and which secrets they hold;
  • whether a reusable workflow elsewhere in the org calls yours with secrets: inherit;
  • whether self-hosted runners are reachable from public forks.

Record how you checked each one, in text rather than screenshots: Settings → Actions → General → Workflow permissions: Read repository contents permission, or the equivalent API call.

Regression checks for GitHub Actions patterns that keep coming back

Automated warnings catch regressions in review. The important framing: a match is a warning, not a verdict. Encode that in the output so nobody treats the check as a scanner.

PatternWhy it is only a warning
pull_request_target presentLegitimate for metadata-only jobs
pull_request_target + actions/checkout in same workflowStill safe if the checkout pins a base ref, not the PR head
ref: ${{ github.event.pull_request.head.High-signal, but a checkout in an unprivileged job is fine
Workflow file with no top-level permissions:Effective value may already be read-only via repo default
${{ github.event.pull_request. inside a run: blockSometimes it is a hardcoded safe field; needs a human read
uses: ./.github/ in a privileged jobFine when the privileged job never checks out PR code

Given the multiline problem, a workable check is to grep for run: blocks containing pull_request. or github.event.issue, then read each hit:

## Print file:line for every run-step line containing PR-controlled event data.
## Follow up by reading the surrounding block; do not treat hits as confirmed bugs.
grep -rn -E '\$\{\{[^}]*github\.event\.(pull_request|issue)' .github/workflows

I keep this in tools/check-workflows.sh, run it in the untrusted test job, and work from a personal follow-up list rather than a pass/fail gate. Any gate that fails on a false positive gets disabled within a month.

Conclusion: Remove Privilege From the Execution Path, Not Contributors From CI

The acceptance criteria I would hold a refactor to:

  1. Fork PR tests still run. npm ci and npm test execute on PR content, deliberately, in a job with contents: read, no secrets, no cache write, no artifacts, and a GitHub-hosted runner.
  2. No privileged job executes contributor code. pull_request_target jobs never check out the PR head. workflow_run consumers never execute upstream artifacts. Local actions never appear in a job that has checked out a PR merge ref.
  3. Credentials stay narrow and separate. GITHUB_TOKEN permissions are declared per workflow and per job; registry tokens and id-token: write live only behind a gated environment; PATs and App tokens get audited as the distinct capabilities they are.
  4. Downstream consumers preserve the boundary. Artifacts are read as data, cache scope is documented rather than assumed, and no untrusted build feeds a publish step.
  5. The invariants are tested, not asserted. A canary 403, a fixture run of the inventory script, and an --ignore-scripts negative test live in the repository.

So, taking a position: in most JavaScript repositories the "dangerous trigger" was never the whole problem, and deleting pull_request_target outright is a worse outcome than keeping an unprivileged fork test path alongside a narrowly scoped metadata path. The capability you want is tests that run on untrusted code with nothing to lose, and that needs an explicit permission model rather than a lucky default.

The PSF report carries the same limits it had at the start. The supplied news item, dated November 23, 2026, reports that the foundation removed dangerous GitHub Actions triggers across its organizations. It names no repositories, no specific triggers, no workflow revisions, and no exploited vulnerability. I take it as evidence that someone ran this audit at organisational scale, not as evidence about which patterns they found. The trigger inventory and the capability table are work you have to do in your own repositories, and the commands above are the cheapest way I know to start.

Further Reading and Verification Sources

Share this post

More posts

Loading comments…