CI/CD security: who can run your pipeline, what each job can reach, and how a deployer checks what it ships
A CI/CD pipeline holds the keys to production: a repository token, cloud credentials and the right to deploy without anyone touching a server.
This guide explains who and what can make yours run, what each job and each third-party action can reach once it does, and what an approval, a short-lived identity and an attested artefact each prove. GitHub Actions is the worked example, with GitLab CI/CD as a section of its own. It comes with a pipeline trust map, a six-part threat test pack, a sample least-privilege workflow and a local checker you can run against your own workflow files.
In this guide
Pipeline trust map, threat test pack and least-privilege workflow
Part A maps eight actors and stages in a GitHub Actions pipeline to what each is trusted to do, what it can reach and the control that limits it, with a source for each control or a note that it is this page's advice. Part B is a threat test pack for untrusted pull requests, third-party actions, build secrets, artefact signing, environment approvals and deployment identity, each with steps you run in your own repository, a passing result and what a failure means.
How to use itHide the instructions
Part C is a sample workflow with permissions declared at workflow and job level, and Part D is a local checker with a regression test, shown with its real output. Every owner, action and commit SHA in it is invented.
cicd-security.txt
Introduction9 lines
Part A: Pipeline trust map65 lines
Part B: Threat test pack59 lines
Part C: Sample least-privilege permission set (careful.yml)78 lines
Part D: Local lab, a workflow checker (illustration)647 lines
Whole template882 lines
ILLUSTRATION ONLY. The repository, the owner example-owner, the action cloud-deploy-action, the environment production and every 40-character commit SHA in this asset are invented for this page. They are not a client's pipeline. The tests in Part B are for repositories you own, using a test secret that unlocks nothing.
What is here:
Part A Pipeline trust map: who and what is trusted to do what, what each can reach, and the control that limits it, with the source behind each control or a note that it is this page's advice.
Part B Threat test pack: one test for each of untrusted pull requests, third-party actions, build secrets, artefact signing, environment approvals and deployment identity.
Part C Sample least-privilege permission set: a complete GitHub Actions workflow with permissions at workflow and job level.
Part D Local lab: a workflow checker and a regression test that run with Node.js alone, with their real output.
GitHub Actions is the worked platform throughout. Settings named here are as GitHub's documentation described them on 14 November 2026.
================================================================
PART A: PIPELINE TRUST MAP
================================================================
Each row lists what the actor or stage is trusted to do, what it can reach, and the controls that limit it. "Source" names the document a control comes from. "This page's advice" marks a control the page recommends without a document behind it.
A1. A CONTRIBUTOR'S PULL REQUEST FROM A FORK
Trusted to: propose a change for someone to review. Nothing in it has been reviewed yet.
Can reach: On pull_request, GitHub runs the workflow file from the pull request's merge commit with a read-only GITHUB_TOKEN and no secrets other than that token. Source: GitHub, Securely using pull_request_target; Events that trigger workflows.
On a private repository whose settings send write tokens or secrets to workflows from fork pull requests, it gets those as well. Source: GitHub, Managing GitHub Actions settings for a repository.
On pull_request_target, the job holds the base repository's secrets and a token with read/write repository permission, so any step that runs the pull request's code hands them to its author. Source: GitHub, Securely using pull_request_target; Workflow syntax.
Limited by: 1. Approval before workflows run for outside contributors; "Require approval for all external contributors" is the strictest setting. For outside contributors' pull requests to public repositories, NIST SP 800-204D (PULL-PUSH-REQ-3) asks for either sandboxed runs with no network access, privileged access or secrets, or this approval at its strictest level. Source: GitHub, repository settings; NIST SP 800-204D.
2. pull_request, not pull_request_target, for anything that builds or tests the change, and no pull request code run in a pull_request_target, issue_comment or workflow_run workflow. Source: GitHub, Securely using pull_request_target.
3. On a private repository, the options that send write tokens and secrets to fork pull requests left off. This page's advice.
A2. A MAINTAINER'S PUSH TO A PROTECTED BRANCH
Trusted to: merge reviewed changes and start the release workflow.
Can reach: everything the push-triggered workflows can: the secrets they name, the token permissions they declare and, through the deploy job, production. A change to a workflow file, or to a file it calls, changes what the pipeline does with all of that. Source: OWASP CICD-SEC-4.
Limited by: 1. Review by someone other than the author before merging. NIST SP 800-204D says developers with merge approval permissions cannot approve their own merges.
2. .github/workflows listed in CODEOWNERS, so changes to workflow files need a designated reviewer. Source: GitHub, Secure use reference.
3. An environment approval on the deploy job (row A8).
4. No single account able to push code or artefacts through to production without another approval or review. Source: OWASP CICD-SEC-1.
A3. THIRD-PARTY ACTIONS
Trusted to: do the one task its step names.
Can reach: whatever its job can: the GITHUB_TOKEN through the github.token context even if the workflow never passes it, plus the job's files, network access and secrets. GitHub says a compromised action would have access to all secrets configured on the repository and may be able to use the GITHUB_TOKEN to write to it. Source: GitHub, Use GITHUB_TOKEN for authentication in workflows; Secure use reference.
Limited by: 1. A workflow dependency lockfile, or a full-length commit SHA taken from the action's own repository and not a fork. Source: GitHub, Workflow dependency lockfiles; Using pre-written building blocks in your workflow.
2. The action's source code audited, whatever other measures are in place. Source: GitHub, Secure use reference. Doing it before a pin is set or moved is this page's advice.
3. Job-level permissions limited to what the job uses. Source: GitHub, Workflow syntax.
4. No third-party action in a job that holds deployment secrets or write scopes it does not use. This page's advice.
A4. THE RUNNER
Trusted to: execute the steps of one job.
Can reach: everything placed in the job and, on a self-hosted runner, whatever else that machine and its network can reach. GitHub says jobs in one workflow can interact with and compromise each other. Source: GitHub, Secure use reference.
Limited by: 1. GitHub-hosted runners for untrusted code. This page's advice, because GitHub notes that self-hosted runners do not run jobs in an isolated container even when they use environments, and that fork pull request code runs on them automatically once approved, or when its author may bypass approval. Source: GitHub, Deployments and environments; repository settings.
2. The execution node reverted to its pristine state after each run, and no shared node for pipelines with different levels of sensitivity. Source: OWASP CICD-SEC-5.
A5. BUILD SECRETS
Trusted to: authenticate one step to one service.
Can reach: whatever the credential allows, for as long as it stays valid, from every job the workflow passes it to.
Limited by: 1. A secret reaches a job only if the workflow includes it. Source: GitHub, Secrets.
2. Credentials that can change production stored as environment secrets, released only to jobs that reference the environment and only after one of its required reviewers approves. Source: GitHub, Deployments and environments.
3. Secrets scoped so each pipeline and step gets only what it requires, and package install scripts run in a context without secrets. Source: OWASP CICD-SEC-5.
4. Least privilege for access to secret assets, and no secrets in source code or build artefacts. Source: OWASP ASVS 5.0 requirements 13.3.2 and 13.3.1.
5. Temporary credentials preferred over static ones. Source: OWASP CICD-SEC-6.
A6. THE ARTEFACT STORE
Trusted to: hold what the build produced, unchanged, until it is deployed.
Can reach: production, indirectly: whatever is in it when the deploy job reads it is what gets deployed. OWASP describes an attacker with access to one system in the pipeline pushing a malicious but seemingly benign artefact down it. Source: OWASP CICD-SEC-9.
Limited by: 1. An attestation created at build time and verified before deployment. Source: GitHub, Artifact attestations; OWASP CICD-SEC-9.
2. Only artefacts generated by the established build process cleared for deployment. Source: NIST SP 800-204D (DEPLOY-REQ-3), which states it for container images.
3. The same artefact promoted between environments rather than rebuilt for each. Source: OWASP Top 10:2025 A03.
A7. THE DEPLOYMENT IDENTITY
Trusted to: change production for this repository's deploy job, and nothing else.
Can reach: whatever the cloud role, registry token or hosting credential allows.
Limited by: 1. OpenID Connect: a short-lived token valid for a single job instead of a long-lived credential stored as a secret. Source: GitHub, OpenID Connect.
2. At least one trust condition on the cloud role, with the subject naming the repository and the production environment. Source: GitHub, OpenID Connect reference.
3. id-token: write granted only in the jobs that request a token. This page's advice; the permission itself is the one GitHub's OIDC reference requires.
4. For npm packages, trusted publishing in place of long-lived npm tokens. Source: npm Docs, Trusted publishing for npm packages.
A8. THE PRODUCTION ENVIRONMENT
Trusted to: hold production secrets, and hold deploy jobs until its rules pass.
Can reach: production secrets, for the jobs that reference it once its rules pass.
Limited by: 1. Required reviewers, with self-review prevented.
2. Deployment branches and tags limited to what releases.
3. Administrator bypass switched off.
Source for 1 to 3: GitHub, Deployments and environments. On GitHub's Free, Pro and Team plans, required reviewers are only available for public repositories.
4. Every environment name in a workflow matched to a configured environment, because running a workflow that names one that does not exist creates it with no protection rules. Source: GitHub, Managing environments for deployment.
================================================================
PART B: THREAT TEST PACK
================================================================
Run these in repositories you own, or in a test repository set up the same way. Where a test needs a secret, use a test secret that unlocks nothing: a repository secret named CANARY_TEST_SECRET whose value is random text that is not a password, key or token for anything. Never use a real credential to find out whether it leaks. If a test suggests a real secret may already have been exposed, stop and work through the secrets exposure guide, or call an incident response specialist.
B1. UNTRUSTED PULL REQUESTS
Question: Can code from a fork reach a secret or a write token, or run without anyone approving it?
Steps: 1. In your repository, or a test copy of it, add CANARY_TEST_SECRET as a repository secret.
2. From a second GitHub account you control, fork the repository and open a pull request that adds one step to an existing pull_request workflow. The step maps CANARY_TEST_SECRET to an environment variable and prints only whether that variable is empty. It never prints the value.
3. Note whether the run waited for approval, and which approval setting the repository uses.
4. Read the step's output: empty or not empty.
5. Search .github/workflows for pull_request_target, issue_comment and workflow_run. In each workflow that uses one, read every step and note whether any step checks out, fetches or downloads pull request code and then runs anything from it, npm install and npm run build included. Rule 4 of the Part D checker flags the usual checkout forms.
6. On a private repository, open Settings, Actions, General and note each fork pull request workflow option.
Passing: The step reports empty. The run waited for approval if your setting covers that account. No privileged workflow runs pull request code. On a private repository, sending write tokens and secrets to fork pull requests is off.
A failure means: anyone who can open a pull request can run code with your secrets or a write token, which OWASP calls poisoned pipeline execution (CICD-SEC-4). Treat every real secret those workflows hold as possibly exposed, and fix the trigger before the next outside pull request.
B2. THIRD-PARTY ACTIONS
Question: Would a moved tag change what your workflows run, and what could each action reach if it changed?
Steps: 1. Run the Part D checker over each workflow file, or list every uses: line yourself.
2. For each reference that is not a full 40-character commit SHA, and is not covered by .github/workflows/actions.lock, write down the action and the job it runs in.
3. For each pinned SHA, open that commit in the action's own repository and confirm it is the commit behind the release you reviewed, not a commit from a fork.
4. For each third-party action, write down its job's permissions and every secret passed into that job.
Passing: Every action is locked, or pinned to a full SHA you have checked against the action's own repository. No third-party action runs in a job with deployment secrets or write scopes it does not use.
A failure means: a change upstream, such as a repointed tag, changes your build without a commit in your repository, and the changed code runs with everything its job holds. GitHub's advisory GHSA-mrrh-fwg8-r2c3 describes that happening to tj-actions/changed-files in March 2025.
B3. BUILD SECRETS
Question: Which jobs can read which secrets, and does any job hold a secret it never uses?
Steps: 1. List the names, never the values, of your organisation, repository and environment secrets.
2. For each job in each workflow, list the secrets it references and the steps that use them.
3. Mark each secret that is a long-lived cloud, hosting or registry credential.
4. In a test repository, use CANARY_TEST_SECRET in one step of one job, run the workflow, and search every job's log in that run for the canary value.
Passing: Each secret appears only in the jobs and steps that use it. Credentials that can change production are environment secrets. No long-lived credential is stored for a provider your deploy job could reach through OIDC. The canary value appears in no log.
A failure means: any step in a job that holds a secret can use it, a third-party action or an install script included. If an unredacted secret is sent to a workflow run log, GitHub's guidance is to delete the log and rotate the secret; the secrets exposure guide covers rotation.
B4. ARTEFACT SIGNING
Question: Can whoever deploys tell that an artefact came from your workflow at a known commit, and would they notice a swap?
Steps: 1. Download the artefact your most recent production deployment used.
2. Run gh attestation verify on it, with -R set to your organisation and repository.
3. Compare the repository, workflow and commit the result names with your deployment record.
4. Copy the artefact, change one byte in the copy, and run the same verification on the copy.
5. Read the deploy job and note whether it verifies before it deploys. The Part C sample does not; the note under it says why.
Passing: The original verifies and names the repository, workflow and commit you expect. The changed copy fails. Either the deploy job verifies before it deploys, or, as with the Part C sample, someone runs this test on the artefact each production deployment used and keeps the result.
A failure means: nothing ties what runs in production to your build, so an artefact swapped in the store would deploy the same way. GitHub notes that generating attestations gives no security benefit until they are verified.
B5. ENVIRONMENT APPROVALS
Question: Does the production deploy wait for someone other than the person who started it, and can anything skip the wait?
Steps: 1. In Settings, Environments, open production and note the required reviewers, whether self-review is prevented, the deployment branches and tags, and whether administrators can bypass the rules.
2. List every environment name used in .github/workflows and compare each with the configured environments, character by character.
3. In a test repository with the same environment settings, start the deploy job yourself and try to approve it.
4. In that test repository, whose deploy step only prints the environment name, push a commit that triggers the deploy workflow from a branch that should not deploy.
Passing: The job waits. You cannot approve your own run. The other branch cannot deploy. Every environment name in the workflows matches a configured environment with rules. Administrators cannot bypass them.
A failure means: the production credential is released without a second person, or a mistyped name has created an environment with no rules at all. If your plan does not offer required reviewers for a private repository, record that: a rule you cannot configure is not in force.
B6. DEPLOYMENT IDENTITY
Question: Can only the deploy job, in the production environment, obtain production access?
Steps: 1. Open the trust policy of the cloud role, or the hosting platform's equivalent, that your deploy job uses.
2. Check that it has at least one condition on the token's subject, and that the subject names your repository and the production environment, in the subject format your repository produces.
3. Note every job that has id-token: write, from rule 7 of the Part D checker or a search of .github/workflows.
4. From a test repository, and again from a branch the environment's rules do not allow to deploy, run a job with id-token: write that asks for the production role and does nothing else, such as calling the provider's who-am-I command.
5. Search your secrets for long-lived keys to the same account.
Passing: Both requests in step 4 are refused. The subject condition names the environment. id-token: write appears only in jobs that request a token. No long-lived production key remains in your secrets.
A failure means: workflows the condition was never meant to cover, possibly from another branch or repository, can obtain production access, or a stored key remains as a way around the controls.
================================================================
PART C: SAMPLE LEAST-PRIVILEGE PERMISSION SET (careful.yml)
================================================================
# careful.yml: a sample least-privilege workflow for this page's lab.
# The owner example-owner, the action cloud-deploy-action, the repository
# example-owner/example-site and every 40-character SHA below are invented.
# Replace each SHA with the full commit SHA of the release you reviewed,
# taken from the action's own repository, not from a fork.
name: build-and-deploy
on:
pull_request:
push:
branches:
- main
# Workflow level: no access. Each job below asks for only what it uses.
permissions: {}
jobs:
test:
runs-on: ubuntu-latest
permissions:
contents: read # read the repository
steps:
- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # invented SHA
- name: Report the pull request title
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "Testing $PR_TITLE"
- run: npm ci
- run: npm test
build:
if: github.event_name == 'push'
needs: test
runs-on: ubuntu-latest
permissions:
contents: read # read the repository
id-token: write # request an OIDC token for signing
attestations: write # create the attestation
steps:
- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # invented SHA
- run: npm ci
- run: npm run build
- run: tar -czf site.tar.gz dist
- uses: actions/attest@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # invented SHA
with:
subject-path: site.tar.gz
- uses: actions/upload-artifact@cccccccccccccccccccccccccccccccccccccccc # invented SHA
with:
name: site
path: site.tar.gz
deploy:
needs: build
runs-on: ubuntu-latest
environment: production
permissions:
id-token: write # request an OIDC token for the cloud role
steps:
- uses: actions/download-artifact@dddddddddddddddddddddddddddddddddddddddd # invented SHA
with:
name: site
- uses: example-owner/cloud-deploy-action@eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee # invented SHA
with:
artifact: site.tar.gz
role: production-deployer
How each part of careful.yml limits access:
- permissions: {} at the top gives no access to any job that does not declare its own. GitHub's workflow syntax sets every permission you do not specify to none once you specify any, and {} disables them all.
- test runs for pull requests, forks included, and pushes. It has contents: read and nothing else, and passes the pull request title to its script through an environment variable rather than writing it into the script.
- build runs only for pushes, which the on: block limits to main. contents: read, id-token: write and attestations: write are the permissions GitHub's attestation guide lists for attesting a binary.
- deploy references the production environment, so it waits for that environment's protection rules before it is sent to a runner, and only then receives the environment's secrets. Its one permission is id-token: write, for the OIDC token the cloud role's trust condition checks.
Before you use it:
- Every SHA is invented. Replace each one with the full commit SHA of the release you reviewed, taken from the action's own repository. If you adopt a workflow dependency lockfile, GitHub says SHA pinning in the workflow file is no longer needed for workflows onboarded to it.
- example-owner/cloud-deploy-action is invented. Use your cloud or hosting provider's own login and deploy actions, and read their documentation for the inputs and permissions they need.
- Create the production environment, with its rules, before the first run. A run that names an environment that does not exist creates one with no protection rules.
- On GitHub's Free, Pro and Team plans, required reviewers and wait timers are only available for public repositories.
- careful.yml attests the artefact but does not verify the attestation before it deploys. GitHub's attestation guides show verification with the GitHub CLI command gh attestation verify, run on the artefact with the repository named, but the pages read for this asset do not say which token permissions that command needs inside a workflow, so the sample leaves verification to you. Until you add a verify step to the deploy job, run test B4 on the artefact each production deployment used.
================================================================
PART D: LOCAL LAB, A WORKFLOW CHECKER (ILLUSTRATION)
================================================================
What this is, and what it is not. The checker reads a workflow file line by line and reports seven rules. It understands the simple shape the two sample files use: two-space indents, one key per line, block lists, no anchors. It is not a YAML parser and not a replacement for a maintained workflow linter, it does not read lockfiles or repository settings, and a file that passes it can still be unsafe in ways it does not look at.
The seven rules:
1 workflow-level permissions are declared, and are not write-all
2 each job's write scopes are declared at job level, never inherited from the workflow level or the repository default
3 every action reference is a full 40-character commit SHA (local ./ actions are skipped; docker:// images are listed as not checked)
4 a workflow triggered by pull_request_target never refers to the pull request head (head.sha, head.ref, head.repo.full_name, github.head_ref, refs/pull/, gh pr checkout or allow-unsafe-pr-checkout)
5 no run script expands a github.event or github.head_ref expression directly, which is stricter than GitHub's own list of untrusted contexts
6 each job whose id contains "deploy" names an environment
7 id-token: write is granted per job, never at workflow level or through write-all
Written and run on: Node.js v26.0.0, the only version it was run on. It imports only node:fs, node:test and node:assert and uses no npm packages. The Node.js documentation lists node:test as stable since v20.0.0. Timings in the test output will differ on your machine.
Make an empty folder, save the four files below and careful.yml from Part C into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 4: workflow-rules.mjs
================================================================
// workflow-rules.mjs: reads the text of one GitHub Actions workflow file and
// checks it against seven rules about permissions, pinning, untrusted pull
// requests, untrusted text, environments and the identity token.
// Illustration only. It reads lines, not YAML: it understands the simple shape
// this page's two sample files use (two-space indents, one key per line, block
// lists, no anchors or flow mappings). It is not a YAML parser and not a
// replacement for a maintained workflow linter.
// Built from two parts so this file never contains the expression marker itself.
const EXPRESSION_START = '$' + '{{'
const EXPRESSION_END = '}}'
// Text that points a checkout or a fetch at the pull request's own code.
const PULL_REQUEST_HEAD_MARKERS = [
'github.event.pull_request.head.sha',
'github.event.pull_request.head.ref',
'github.event.pull_request.head.repo.full_name',
'github.head_ref',
'refs/pull/',
'gh pr checkout',
'allow-unsafe-pr-checkout',
]
// Expression values a pull request author can influence. This is stricter than
// GitHub's own list: every github.event value counts.
const UNTRUSTED_EXPRESSION_PREFIXES = ['github.event.', 'github.head_ref']
const FULL_SHA_LENGTH = 40
const LOWERCASE_HEX = '0123456789abcdef'
// ---------------------------------------------------------------- reading lines
function removeComment(rawLine) {
let quote = ''
for (let index = 0; index < rawLine.length; index++) {
const character = rawLine[index]
if (quote !== '') {
if (character === quote) quote = ''
continue
}
if (character === '"' || character === "'") {
quote = character
continue
}
const startsComment = character === '#' && (index === 0 || rawLine[index - 1] === ' ')
if (startsComment) return rawLine.slice(0, index)
}
return rawLine
}
function countIndent(text) {
let count = 0
while (count < text.length && text[count] === ' ') count++
return count
}
// One entry per line that still has content once comments are removed.
function readLines(source) {
const lines = []
const rawLines = source.split('\n')
for (let index = 0; index < rawLines.length; index++) {
const text = removeComment(rawLines[index]).trimEnd()
if (text.trim() === '') continue
lines.push({ number: index + 1, text: text, indent: countIndent(text) })
}
return lines
}
// " - uses: actions/checkout@v6" gives { key: 'uses', value: 'actions/checkout@v6' }.
function splitKey(line) {
let body = line.text.trim()
if (body.startsWith('- ')) body = body.slice(2).trim()
const colon = body.indexOf(':')
if (colon === -1) return { key: '', value: body }
const afterColon = body.slice(colon + 1)
if (afterColon !== '' && !afterColon.startsWith(' ')) return { key: '', value: body }
return { key: body.slice(0, colon).trim(), value: afterColon.trim() }
}
// The lines nested under lines[index], that is every following line indented further.
function readChildren(lines, index) {
const children = []
for (let next = index + 1; next < lines.length; next++) {
if (lines[next].indent <= lines[index].indent) break
children.push(lines[next])
}
return children
}
function findTopLevelKey(lines, key) {
for (let index = 0; index < lines.length; index++) {
if (lines[index].indent === 0 && splitKey(lines[index]).key === key) return index
}
return -1
}
// ---------------------------------------------------------- reading the workflow
function readTriggers(lines) {
const index = findTopLevelKey(lines, 'on')
if (index === -1) return []
const value = splitKey(lines[index]).value
if (value !== '') {
const list = value.replace('[', '').replace(']', '')
return list.split(',').map(function (name) { return name.trim() }).filter(Boolean)
}
const children = readChildren(lines, index)
if (children.length === 0) return []
const triggerIndent = children[0].indent
const triggers = []
for (const child of children) {
if (child.indent === triggerIndent) triggers.push(splitKey(child).key || splitKey(child).value)
}
return triggers
}
// Reads a permissions key at lines[index]: {}, read-all, write-all or a block of scopes.
function readPermissions(lines, index) {
if (index === -1) return { declared: false, form: 'none declared', scopes: {}, line: 0 }
const value = splitKey(lines[index]).value
const permissions = { declared: true, form: value, scopes: {}, line: lines[index].number }
if (value === '') {
permissions.form = 'scopes'
for (const child of readChildren(lines, index)) {
const scope = splitKey(child)
permissions.scopes[scope.key] = scope.value
}
}
return permissions
}
function listWriteScopes(permissions) {
if (permissions.form === 'write-all') return ['write-all']
const writes = []
for (const scope of Object.keys(permissions.scopes)) {
if (permissions.scopes[scope] === 'write') writes.push(scope)
}
return writes
}
function grantsIdToken(permissions) {
return permissions.form === 'write-all' || permissions.scopes['id-token'] === 'write'
}
// Collects every run script in a job, as { line, text } pairs.
function readRunScripts(jobLines) {
const scripts = []
for (let index = 0; index < jobLines.length; index++) {
const entry = splitKey(jobLines[index])
if (entry.key !== 'run') continue
const isBlock = entry.value.startsWith('|') || entry.value.startsWith('>')
if (!isBlock) {
scripts.push({ line: jobLines[index].number, text: entry.value })
continue
}
for (const child of readChildren(jobLines, index)) {
scripts.push({ line: child.number, text: child.text.trim() })
}
}
return scripts
}
function readJob(id, jobLines) {
const keyIndent = jobLines.length > 0 ? jobLines[0].indent : 0
const job = { id: id, permissions: readPermissions([], -1), environment: '', uses: [], runScripts: [] }
for (let index = 0; index < jobLines.length; index++) {
const line = jobLines[index]
const entry = splitKey(line)
if (line.indent === keyIndent && entry.key === 'permissions') job.permissions = readPermissions(jobLines, index)
if (line.indent === keyIndent && entry.key === 'environment') job.environment = readEnvironmentName(jobLines, index)
if (entry.key === 'uses') job.uses.push({ line: line.number, reference: entry.value })
}
job.runScripts = readRunScripts(jobLines)
return job
}
// environment: production, or environment: with a nested name: production.
function readEnvironmentName(jobLines, index) {
const value = splitKey(jobLines[index]).value
if (value !== '') return value
for (const child of readChildren(jobLines, index)) {
if (splitKey(child).key === 'name') return splitKey(child).value
}
return '(unnamed)'
}
function readJobs(lines) {
const index = findTopLevelKey(lines, 'jobs')
if (index === -1) return []
const children = readChildren(lines, index)
if (children.length === 0) return []
const jobIndent = children[0].indent
const jobs = []
let currentId = ''
let currentLines = []
for (const child of children) {
if (child.indent === jobIndent) {
if (currentId !== '') jobs.push(readJob(currentId, currentLines))
currentId = splitKey(child).key
currentLines = []
} else {
currentLines.push(child)
}
}
if (currentId !== '') jobs.push(readJob(currentId, currentLines))
return jobs
}
export function readWorkflow(source) {
const lines = readLines(source)
return {
lines: lines,
triggers: readTriggers(lines),
permissions: readPermissions(lines, findTopLevelKey(lines, 'permissions')),
jobs: readJobs(lines),
}
}
// ---------------------------------------------------------------------- helpers
function isFullSha(ref) {
if (ref.length !== FULL_SHA_LENGTH) return false
for (const character of ref) {
if (!LOWERCASE_HEX.includes(character)) return false
}
return true
}
function listExpressions(text) {
const expressions = []
let start = text.indexOf(EXPRESSION_START)
while (start !== -1) {
const end = text.indexOf(EXPRESSION_END, start + EXPRESSION_START.length)
if (end === -1) break
expressions.push(text.slice(start + EXPRESSION_START.length, end).trim())
start = text.indexOf(EXPRESSION_START, end + EXPRESSION_END.length)
}
return expressions
}
function isUntrusted(expression) {
return UNTRUSTED_EXPRESSION_PREFIXES.some(function (prefix) { return expression.includes(prefix) })
}
function describeScopes(permissions) {
if (permissions.form !== 'scopes') return permissions.form
const parts = Object.keys(permissions.scopes).map(function (scope) { return scope + ': ' + permissions.scopes[scope] })
return parts.length > 0 ? parts.join(', ') : 'no scopes'
}
function makeResult(number, title, failures, passes) {
if (failures.length > 0) return { number: number, title: title, status: 'FAIL', details: failures }
return { number: number, title: title, status: 'PASS', details: passes }
}
// ------------------------------------------------------------------- the rules
function checkWorkflowPermissions(workflow) {
const title = 'Workflow-level permissions are declared'
const permissions = workflow.permissions
if (!permissions.declared) {
const reason = 'no top-level permissions key, so each job without its own starts from the repository or organisation default'
return makeResult(1, title, [reason], [])
}
if (permissions.form === 'write-all') return makeResult(1, title, ['line ' + permissions.line + ': write-all for every job'], [])
return makeResult(1, title, [], ['line ' + permissions.line + ': ' + describeScopes(permissions)])
}
function checkJobWriteScopes(workflow) {
const failures = []
const passes = []
for (const job of workflow.jobs) {
const fromJob = job.permissions.declared
const effective = fromJob ? job.permissions : workflow.permissions
if (!effective.declared) {
failures.push(job.id + ': no permissions at job or workflow level, so the default applies')
continue
}
const writes = listWriteScopes(effective)
const where = fromJob ? 'job level' : 'inherited from workflow level'
if (writes.includes('write-all')) {
failures.push(job.id + ': write-all (' + where + ')')
} else if (writes.length > 0 && !fromJob) {
failures.push(job.id + ': ' + writes.join(', ') + ' (' + where + ')')
} else {
passes.push(job.id + ': ' + (writes.length > 0 ? writes.join(', ') : 'none') + ' (' + where + ')')
}
}
return makeResult(2, 'Write scopes are granted per job, never inherited', failures, passes)
}
function checkPinnedActions(workflow) {
const failures = []
const notes = []
let checked = 0
for (const job of workflow.jobs) {
for (const use of job.uses) {
if (use.reference.startsWith('./')) continue
if (use.reference.startsWith('docker://')) {
notes.push('line ' + use.line + ': container image reference, not checked')
continue
}
checked++
const ref = use.reference.slice(use.reference.lastIndexOf('@') + 1)
if (!isFullSha(ref)) failures.push('line ' + use.line + ': ' + use.reference)
}
}
const summary = (checked - failures.length) + ' of ' + checked + ' action references pinned to a full-length commit SHA'
const failuresWithSummary = failures.length > 0 ? [summary].concat(failures) : []
return makeResult(3, 'Every action is pinned to a full-length commit SHA', failuresWithSummary, [summary].concat(notes))
}
function checkPullRequestTarget(workflow) {
const title = 'A pull_request_target workflow does not fetch the pull request head'
if (!workflow.triggers.includes('pull_request_target')) {
return { number: 4, title: title, status: 'N/A', details: ['not triggered by pull_request_target'] }
}
const failures = []
for (const line of workflow.lines) {
for (const marker of PULL_REQUEST_HEAD_MARKERS) {
if (line.text.includes(marker)) failures.push('line ' + line.number + ': ' + marker)
}
}
if (failures.length > 0) failures.unshift('triggered by pull_request_target, and these lines point at pull request code:')
return makeResult(4, title, failures, ['triggered by pull_request_target; no line points at the pull request head'])
}
function checkUntrustedTextInRun(workflow) {
const failures = []
let scriptLines = 0
for (const job of workflow.jobs) {
for (const script of job.runScripts) {
scriptLines++
for (const expression of listExpressions(script.text)) {
if (isUntrusted(expression)) failures.push('line ' + script.line + ' (' + job.id + '): ' + expression + ' is expanded inside the script')
}
}
}
const passes = [scriptLines + ' run script lines read; none expands a github.event or github.head_ref value']
return makeResult(5, 'No untrusted expression sits directly inside a run script', failures, passes)
}
function checkDeployEnvironment(workflow) {
const title = 'The deploy job names an environment'
const deployJobs = workflow.jobs.filter(function (job) { return job.id.includes('deploy') })
if (deployJobs.length === 0) return { number: 6, title: title, status: 'N/A', details: ['no job id contains "deploy"'] }
const failures = []
const passes = []
for (const job of deployJobs) {
if (job.environment === '') failures.push(job.id + ': no environment')
else passes.push(job.id + ': environment ' + job.environment)
}
return makeResult(6, title, failures, passes)
}
function checkIdentityToken(workflow) {
const failures = []
const passes = []
if (workflow.permissions.declared && grantsIdToken(workflow.permissions)) {
failures.push('workflow level (line ' + workflow.permissions.line + '): reaches every job without its own permissions')
}
for (const job of workflow.jobs) {
if (!job.permissions.declared || !grantsIdToken(job.permissions)) continue
const environment = job.environment === '' ? 'no environment' : 'environment ' + job.environment
if (job.permissions.form === 'write-all') failures.push(job.id + ': through write-all, ' + environment)
else passes.push(job.id + ': job level, ' + environment)
}
if (failures.length === 0 && passes.length === 0) passes.push('not granted anywhere in this file')
return makeResult(7, 'The identity-token permission is granted per job, never workflow-wide or through write-all', failures, passes)
}
export function checkWorkflow(source) {
const workflow = readWorkflow(source)
return [
checkWorkflowPermissions(workflow),
checkJobWriteScopes(workflow),
checkPinnedActions(workflow),
checkPullRequestTarget(workflow),
checkUntrustedTextInRun(workflow),
checkDeployEnvironment(workflow),
checkIdentityToken(workflow),
]
}
================================================================
FILE 2 OF 4: check-workflow.mjs
================================================================
// check-workflow.mjs: prints the seven rule results for one workflow file.
// Usage: node check-workflow.mjs careless.yml
// It sets exit code 1 when any rule fails, for pipeline steps that stop on a non-zero code.
// Illustration only; see the note at the top of workflow-rules.mjs.
import { readFileSync } from 'node:fs'
import { checkWorkflow, readWorkflow } from './workflow-rules.mjs'
const fileName = process.argv[2]
if (!fileName) {
console.error('Usage: node check-workflow.mjs path/to/workflow.yml')
process.exit(2)
}
const source = readFileSync(fileName, 'utf8')
const workflow = readWorkflow(source)
const results = checkWorkflow(source)
console.log('Workflow: ' + fileName)
console.log('Triggers: ' + workflow.triggers.join(', '))
console.log('Jobs: ' + workflow.jobs.map(function (job) { return job.id }).join(', '))
console.log('')
const counts = { PASS: 0, FAIL: 0, 'N/A': 0 }
for (const result of results) {
counts[result.status]++
console.log(result.number + '. ' + result.title)
console.log(' ' + result.status)
for (const detail of result.details) console.log(' - ' + detail)
}
console.log('')
console.log('Result: ' + counts.FAIL + ' failed, ' + counts.PASS + ' passed, ' + counts['N/A'] + ' not applicable')
if (counts.FAIL > 0) process.exitCode = 1
================================================================
FILE 3 OF 4: workflow-rules.test.mjs
================================================================
// workflow-rules.test.mjs: a regression test for one workflow file, using
// node:test. Each rule is one test, and a test fails when
// its rule fails, so the run fails on careless.yml and passes on careful.yml.
// Usage: node workflow-rules.test.mjs careful.yml
// Point it at your own workflow files to keep a fixed rule from coming back.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { checkWorkflow } from './workflow-rules.mjs'
const fileName = process.argv[2] || 'careful.yml'
const results = checkWorkflow(readFileSync(fileName, 'utf8'))
for (const result of results) {
test(fileName + ', rule ' + result.number + ': ' + result.title, function () {
assert.notEqual(result.status, 'FAIL', result.details.join(' | '))
})
}
================================================================
FILE 4 OF 4: careless.yml
================================================================
# careless.yml: an invented workflow for this page's lab, written to break
# every rule in check-workflow.mjs. Do not copy it into a repository.
name: build-and-deploy
on:
pull_request_target:
push:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Report the pull request title
run: echo "Testing ${{ github.event.pull_request.title }}"
- run: npm ci
- run: npm test
deploy:
needs: test
runs-on: ubuntu-latest
permissions: write-all
steps:
- uses: actions/checkout@main
- run: npm ci
- run: npm run build
- uses: example-owner/cloud-deploy-action@v3
with:
access-key: ${{ secrets.CLOUD_ACCESS_KEY }}
================================================================
RUN 1: node check-workflow.mjs careless.yml
================================================================
Workflow: careless.yml
Triggers: pull_request_target, push
Jobs: test, deploy
1. Workflow-level permissions are declared
FAIL
- no top-level permissions key, so each job without its own starts from the repository or organisation default
2. Write scopes are granted per job, never inherited
FAIL
- test: no permissions at job or workflow level, so the default applies
- deploy: write-all (job level)
3. Every action is pinned to a full-length commit SHA
FAIL
- 0 of 3 action references pinned to a full-length commit SHA
- line 15: actions/checkout@v6
- line 28: actions/checkout@main
- line 31: example-owner/cloud-deploy-action@v3
4. A pull_request_target workflow does not fetch the pull request head
FAIL
- triggered by pull_request_target, and these lines point at pull request code:
- line 17: github.event.pull_request.head.sha
5. No untrusted expression sits directly inside a run script
FAIL
- line 19 (test): github.event.pull_request.title is expanded inside the script
6. The deploy job names an environment
FAIL
- deploy: no environment
7. The identity-token permission is granted per job, never workflow-wide or through write-all
FAIL
- deploy: through write-all, no environment
Result: 7 failed, 0 passed, 0 not applicable
(exit code 1)
================================================================
RUN 2: node check-workflow.mjs careful.yml
================================================================
Workflow: careful.yml
Triggers: pull_request, push
Jobs: test, build, deploy
1. Workflow-level permissions are declared
PASS
- line 15: {}
2. Write scopes are granted per job, never inherited
PASS
- test: none (job level)
- build: id-token, attestations (job level)
- deploy: id-token (job level)
3. Every action is pinned to a full-length commit SHA
PASS
- 6 of 6 action references pinned to a full-length commit SHA
4. A pull_request_target workflow does not fetch the pull request head
N/A
- not triggered by pull_request_target
5. No untrusted expression sits directly inside a run script
PASS
- 6 run script lines read; none expands a github.event or github.head_ref value
6. The deploy job names an environment
PASS
- deploy: environment production
7. The identity-token permission is granted per job, never workflow-wide or through write-all
PASS
- build: job level, no environment
- deploy: job level, environment production
Result: 0 failed, 6 passed, 1 not applicable
(exit code 0)
================================================================
RUN 3: node workflow-rules.test.mjs careless.yml
================================================================
✖ careless.yml, rule 1: Workflow-level permissions are declared (0.957209ms)
✖ careless.yml, rule 2: Write scopes are granted per job, never inherited (0.061916ms)
✖ careless.yml, rule 3: Every action is pinned to a full-length commit SHA (0.047ms)
✖ careless.yml, rule 4: A pull_request_target workflow does not fetch the pull request head (0.045541ms)
✖ careless.yml, rule 5: No untrusted expression sits directly inside a run script (0.050167ms)
✖ careless.yml, rule 6: The deploy job names an environment (0.036959ms)
✖ careless.yml, rule 7: The identity-token permission is granted per job, never workflow-wide or through write-all (0.042083ms)
ℹ tests 7
ℹ suites 0
ℹ pass 0
ℹ fail 7
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.453875
✖ failing tests:
test at workflow-rules.test.mjs:15:3
✖ careless.yml, rule 1: Workflow-level permissions are declared (0.957209ms)
AssertionError [ERR_ASSERTION]: no top-level permissions key, so each job without its own starts from the repository or organisation default
(stack trace lines removed here)
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: 'FAIL',
expected: 'FAIL',
operator: 'notStrictEqual',
diff: 'simple'
}
(failure details for rules 2 to 7 removed here: each block has the same form as the one above, with that rule's details as the message)
(exit code 1)
================================================================
RUN 4: node workflow-rules.test.mjs careful.yml
================================================================
✔ careful.yml, rule 1: Workflow-level permissions are declared (0.651834ms)
✔ careful.yml, rule 2: Write scopes are granted per job, never inherited (0.052916ms)
✔ careful.yml, rule 3: Every action is pinned to a full-length commit SHA (0.038625ms)
✔ careful.yml, rule 4: A pull_request_target workflow does not fetch the pull request head (0.034583ms)
✔ careful.yml, rule 5: No untrusted expression sits directly inside a run script (0.038ms)
✔ careful.yml, rule 6: The deploy job names an environment (0.033917ms)
✔ careful.yml, rule 7: The identity-token permission is granted per job, never workflow-wide or through write-all (0.037459ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4.873417
(exit code 0)
Reading the output:
- careless.yml fails all seven rules. The pull_request_target trigger, a checkout of github.event.pull_request.head.sha and then npm ci and npm test is the pwn request shape GitHub describes; the pull request title written into an echo is the script injection shape; the deploy job has write-all, no environment and a tag-pinned third-party action.
- careful.yml passes six rules, and rule 4 does not apply because it never uses pull_request_target. Rule 7 lists the build job's id-token: write as well as the deploy job's, because attesting needs it. The checker reports where the permission is granted; deciding whether each job needs it is yours.
- check-workflow.mjs sets exit code 1 itself when any rule fails. For the test run, the Node.js documentation says that if any tests fail, the process exit code is set to 1. A pipeline step that treats a non-zero exit code as a failure stops on either.
Using it on your own workflows:
1. Copy workflow-rules.mjs and workflow-rules.test.mjs into your repository's tests.
2. Run node workflow-rules.test.mjs .github/workflows/deploy.yml for each workflow file, in the pipeline that runs on every pull request.
3. If a file uses YAML this checker does not read, such as anchors or flow mappings, it may miss things. Keep a maintained workflow linter alongside it rather than relying on it alone.What a CI/CD pipeline is, and why it is worth attacking
A CI/CD pipeline is the automation that turns a commit into a running release.
Continuous integration builds and tests each change; continuous delivery or deployment packages the result and puts it where users can reach it. NIST SP 800-204D, NIST's guidance on supply chain security in DevSecOps pipelines, describes CI/CD pipelines as using processes called workflows to transform source artefacts into deployable packages in production environments. On GitHub those workflows are YAML files in .github/workflows; on GitLab the pipeline is defined in .gitlab-ci.yml.
Two things make a pipeline worth attacking. It holds credentials: a token for the repository, keys or roles for the cloud account, tokens for the package registry. And it is allowed to change production on its own. OWASP's entry on poisoned pipeline execution (CICD-SEC-4), in its Top 10 CI/CD Security Risks, spells out what a successful attack gives an attacker: the same abilities and level of access as the build job, including any secret available to it, and the ability to ship code and artefacts further down the pipeline in the guise of legitimate code built by the build process.
OWASP Top 10:2025, in A03 Software Supply Chain Failures, lists a CI/CD pipeline with weaker security than the systems it builds and deploys among the signs that you are likely vulnerable.
So this page treats the pipeline as a system that holds the right to deploy, and asks three questions of it. Who and what can make it run, and with whose code? What can each job reach once it runs?
What proves that an artefact came from it? NIST SP 800-204D frames the same work as two goals: actively defend the CI/CD pipeline and build processes, and ensure the integrity of upstream sources and artefacts.
Neighbouring guides take the rest. The supply chain attacks guide covers how a compromised package, build step or browser script reaches a site. The dependency security guide covers finding and updating vulnerable packages. The secrets exposure guide covers finding a leaked key and rotating it. The SAST and DAST guides cover the scanners that run inside a pipeline. The SBOM guide covers the inventory of what a build contains.
Who can make the pipeline run, and with whose code
A pipeline runs when an event says so: a push, a pull request, a schedule, a comment, a person pressing a button.
Each trigger decides two things at once: whose code runs, and with which token and secrets. OWASP's entry on poisoned pipeline execution (CICD-SEC-4) says pipelines that execute unreviewed code, such as those triggered directly off pull requests or commits to arbitrary branches, are more susceptible, because that code has not been through any review or approval.
On GitHub, the pull_request event runs the workflow from the pull request's merge commit. For a pull request from a fork, that commit, workflow file included, is controlled by someone without write access to your repository. GitHub's answer is to limit what the run receives: apart from the GITHUB_TOKEN, secrets are not passed to the runner when a workflow is triggered from a forked repository, and the GITHUB_TOKEN is read-only in pull requests from forks. Workflows triggered by Dependabot pull requests are treated the same way.
Those limits have switches. For a private repository, workflows on fork pull requests run only when enabled, and the settings include options to send write tokens and to send secrets to workflows from fork pull requests. Leave both off unless you have read exactly what each workflow would do with them.
For a public repository, an approval setting decides whose pull requests run without a maintainer agreeing first, and by default every first-time contributor needs approval. GitHub warns that when approval covers only first-time contributors, anyone who has had a commit or pull request merged no longer needs it, and that a malicious user could get there by having a simple typo fix or other innocuous change accepted.
Requiring approval for all external contributors closes that gap. For outside contributors' pull requests to public repositories, NIST SP 800-204D asks for one of two things: CI runs in a sandbox with no network access, privileged access or ability to read secrets, or a delay until a maintainer with write access approves, with that setting at its strictest level. Before approving, GitHub tells maintainers to be especially alert to changes in the .github/workflows directory.
Approval decides who gets to run code; it does not contain what the code does. GitHub says its fork approval policies are intended to restrict who can run workflows, against unexpected resource and compute use on GitHub-hosted runners, and that on self-hosted runners, user-controlled workflow code runs automatically once the pull request is approved, or when its author may bypass approval.
pull_request_target exists for automation that must respond to forks with privileges, such as labelling or commenting. GitHub runs it in the context of the base repository's default branch rather than the merge commit, gives the job the base repository's GITHUB_TOKEN and access to repository and organisation secrets, and grants the token read/write repository permission even when the event comes from a public fork.
Because the base branch is considered trusted, these workflows run regardless of fork approval settings, and unlike pull_request they run even when the pull request has a merge conflict.
The trust holds only while no code from the pull request runs. GitHub's guidance describes the failure, known as a "pwn request": a pull_request_target workflow points actions/checkout at the pull request head and then runs something from it, such as a Makefile, build script, test command, dependency or configuration file, and the fork's commands run with the base repository's secrets and token.
GitHub adds that build and test commands such as npm install and npm run build can run attacker-controlled code, and that issue_comment and workflow_run workflows that check out or download pull request code and then run it are vulnerable in the same way. Its rule is that checked-out code must only ever be inspected as data and never executed.
GitHub's guidance describes two protections, and neither replaces reading the workflow. Its documentation, read on 14 November 2026, describes a default policy that blocks pull_request_target in public repositories that do not already have an applicable Actions event policy. It does not apply to private or internal repositories, currently runs in evaluate mode, and GitHub says it will enforce it on 2 December 2026 for affected repositories that were using the default pull_request_target policy before general availability.
The second is in actions/checkout: its README lists under Checkout v7 that checkout now refuses to check out fork pull request code by default when the workflow is triggered by pull_request_target or workflow_run, and that you opt in by setting the new allow-unsafe-pr-checkout input to true.
The lab's careless.yml references actions/checkout@v6, a version before the one the README lists it under. GitHub says to set the input only after confirming the checked-out code is never executed, and that the protection only covers fork pull request refs, not git fetch, gh pr checkout or a downloaded artefact. If a workflow does not need the privileged context, GitHub's advice is to use pull_request.
Code is not the only thing a pull request author controls. The title, body, branch name and commit messages are theirs too. GitHub says the github context should be treated as potentially untrusted input. The contexts attackers can add content to typically end with body, default_branch, email, head_ref, label, message, name, page_name, ref or title, and branch names and email addresses are less obvious sources because their permitted content is flexible.
A run step executes as a temporary shell script, and any expression inside it is evaluated and substituted before the script runs, so a pull request title written straight into a run script can turn into shell commands.
GitHub's secure use reference names the preferred approach for inline scripts: set the value of the expression to an intermediate environment variable. GitHub says the value is then stored in memory and used as a variable, and does not interact with the script generation process. The sample workflow in the asset does this with the pull request title, and rule 5 of the lab checker flags the unsafe form.
Whoever can change a workflow file can change what the pipeline does with everything it holds. OWASP's CICD-SEC-4 describes three types of poisoned pipeline execution; two of them matter here. In direct poisoned pipeline execution, the attacker edits the CI configuration file and either pushes it to an unprotected branch or submits it in a pull request from a branch or a fork.
In the indirect form, the configuration is protected but the files it calls are not, for example a Makefile, a script in the repository, test code, or the configuration a linter or scanner reads.
On the trusted side, GitHub notes that anyone with write access can change the GITHUB_TOKEN's permissions by editing the permissions key, and that anyone who can edit workflows can create an environment by naming it in a workflow file.
Treat workflow files, and the scripts they call, as deploy configuration. Protect the branches that deploy and require review by someone other than the author: NIST SP 800-204D says developers with merge approval permissions cannot approve their own merges. GitHub's secure use reference suggests adding .github/workflows to CODEOWNERS so that changes to workflow files need a designated reviewer.
OWASP's CICD-SEC-1 names what this prevents: an attacker with access to one system in the pipeline single-handedly pushing malicious code or artefacts through it, because nothing enforces another approval or review.
What each job can reach: the token, the secrets and the runner
Once a job runs, everything in it can reach everything the job was given.
That makes the job, not the workflow, the unit to limit.
At the start of each job, GitHub creates a unique GITHUB_TOKEN: an installation access token whose permissions are limited to the repository that contains the workflow, and which expires when the job finishes or reaches its maximum lifetime. Every step in the job can use it, third-party actions included. GitHub says an action can read it through the github.token context even if the workflow never passes it.
What the token can do depends on a default you may never have looked at. GitHub's documentation says a new repository in a personal account starts with read access only for the contents and packages scopes, a new repository in an organisation inherits the organisation's setting, and the permissive option gives read and write access for all permissions.
A workflow's permissions key then adjusts that default, first at the workflow level and then for each job. Once you specify any permission, every permission you do not specify is set to none. That is what makes the key a least-privilege tool: permissions: {} at the top removes everything, and each job adds back only the scopes it uses, such as contents: read to check out code, attestations: write to create an attestation, or id-token: write to request an OIDC token.
Declaring permissions in the file also makes them reviewable. A repository default can change in the settings without a commit; a permissions block changes only through a change someone can read in a pull request. GitHub's secure use reference calls a default of read access for repository contents good security practice, with permissions increased per job as required.
A secret reaches a job only through the workflow: GitHub Actions can read a secret only if you explicitly include it in a workflow, and to pass one to an action you set it as an input or an environment variable.
Secrets sit at three levels, organisation, repository and environment, and when names collide the lowest level wins, so an environment secret overrides a repository secret of the same name. Organisation and repository secrets are read when the run is queued.
Environment secrets are read when a job that references the environment starts, and if the environment requires approval, a job cannot access them until a required reviewer approves.
That makes environment secrets the right home for anything that can change production. A repository secret is available to whichever job a workflow passes it to, and GitHub's secure use reference notes that any user with write access to a repository has read access to all secrets configured in it.
Some jobs should never see a production secret: jobs that run on pull requests, jobs that install and build dependencies, jobs that run linters, scanners or test suites over code nobody has reviewed yet, and any job whose third-party actions you have not read.
OWASP's CICD-SEC-5 recommends scoping secrets so each pipeline and step can access only what it requires, and giving package installation scripts a separate context without access to secrets. OWASP ASVS 5.0 requirement 13.3.2 asks that access to secret assets follows the principle of least privilege, and requirement 13.3.1 asks for a secrets management solution for backend secrets and says secrets must not be included in source code or build artefacts.
Log masking is a backstop. GitHub redacts secrets printed to workflow logs, but says the redaction is not guaranteed because a value can be transformed in multiple ways, and that the runner can only redact secrets used in the current job. When a key does leak, the secrets exposure guide covers finding it, rotating it and showing that the old one no longer works.
The runner is the machine that executes the job, and it holds everything the job was given: the checked-out code, the token, the secrets and network access. GitHub notes that jobs in one workflow can interact with, and compromise, each other. A self-hosted runner adds whatever else lives on that machine and its network.
GitHub notes that workflows on self-hosted runners do not run in an isolated container even when they use environments, so environment secrets there deserve the same care as repository secrets, and that fork pull request code runs on them automatically once the pull request is approved, or when its author may bypass approval.
OWASP's CICD-SEC-5 recommends reverting the execution node to its pristine state after each run and not sharing a node between pipelines with different levels of sensitivity.
What a third-party action can do once it runs
An action is someone else's code running inside your job.
OWASP's CICD-SEC-8 points out how little that takes: adding a third party to a build is usually one or two lines in the pipeline file, and its code then runs with full access to whatever the pipeline stage can reach. In GitHub Actions that means the job's token through github.token, the job's files and network access, and every secret the job was given.
GitHub's secure use reference goes further for a compromised action: it would have access to all secrets configured on the repository, and may be able to use the GITHUB_TOKEN to write to the repository.
The reference you write decides which code arrives. A tag or branch is resolved at run time, and GitHub warns that tags can move: if an upstream maintainer's account is compromised and a tag is repointed, your repositories could run malicious code.
GitHub's advisory GHSA-mrrh-fwg8-r2c3 (CVE-2025-30066) describes a case: attackers retroactively modified multiple version tags of tj-actions/changed-files to reference a malicious commit. The attack ran a script that extracted secrets from the Runner Worker process memory and printed them in the workflow logs, making them publicly accessible in repositories with public logs, and the advisory gives the period as between 14 and 15 March 2025.
CISA's alert says the compromise allows disclosure of secrets including, but not limited to, valid access keys, GitHub personal access tokens, npm tokens and private RSA keys, that the compromise was potentially enabled by the compromise of another action, reviewdog/action-setup@v1, and that affected organisations should rotate all identified secrets immediately.
GitHub calls a workflow dependency lockfile the strongest protection. The file, .github/workflows/actions.lock, is generated by the gh actions-lock extension and pins every action your workflows depend on, transitive dependencies included, to a commit, records the identity of each source repository, and rejects a commit that exists only in a fork.
It does not pin calls to reusable workflows, which should be referenced by full commit SHA, and it does not control other build inputs, such as input parameters, secrets or the runner image. For repositories that cannot adopt a lockfile, GitHub advises pinning each action to a full-length commit SHA, taken from the action's own repository rather than a fork; an abbreviated SHA does not count.
A repository setting, "Require actions to be pinned to a full-length commit SHA", enforces this for every action, GitHub's own included, while reusable workflows can still be referenced by tag.
Pinning has costs GitHub states plainly. GitHub says that with a SHA you will not automatically receive updates for an action, including important bug fixes and security updates, and that Dependabot only creates alerts for vulnerable actions that use semantic versioning, not for actions pinned to SHA values.
GitHub's secure use reference also says Dependabot version updates open pull requests to update actions when a new version is released, and that Dependabot supports references written as a commit SHA. A tool can propose the new pin, but a person still has to review it.
A pin also says nothing about what the pinned code does. GitHub's guidance is to audit an action's source code regardless of your measures, for example checking that secrets are not sent to unintended hosts or inadvertently logged.
Where you can, keep third-party actions out of the jobs that hold deployment secrets or write scopes: a lint or comment action has no reason to share a job with a production credential.
What an environment approval checks, and what it does not
On GitHub, an environment is a named deployment target, such as production, with its own secrets and protection rules.
All of an environment's deployment protection rules must pass before a job that references it is sent to a runner, and its secrets reach only jobs that reference it, after the rules pass. The rules include required reviewers (up to six people or teams, any one of whom can approve), an option to prevent self-review so the person who started a deployment cannot approve it, a wait timer, limits on which branches and tags can deploy, and custom rules from GitHub Apps, which GitHub labels public preview.
Check your plan before relying on them. GitHub's documentation says that on its Free, Pro and Team plans, required reviewers and wait timers are only available for public repositories, deployment branch and tag rules reach private repositories on Pro and Team, and on Free, environments can only be configured for public repositories at all.
By default, administrators can bypass the protection rules, and each environment has to be set to disallow that.
An approval answers one question: did a named person agree that this job may run now? It does not tell the reviewer what the job will do, which commit it was built from, or whether the workflow file changed on the way.
For an approval to mean more than a click, the reviewer has to look at the run's commit, its workflow file and the artefact it will deploy. OWASP's CICD-SEC-1 recommends, where applicable, preventing accounts from triggering production build and deployment pipelines without additional approval or review; required reviewers with self-review prevented is one way to do that for a deploy job on GitHub.
Two details catch teams out. A deploy job that names an environment which does not exist does not fail: GitHub creates a new environment with that name and no protection rules or secrets, and anyone who can edit workflows can do this, while only repository admins can configure it.
And branch rules are matched against the run's GITHUB_REF: adding refs/pull/*/merge as a deployment branch rule lets pull_request events deploy too, and "protected branches only" lets every branch deploy if no branch in the repository has protection rules.
Deployment identity: short-lived tokens instead of stored keys
The deploy job has to prove to the cloud provider, registry or host that it may deploy.
The traditional answer is a key stored as a secret, which GitHub's documentation describes as a credential presented to the cloud provider every time the workflow runs, created in the provider and duplicated in GitHub. With OpenID Connect (OIDC), the job instead requests a token from GitHub's OIDC provider and exchanges it for a short-lived cloud access token, which GitHub says is only valid for a single job and then expires. There is no long-lived cloud credential stored in GitHub to be printed, copied or stolen.
OWASP's CICD-SEC-6 recommends the same direction for every pipeline: prefer temporary credentials over static ones, rotate the static ones you have to keep, and avoid sharing one credential across contexts. npm's trusted publishing applies it to packages, publishing from a CI/CD workflow through OIDC with short-lived tokens specific to that workflow, in place of long-lived npm tokens.
A short-lived token is only as narrow as the trust condition behind it. The cloud provider checks the token's subject and other claims against conditions you configure on the role, and GitHub says you must define at least one condition so that untrusted repositories cannot request access tokens for your cloud resources.
The subject is the useful claim. When the job references an environment, the subject includes the environment name, as in GitHub's example repo:octo-org/octo-repo:environment:Production, and a pull request event appears in the subject only when the job references no environment. A condition that names your repository and the production environment therefore matches only jobs that reference that environment, which are jobs whose protection rules have already passed.
GitHub notes that repositories created after 15 July 2026 use an immutable default subject format that includes the owner ID and repository ID, that repositories created before that date keep the previous format unless you opt in, and that repository renames and transfers after that date also move to the immutable format.
The rollout does not include GitHub's self-hosted server edition. Check which format your repository produces before writing the condition.
The permission that unlocks all this is id-token: write. GitHub's reference says it only enables fetching the OIDC token and does not grant write access to other resources. It is still the way into the deployment role, so grant it in the deploy job, and in any other job that uses it, such as one that signs an attestation, and nowhere else.
For reusable workflows owned outside your organisation, and outside any business account above it, GitHub says to set id-token: write explicitly at the caller, so the token is only available to intended callers.
What a signed or attested artefact lets a deployer check
Between the build and the deployment, the artefact sits somewhere: an artifact store, a container registry, a release page.
OWASP's CICD-SEC-9 describes the risk at that hand-over, an attacker with access to one system in the pipeline pushing malicious but seemingly benign code or artefacts down it, and recommends signing a resource when it is generated and validating it against the signing authority before the next step consumes it.
NIST SP 800-204D gives the deploy-side rule, written for container images: where a secure build environment and process exist, it should be possible to require that the image being deployed was generated by that process before it is cleared for deployment. OWASP Top 10:2025's A03 entry asks for artefacts whose integrity is ensured through provenance, signing and time stamping, promoted between environments rather than rebuilt for each, and its A08 entry gives as an example a CI/CD pipeline that pulls code or artefacts from untrusted places and/or does not verify them before use.
GitHub's artifact attestations are one implementation. The attest action creates cryptographically signed claims about a build, including a link to the workflow, and the repository, organisation, environment, commit SHA and triggering event. GitHub signs them with Sigstore; public repositories use the Sigstore Public Good Instance and a publicly readable transparency log, while private repositories use GitHub's own instance, which has no transparency log.
A deployer runs gh attestation verify on the artefact with the expected repository, and can then check that what it is about to deploy was built by that repository's workflow, at a commit it recognises, and has not changed since.
Sigstore describes what verification establishes: the artefact comes from its expected source and has not been tampered with after its creation.
Be exact about what that does not prove. GitHub says attestations by themselves provide SLSA v1.0 Build Level 2, and that building in a reusable workflow isolated from the calling workflow can meet Build Level 3. In the current SLSA specification, version 1.2, Build L2 means a hosted build platform generates and signs the provenance, and the first benefit it lists is preventing tampering after the build.
Build L3 adds a hardened platform that stops runs influencing one another and keeps the provenance signing material away from user-defined build steps, preventing tampering during the build.
Neither level says the source was free of flaws or malice. GitHub says attestations link you to the source and build instructions, that the policy you check them against is yours to define, and that generating them gives no security benefit until someone verifies them. Sigstore adds that misbehaviour by its certificate authority or log might go undetected if no third parties monitor the logs, and that monitoring the log for certificates issued to your identities is up to you. The supply chain attacks guide covers the same limits for npm provenance.
The frameworks that describe pipeline risk
Several public documents cover this ground.
Each is worth reading beside this page, and none is a certificate for a pipeline:
- OWASP Top 10 CI/CD Security Risks, an OWASP lab project: CICD-SEC-1 Insufficient Flow Control Mechanisms, CICD-SEC-2 Inadequate Identity and Access Management, CICD-SEC-3 Dependency Chain Abuse, CICD-SEC-4 Poisoned Pipeline Execution (PPE), CICD-SEC-5 Insufficient PBAC (Pipeline-Based Access Controls), CICD-SEC-6 Insufficient Credential Hygiene, CICD-SEC-7 Insecure System Configuration, CICD-SEC-8 Ungoverned Usage of 3rd Party Services, CICD-SEC-9 Improper Artifact Integrity Validation and CICD-SEC-10 Insufficient Logging and Visibility.
- NIST SP 800-204D, Strategies for the Integration of Software Supply Chain Security in DevSecOps CI/CD Pipelines, published in February 2024, with numbered requirements such as PULL-PUSH-REQ-3 for outside contributors' pull requests and DEPLOY-REQ-3 for deploying only container images the established build process produced.
- CISA and the NSA's joint guidance on defending CI/CD environments, a Cybersecurity Information Sheet released on 28 June 2023 with recommendations and best practices for strengthening CI/CD pipelines, and a list of common risks and attack surfaces in them.
- The SLSA specification, version 1.2, whose Build track runs from L0, which represents the lack of SLSA, through L1, provenance exists, and L2, a hosted build platform that generates and signs provenance, to L3, a hardened build platform.
- OWASP Top 10:2025 A03 Software Supply Chain Failures, which lists a pipeline weaker than the systems it deploys among the signs you are likely vulnerable, and A08 Software or Data Integrity Failures, which gives as an example a CI/CD pipeline that pulls code or artefacts from untrusted places and/or does not verify them before use.
- OWASP ASVS 5.0, chapter V13 Configuration, whose requirements 13.3.1 and 13.3.2 cover keeping secrets out of source code and build artefacts and least-privilege access to them.
GitLab CI/CD: the same questions, different mechanisms
The questions are the same on every platform; the mechanisms are not, and parity should not be assumed.
GitLab's documentation answers them like this:
- Forks. A merge request from a fork triggers a pipeline that runs in the fork project, with the fork's CI/CD configuration, resources and variables. A member of the parent project can run it in the parent project instead, where it uses the fork's configuration with the parent project's variables and resources and the permissions of the member who triggers it. GitLab warns that such a merge request can contain code that tries to steal the parent project's secrets, and its CI/CD variables documentation says reviewers should never trigger a pipeline when they find malicious code, because it can compromise both masked and protected variables.
- Secrets. A protected variable is available only to pipelines on protected branches or protected tags, though merge request pipelines can optionally be given access. GitLab says masking a variable cannot be relied on to stop malicious users reading its value.
- The job token. GitLab generates CI_JOB_TOKEN for each job, valid only while the job runs, with the same access level as the user who triggered the pipeline but fewer resources than a personal access token. By default, each project's job token allowlist includes only the project itself.
- Identity. ID tokens are JSON web tokens generated by GitLab CI/CD for OIDC with third-party services, such as secrets providers and cloud services, declared per job with the id_tokens keyword, where each token can set its own audience.
- Approvals. Protected environments and deployment approvals are on GitLab's Premium and Ultimate tiers, and deployments to a protected environment that requires approval are blocked until all required approvals are given. GitLab administrators can use all environments, protected ones included.
Questions to ask of any other CI service
For a CI service not covered here, ask its own documentation five questions before trusting it with a deployment.
What runs for an outside contribution, and with which credentials? How is a job's token scoped, and can each job be given less than the default? How are third-party steps referenced, and can they be pinned to something that cannot move?
How is a deployment gated, and who can bypass the gate? Can a job use a short-lived identity instead of a stored key? This page does not describe services whose documentation it has not checked.
Checking your own workflow files
The asset on this page has four parts.
The trust map lists who and what in a pipeline is trusted to do what, what each can reach, and the control that limits it. The threat test pack turns six of those controls into tests you run in your own repository, with a test secret that unlocks nothing.
The sample permission set is a complete workflow with permissions declared at workflow and job level. The local lab is a small checker, importing only node:fs, node:test and node:assert, that reads a careless and a careful workflow file and reports seven rules.
The checker is an illustration. It reads lines in the simple shape the two sample files use; it is not a YAML parser, it does not read lockfiles or repository settings, and a file that passes it can still be unsafe in ways it does not look at.
GitHub's secure use reference points to code scanning with CodeQL, which can detect potentially vulnerable workflows, and to OpenSSF Scorecards, whose checks include script injection, token permissions and pinned actions.
On careless.yml all seven rules failed and the check exited with code 1. On careful.yml six passed, and the pull_request_target rule did not apply because the file never uses that trigger. The regression test, which uses node:test, failed all seven of its tests on careless.yml and passed all seven on careful.yml.
The Node.js documentation says that if any tests fail, the process exit code is set to 1. A pipeline step that treats a non-zero exit code as a failure stops on it.
Where a security review fits
Clever Ops tests what customers reach through a browser or an API, so a pipeline comes into its work through the code.
A secure code review, with read-only access to the repository, reads what runs on its own at install, build or deploy time, such as package scripts and CI workflow files, in the branch or commit in scope. Repository settings, environment rules and cloud trust policies are not in those files, which is why the test pack is written for your own team to run.
If Clever Ops built or hosts the application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
If you think your pipeline has already been used against you, for example a secret appeared in a public log or a deployment ran that nobody started, call your host and an incident response specialist first. Clever Ops does not provide incident response or monitoring, so it is not the right first call.
Frequently asked questions
Protecting the pipeline that builds and deploys your software as a system in its own right, because it holds credentials and the right to change production. In practice that means controlling who and what can make it run and with whose code, limiting what each job can reach, and being able to show that what you deploy came from it. NIST SP 800-204D names actively defending the CI/CD pipeline and build processes as one of its two security goals.
On the pull_request event, GitHub passes no secrets other than the GITHUB_TOKEN to a run triggered from a fork, and that token is read-only, unless a private repository's settings send write tokens or secrets to fork pull requests. On pull_request_target, the job holds the base repository's secrets and a read/write token, and runs regardless of approval settings, so it must never run code from the pull request. On a self-hosted runner, an approved fork pull request also runs on that machine.
As few as each job needs, declared in the workflow file. Set permissions: {} at the top, then give each job only the scopes it uses, such as contents: read to check out code. GitHub says a new repository in a personal account defaults to read access for contents and packages, while an organisation repository inherits the organisation's setting, which may be the permissive one, so a workflow without a permissions key depends on a setting outside the file.
It stops a moved tag from changing the code you run; GitHub's advisory GHSA-mrrh-fwg8-r2c3 describes attackers modifying tj-actions/changed-files version tags to point at a malicious commit. It is not enough on its own. GitHub calls a workflow dependency lockfile the strongest protection available; it records the exact commit for every action your workflows depend on, transitive dependencies included. GitHub also advises auditing an action's source code regardless of your measures, and says a SHA-pinned action does not receive updates automatically. GitHub says Dependabot version updates can open pull requests that update a SHA-pinned action, but a person still has to review each one.
It stops the deploy job, and keeps the environment's secrets from it, until a required reviewer approves. Whether that catches anything depends on what the reviewer looks at: the commit, the workflow file and the artefact. Turn on prevent self-review, switch off administrator bypass, limit which branches can deploy, and check that every environment named in a workflow exists, because a name that does not exist creates an environment with no rules.
GitHub says OIDC removes the need to duplicate cloud credentials as long-lived GitHub secrets: each job exchanges an OIDC token for a short-lived cloud access token that is valid for that job only. Its value depends on the cloud role's trust condition, which should name your repository and the production environment, and on granting id-token: write only to the jobs that use it. OWASP's CICD-SEC-6 likewise recommends temporary credentials over static ones.
It means you can check where and how the artefact was built: which repository and workflow produced it and at which commit. Sigstore, which GitHub uses to sign attestations, says verification also shows the artefact has not been tampered with since its creation. GitHub says attestations provide SLSA v1.0 Build Level 2 on their own, that generating them gives no benefit until someone verifies them, and that the policy you verify against is yours to define. They say nothing about whether the source code was free of flaws.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.