Sub topic 13
Securing Pipelines and Handling Secrets
A pipeline holds some of the most powerful access in an organization. It can read source code, build the software that customers run, and write to production. An attacker who controls a pipeline can often ship malicious code without touching the application repository. This chapter covers how to protect pipelines and how to handle the credentials they need.
Prerequisites assumed: the pipeline anatomy from earlier chapters (jobs, triggers, environments), basic Git and pull request workflow, and the ability to read GitHub Actions YAML. The examples use GitHub Actions, but the ideas apply to any CI/CD system.
Why pipelines are attractive targets
A pipeline needs credentials to do its work. It pulls private dependencies, pushes images to a registry, and deploys to cloud accounts. It also runs code that people wrote, including code from pull requests, third-party actions, and package dependencies. Credentials and untrusted code in the same place create the risk.
Common attack paths:
- Leaked secrets. A token is committed to the repository, printed in a log, or baked into an artifact.
- Malicious pull requests. A change from a fork or a compromised account edits the pipeline definition or test code so it sends secrets elsewhere.
- Compromised dependencies. A third-party action or package is altered after you start using it.
- Over-privileged credentials. A stolen token can do far more than the job needed.
- Unprotected deployment paths. Anyone who can push a branch can reach production.
Principles to apply everywhere
Four principles cover most of the guidance in this chapter.
- Least privilege. Give each job only the access it needs, for only as long as it needs it.
- Short-lived credentials. A token that expires in minutes is much less useful to a thief than one that lasts for years.
- Separation of duties. The code that runs on a pull request should not have the keys to production.
- Auditability. You should be able to answer who changed the pipeline, who approved a deploy, and which credential was used.
Handling secrets
A secret is any value that grants access: API keys, passwords, tokens, signing keys, and cloud credentials.
Never store secrets in the repository
Git history is permanent. Deleting a secret in a later commit does not remove it from earlier commits, clones, or forks. If a secret reaches the repository, treat it as compromised and rotate it, which means issuing a new value and revoking the old one. Rewriting history is a secondary cleanup step.
Prevent the mistake with secret scanning. Run a scanner as a pre-commit hook and again in the pipeline so that a missed commit is still caught. GitHub offers built-in secret scanning and push protection, and open-source tools such as gitleaks do the same job.
Use the platform's secret store
CI/CD platforms provide encrypted storage for secrets. In GitHub Actions you define a secret in the repository, organization, or environment settings and read it with the secrets context. Prefer environment-scoped secrets for deployment credentials. Then only jobs that target that environment can read them, and the environment's protection rules apply.
name: deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Deploy
env:
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
run: ./scripts/deploy.shThe secret is passed to a single step through env, not to the whole job. Limiting the scope this way reduces the number of programs that can read it.
Keep secrets out of logs
Platforms mask known secret values in logs, but masking is a best-effort measure. It matches the exact string. If a script transforms a secret, for example by encoding it in Base64 or splitting it across lines, the transformed value is not masked. Avoid these habits:
- Running shell scripts with
set -x, which echoes every command with its expanded arguments. - Printing the whole environment with
envorprintenvwhile debugging. - Passing secrets as command-line arguments, which can show up in process listings and error messages. Prefer environment variables or files with restricted permissions.
- Writing secrets into build output, such as a
.envfile that is later packaged in an artifact or a Docker image layer.
Prefer short-lived credentials over stored ones
A stored secret is a long-lived password sitting in a settings page. A better approach for cloud deployments is OpenID Connect (OIDC) federation. The CI platform issues a signed identity token for each job run. The cloud provider verifies the token and returns temporary credentials. No long-lived cloud key is stored in the CI system at all.
The cloud account is configured with a trust rule, such as "accept tokens from this repository, on this branch or environment". A job that does not match the rule gets nothing.
name: deploy-oidc
on:
push:
branches: [main]
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/ci-deploy
aws-region: eu-west-1
- run: aws sts get-caller-identityThe id-token: write permission lets the job request the identity token. The role ARN here is a placeholder. The role's trust policy decides which repositories and environments may assume it. The last step prints the identity the job received, which is a quick way to confirm the setup works.
For secrets that cannot be replaced by federation, such as third-party API keys, consider a dedicated secrets manager (HashiCorp Vault, AWS Secrets Manager, or similar). It supports central rotation, access policies, and audit logs.
Limiting what the pipeline can do
Restrict the default token
Most platforms give each run an automatic token. In GitHub Actions this is GITHUB_TOKEN. Set its permissions explicitly instead of relying on defaults:
permissions:
contents: readSet this at the top of the workflow, then grant extra permissions to individual jobs that need them. A test job rarely needs to write to the repository.
Be careful with pull requests from forks
Code in a pull request is untrusted until a reviewer says otherwise. For forks, GitHub's pull_request trigger runs without access to repository secrets and with a read-only token, which is the safe default. The pull_request_target trigger runs in the context of the base repository and does have access to secrets. If a workflow using it checks out and runs the fork's code, the fork author can steal those secrets. Use pull_request_target only for tasks that do not execute pull request code, such as adding labels.
A related risk is script injection. Expressions like ${{ github.event.pull_request.title }} are substituted into the script text before the shell runs. A title containing shell syntax can run commands. Pass such values through an environment variable instead:
- name: Print title safely
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "$PR_TITLE"The shell now treats the title as data, not as code.
Pin third-party dependencies
Every uses: line runs someone else's code with your job's access. A tag such as v4 can be moved by its owner, or by an attacker who takes over the owner's account. Pinning to a full commit SHA fixes the version to exact content:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1Keep a version comment next to the SHA and use an automated updater such as Dependabot or Renovate so pinned versions still receive security updates. Apply the same idea to package dependencies with lockfiles, and use npm ci rather than npm install in pipelines so the lockfile is respected.
Protect the pipeline definition and the deploy path
Because pipelines are code, changes to them need the same review as application code:
- Require pull request review on the main branch, including for files under
.github/workflows/. A CODEOWNERS entry can require a security or platform team to approve those files. - Use branch protection so deployments cannot run from arbitrary branches.
- Use environment protection rules, such as required reviewers, for production. This is the approval gate that turns continuous deployment into continuous delivery.
- Run untrusted builds on ephemeral runners, which are created fresh for each job and destroyed afterward. Long-lived self-hosted runners keep files and processes between jobs, and a malicious job can leave something behind for the next one. Never attach self-hosted runners to public repositories without strong isolation.
Securing what the pipeline produces
The pipeline's output is also an attack surface. Since you build once and promote the same artifact, a tampered artifact reaches every environment.
- Scan dependencies and images for known vulnerabilities, and fail the build above an agreed severity.
- Generate a software bill of materials (SBOM), a list of the components inside the artifact, so you can find affected builds when a new vulnerability is announced.
- Sign artifacts and images (for example with Sigstore's cosign) and verify the signature before deploying. This confirms that the artifact came from your pipeline.
- Record provenance, which is metadata describing which commit, workflow, and runner produced the artifact.
Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Long-lived cloud keys stored as CI secrets | A leak gives lasting access | Use OIDC and short-lived credentials |
| Secrets available to every job | Test code can read production keys | Use environment-scoped secrets |
| Default write-all token | A compromised step can modify the repository | Set `permissions` explicitly |
| `pull_request_target` with fork checkout | Fork code runs with secrets | Use `pull_request`, or avoid running fork code |
| Tag-pinned third-party actions | A moved tag runs attacker code | Pin to commit SHAs |
| Untrusted values interpolated into `run` | Script injection | Pass values through `env` |
| Rotating secrets only after an incident | Slow response when a leak occurs | Rotate on a schedule and rehearse it |
A short checklist
- No secrets in the repository, with scanning enabled.
- Deployment secrets scoped to environments, or replaced by OIDC.
- Explicit minimal
permissionson every workflow. - Third-party actions pinned and updated automatically.
- Pipeline files protected by review and branch protection.
- Production deploys gated by an environment rule.
- Artifacts scanned, and signed where practical.
Exercise
A workflow uses the pull_request_target trigger, checks out the pull request's head commit from a fork, and runs npm test with a deployment secret available in the environment. What is the risk, and how would you change the workflow?
Show answer
Fork authors can edit test code or package.json scripts, and npm test will run that code with access to the deployment secret, so they can send the secret to a server they control. Switch to the pull_request trigger, which gives fork runs no secrets and a read-only token, and keep deployment secrets only in environment-scoped secrets for jobs on protected branches. If pull_request_target is needed, for example to add labels, do not check out or run the pull request's code in that workflow.
Exercise
Your team stores a long-lived AWS access key as a repository secret. Describe how OIDC federation improves on this, and name the setting that lets a GitHub Actions job request the identity token.
Show answer
With OIDC, the CI platform issues a signed token for each run and the cloud provider exchanges it for temporary credentials, after checking a trust rule on repository, branch, or environment. No long-lived key exists to leak, and credentials expire shortly after the job ends. The job needs permissions: id-token: write to request the token.