Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

Pipeline security scanning

Add SAST, dependency (SCA), secrets, container image and infrastructure-as-code scanning to the Account API's GitHub Actions pipeline, gate merges on a written policy, and govern suppressions so the scanners stay trusted.

intermediate⏱ 2 h 🟢 FreeSCS-C03DVA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 · AWS CLI v2 · GitHub Actions (actions/checkout@v6, github/codeql-action@v4) · Trivy action v0.36.0 · Checkov · Cdklabs.CdkNag 3.0.2 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Name the five families of automated security scanning — SAST, SCA, secrets, container image and IaC — and say which class of defect each one can and cannot find.
  • Turn on NuGet Audit for a .NET 10 solution and decide which severities should break the build.
  • Build a GitHub Actions workflow for the Harbourline Accounts API that runs CodeQL, NuGet Audit, Gitleaks, Trivy and Checkov, and uploads SARIF results to one place.
  • Run cdk-nag and cfn-nag against CDK output and explain the difference from Checkov.
  • Use Amazon ECR basic and enhanced (Amazon Inspector) scanning for images after they leave the pipeline.
  • Write a gating policy — what blocks a merge, what blocks a release, what only raises a ticket — and enforce it with a small C# tool that reads SARIF.
  • Govern suppressions so that "ignore this finding" is a reviewed, expiring risk decision rather than a silent opt-out.

Prerequisites

  • Threat modelling with STRIDE — scanning finds known patterns; threat modelling finds design flaws. You need both.
  • Least privilege in practice — the pipeline's own IAM role must be narrow.
  • Module 3: .NET on AWS — a containerised ASP.NET Core API and an ECR repository.
  • Tools: .NET 10 SDK (or Docker), Git, a GitHub account (a public fork or personal repository keeps every tool in this lesson free), optionally the AWS CLI v2 with the learn-sandbox profile for the ECR section.

Why this matters in banking

In March 2025 a popular GitHub Action (tj-actions/changed-files) was compromised and rewritten to print CI secrets into public build logs. In March 2026 it happened again to a security tool: attackers with stolen credentials published a malicious Trivy release, force-pushed the tags of aquasecurity/trivy-action and setup-trivy to credential-stealing commits, and later pushed malicious Trivy images to Docker Hub (advisory GHSA-69fq-xp46-6x23 lists trivy-action v0.35.0 as the fixed version). The very scanner many teams use to find vulnerabilities became the vulnerability. Every pipeline that referenced the action by a moveable tag pulled the attacker's code with the repository's secrets in scope.

Now put that into a bank. Harbourline's pipeline holds a role that can push images to ECR and deploy the Payments Service. If a dependency, a scanner or a build step is compromised, an attacker can ship code that moves money. Regulators and card schemes expect the bank to show that changes to systems handling customer data and payments are reviewed and tested for known vulnerabilities before release — PCI DSS, for example, has explicit requirements on secure development and vulnerability identification, and UK and EU operational-resilience rules expect ICT change management. None of that is satisfied by "we have a scanner". It is satisfied by a process with evidence: what was scanned, what was found, who decided what, and what was released.

This lesson builds that process for one service — the Accounts API — so you can copy it to the others.

The idea in plain language

Automated security scanning is a set of robots that read your code, your packages, your container image and your infrastructure definitions, and compare them with known-bad patterns. Each robot is good at one thing:

FamilyReadsFindsCannot find
SAST (static application security testing)Your C# sourceSQL built from strings, path traversal, weak crypto calls, unsafe deserialisation, missing [Authorize] patternsBusiness-logic flaws (a customer can see another customer's account if they guess an ID)
SCA (software composition analysis)*.csproj, lock files, packages.lock.json, image layersNuGet packages with published CVEs; licencesVulnerabilities nobody has published yet
Secrets scanningEvery file and every commit in Git historyAWS access keys, connection strings, private keys, API tokensSecrets that look like ordinary text
Container image scanningThe built image (OS packages and app packages)Vulnerable openssl, libc, zlib in the base imageRuntime behaviour
IaC scanningCDK output, CloudFormation, TerraformPublic S3 buckets, unencrypted volumes, 0.0.0.0/0 on port 22, wildcards in IAM policiesWhether the design is right for the data

Each robot produces a list of findings. The hard part is not running the robots — that takes an afternoon. The hard part is deciding which findings stop a release, which can wait, and who is allowed to say "this one does not apply".

Analogy: a bank branch has several checks before cash leaves the vault: a counterfeit-note detector (SCA — known-bad items), a second cashier who watches the count (SAST — patterns of mistakes), a bag search at the door (secrets — nothing sensitive walks out), an inspection of the armoured van (image scanning) and a review of the vault's own locks (IaC). None of them proves the branch manager is honest — that needs separation of duties and audit, which is why scanning sits inside a wider control set.

What problem the AWS services and tools solve

AWS used to offer Amazon CodeGuru Reviewer for automated code review. It is now in maintenance and is not a sensible choice for new work (see the module's service availability notes). In 2025 AWS launched Amazon Inspector code security, which adds SAST, SCA and IaC scanning for GitHub and GitLab repositories alongside Inspector's long-standing EC2, ECR and Lambda scanning. Most banks still combine open-source or vendor scanners in CI with Inspector for what is deployed. This lesson uses free tools in the pipeline and AWS for the registry and runtime.

ToolFamilyWhere it runsLicence / cost (checked 2026-11-18)Notes
NuGet AuditSCAInside dotnet restoreFree, built into the SDKUses the GitHub Advisory Database via nuget.org. In .NET 10 NuGetAuditMode defaults to all (transitive packages too) for net10.0 projects
dotnet package list --vulnerableSCACLIFreeReport form; add --include-transitive
CodeQLSASTGitHub ActionsFree for public repositories; private repositories need GitHub Code Security ⚠ VERIFY current plan namebuild-mode: none works for C# without compiling
Semgrep Community EditionSASTAny CI or locallyFree (LGPL engine; registry rules have their own licences)Fast, easy custom rules
GitleaksSecretsLocally, pre-commit, ActionsFree CLI; the Action needs a free licence key for organisation repositoriesScans full history with fetch-depth: 0
TruffleHogSecretsLocally, ActionsFree (AGPL)Can verify whether a found key is live
TrivyImage, SCA, IaC, secretsLocally, ActionsFree (Apache-2.0)Pin the Action by commit SHA after the 2026 compromise
CheckovIaCLocally, ActionsFree (Apache-2.0)Terraform, CloudFormation, CDK output, Dockerfiles, GitHub Actions workflows
cdk-nagIaCInside cdk synthFreeRule packs such as AwsSolutionsChecks, plus HIPAA, NIST and PCI DSS 3.2.1 packs
cfn-nagIaCRuby gem or DockerFreeOlder, CloudFormation only; still common in banks' existing pipelines
Amazon ECR basic scanningImage (OS)AWS, on push or manualNo extra chargeAWS-native engine for OS packages
Amazon ECR enhanced scanningImage (OS + language)AWS via Amazon InspectorInspector pricing; 15-day free trial ⚠ VERIFYContinuous rescans when new CVEs appear
Amazon Inspector code securitySAST, SCA, IaCAWS, connected to GitHub/GitLabInspector pricing ⚠ VERIFYFindings in Inspector and Security Hub

Honest limitations. Scanners produce false positives (findings that are not real) and false negatives (real problems they miss). SCA only knows about published vulnerabilities. SAST has a hard time with reflection, dependency injection and data flowing through message queues. IaC scanners check configuration in isolation: a bucket can pass every rule and still be the wrong place for card data. And every scanner is itself software in your supply chain.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS / open-source equivalentWhat's different
GitHub Advanced Security for Azure DevOps (CodeQL, secret scanning, dependency scanning)CodeQL in GitHub Actions, or Amazon Inspector code securitySame CodeQL engine if you use GitHub; AWS has no Azure DevOps-native equivalent
Microsoft Defender for Cloud DevOps securityAmazon Inspector code security + Security HubInspector findings land in Security Hub with your runtime findings
Microsoft Defender for Containers (ACR image scanning)ECR basic scanning / ECR enhanced scanning (Inspector)Enhanced scanning rescans images continuously as new CVEs are published
Roslyn security analyzers (CA2100, CA3001–CA3012, CA5350…)The same analyzers — they are part of the .NET SDKTurn them on with AnalysisMode and TreatWarningsAsErrors; they cost nothing
dotnet list package --vulnerable / NuGet AuditSameIdentical — it is a .NET feature, not an Azure one
Azure Policy for ARM/Bicep, PSRule for AzureCheckov, cdk-nag, cfn-nag, CloudFormation GuardSeveral tools; choose by IaC language
Azure Pipelines approvals and checksGitHub environments with required reviewers, branch protection, CodePipeline manual approvalGate on SARIF results instead of a single vendor dashboard

Architecture

The pipeline has three stages, each with a different job.

Security-boundary view

  • Pull-request jobs get no AWS credentials. They run on code from a branch that may be malicious (a contributor's fork, or a compromised developer account). They only read code and write SARIF.
  • The release job runs only on main, inside a GitHub environment with required reviewers, and gets a short-lived AWS role through OIDC (no stored access keys). Its IAM policy allows pushing to one ECR repository and nothing else.
  • Runtime scanning (Inspector) keeps checking the image after release, because new CVEs are published every day for code that has not changed.
  • Every third-party action is pinned to a full commit SHA, so a moved tag cannot change what runs.

Step-by-step implementation

Inventory what the pipeline builds

List the artefacts for the Accounts API: the C# solution, Directory.Packages.props, the Dockerfile, and the CDK app (or Terraform) under infra/. Each artefact type maps to one scanner family. Write the list down — it becomes the "scope" section of your scanning standard, and auditors will ask for it.

Turn on the free controls inside the .NET SDK

Before adding any external tool, make the compiler and NuGet do security work. In Directory.Build.props enable NuGet Audit with transitive scanning, the .NET security analyzers, and make high and critical advisories errors. This catches a large class of problems on every developer's machine, not just in CI.

Stop secrets at the developer's laptop

Add a pre-commit hook running Gitleaks. A secret blocked before git commit never reaches GitHub, so it never needs rotating. CI scanning is the safety net, not the first line.

Add the pull-request workflow

Create .github/workflows/security.yml with one job per scanner. Each job writes SARIF and uploads it with github/codeql-action/upload-sarif. Give the workflow contents: read and security-events: write only. Pin every action to a commit SHA.

Add IaC rules where the IaC is written

Add cdk-nag to the CDK app, so cdk synth fails on violations. Run Checkov over the synthesised templates (cdk.out) and any Terraform. Use cfn-nag only if the bank already depends on it.

Write the gating policy, then enforce it

Agree with the security team which findings block a merge. A typical starting point is in the Banking use case. Encode it in the SARIF gate tool (below) and make that job a required status check on the main branch.

Govern suppressions

Create security/suppressions.json. Every suppression has a rule ID, a path, a reason, an approver and an expiry date. Protect the file with CODEOWNERS so only the security champion group can approve changes. The gate tool ignores expired suppressions.

Keep scanning after release

Turn on ECR enhanced scanning for the repository, send Inspector findings to Security Hub, and route critical findings on running images to the team's queue through EventBridge.

AWS Console instructions

ECR scanning

  1. Console → Amazon ECR → Private registry → Settings → Scanning configuration (in the left menu under Private registry).
  2. Choose Basic scanning for the free OS-only option, or Enhanced scanning to use Amazon Inspector. Enhanced scanning asks you to enable Inspector for ECR if it is not already enabled.
  3. Add a filter (for example hl-m05-*) with Scan on push, or Continuous scanning for enhanced.
  4. After pushing an image: ECR → Repositories → hl-m05-accounts-api → (image tag) → Vulnerabilities (basic) or Amazon Inspector → Findings → By container image (enhanced).

Inspector code security (overview only; not used in this lesson's free path)

  • Console → Amazon Inspector → Code security → Integrations to connect a GitHub organisation through the Amazon Inspector GitHub App, then create a scan configuration. ⚠ VERIFY exact menu labels; the feature is new and the console changes often.

AWS CLI

# 1. Create a repository with scan-on-push (basic scanning) and KMS encryption.
aws ecr create-repository \
  --repository-name hl-m05-accounts-api \
  --image-scanning-configuration scanOnPush=true \
  --encryption-configuration encryptionType=KMS \
  --image-tag-mutability IMMUTABLE \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m05-l24 Key=Environment,Value=learn Key=Owner,Value=you \
  --profile learn-sandbox --region us-east-1

# 2. Show the registry-level scanning configuration (BASIC or ENHANCED).
aws ecr get-registry-scanning-configuration --profile learn-sandbox

# 3. Read basic-scanning findings for one image tag.
aws ecr describe-image-scan-findings \
  --repository-name hl-m05-accounts-api \
  --image-id imageTag=1.0.0 \
  --query 'imageScanFindings.findingSeverityCounts' \
  --profile learn-sandbox

# 4. (Optional, starts Inspector billing after the trial) switch the registry to enhanced scanning
#    for repositories that match hl-m05-*, rescanning continuously.
aws ecr put-registry-scanning-configuration \
  --scan-type ENHANCED \
  --rules '[{"scanFrequency":"CONTINUOUS_SCAN","repositoryFilters":[{"filter":"hl-m05-*","filterType":"WILDCARD"}]}]' \
  --profile learn-sandbox

# 5. List critical Inspector findings for ECR images.
aws inspector2 list-findings \
  --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_ECR_CONTAINER_IMAGE"}],"severity":[{"comparison":"EQUALS","value":"CRITICAL"}]}' \
  --max-results 20 --profile learn-sandbox

Local equivalents that cost nothing and need no account:

# SCA: list vulnerable packages, including transitive ones (.NET 10 noun-first syntax).
dotnet package list --vulnerable --include-transitive

# Fix: move every vulnerable package to the first non-vulnerable version.
dotnet package update --vulnerable

# Secrets: scan the whole Git history of the current repository.
docker run --rm -v "$PWD:/repo" ghcr.io/gitleaks/gitleaks:latest git /repo --redact -v

# Image: scan a locally built image, failing on fixable HIGH/CRITICAL.
docker build -t hl-accounts-api:dev .
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
  image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 hl-accounts-api:dev

# IaC: scan CDK output and Terraform.
docker run --rm -v "$PWD:/src" bridgecrew/checkov:latest -d /src/infra --framework cloudformation,terraform

⚠ Learning shortcut — not for production

The local commands above use :latest image tags for brevity. In a bank's pipeline, pin scanner images by digest (image@sha256:…) and update them through a reviewed pull request (Dependabot or Renovate can raise these automatically). A scanner pulled by a moving tag is exactly how the 2026 Trivy compromise reached pipelines.

Infrastructure as Code

The IaC itself should be scanned, and the pipeline's AWS access should be defined as code too.

infra/cdk/Program.cs
using Amazon.CDK;
using Amazon.CDK.AWS.ECR;
using Amazon.CDK.AWS.IAM;
using Cdklabs.CdkNag;
using Constructs;

var app = new App();
var stack = new PipelineSupportStack(app, "hl-m05-pipeline-support", new StackProps
{
    Env = new Amazon.CDK.Environment { Region = "us-east-1" },
});

// Tags required on every lab resource (CONVENTIONS.md §3).
Tags.Of(app).Add("Project", "cea-lab");
Tags.Of(app).Add("Lab", "m05-l24");
Tags.Of(app).Add("Environment", "learn");
Tags.Of(app).Add("Owner", "you");

// cdk-nag v3: the AWS Solutions rule pack runs as a CDK validation plugin. Unacknowledged findings fail `cdk synth`.
Validations.Of(app).AddPlugins(new AwsSolutionsChecks(app, new NagPackProps { Verbose = true }));

app.Synth();

public sealed class PipelineSupportStack : Stack
{
    public PipelineSupportStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
    {
        // Image repository: immutable tags, scan on push, AWS-managed KMS encryption.
        var repo = new Repository(this, "AccountsApiRepo", new RepositoryProps
        {
            RepositoryName = "hl-m05-accounts-api",
            ImageTagMutability = TagMutability.IMMUTABLE,
            ImageScanOnPush = true,
            Encryption = RepositoryEncryption.KMS,
            RemovalPolicy = RemovalPolicy.DESTROY,
            EmptyOnDelete = true,
        });

        // GitHub OIDC provider: lets Actions get short-lived credentials without stored keys.
        var github = new OpenIdConnectProvider(this, "GitHubOidc", new OpenIdConnectProviderProps
        {
            Url = "https://token.actions.githubusercontent.com",
            ClientIds = ["sts.amazonaws.com"],
        });

        // Release role: only the main branch, only the 'release' environment, of one repository.
        var releaseRole = new Role(this, "ReleaseRole", new RoleProps
        {
            RoleName = "hl-m05-release",
            MaxSessionDuration = Duration.Hours(1),
            AssumedBy = new WebIdentityPrincipal(github.OpenIdConnectProviderArn, new Dictionary<string, object>
            {
                ["StringEquals"] = new Dictionary<string, object>
                {
                    ["token.actions.githubusercontent.com:aud"] = "sts.amazonaws.com",
                    ["token.actions.githubusercontent.com:sub"] = "repo:example-org/harbourline-accounts-api:environment:release",
                },
            }),
        });

        // Push to this one repository only. GetAuthorizationToken has no resource-level control.
        repo.GrantPush(releaseRole);

        // cdk-nag v3 acknowledgments match the exact finding ID and must carry a reason.
        Validations.Of(this).Acknowledge(
            new Acknowledgment
            {
                Id = "AwsSolutions-IAM5[Resource::*]",
                Reason = "ecr:GetAuthorizationToken requires Resource '*'; all other actions are scoped to one repository. Approved: security-champions, expires 2027-05-18.",
            });
    }
}

AwsSolutionsChecks is one of several packs; cdk-nag also ships HIPAASecurityChecks, NIST80053R5Checks and PCIDSS321Checks. A PCI DSS rule pack is a useful hint list, not evidence of compliance — and it targets PCI DSS v3.2.1, which has been retired in favour of v4.x.

Complete code

Three pieces: the repository-wide .NET settings, the GitHub Actions workflow, and a C# gate tool that applies the bank's policy to all SARIF files.

1. Directory.Build.props — security in every build

Directory.Build.props
<Project>
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>

    <!-- NuGet Audit: on by default; be explicit so nobody turns it off quietly. -->
    <NuGetAudit>true</NuGetAudit>
    <NuGetAuditMode>all</NuGetAuditMode>        <!-- direct AND transitive packages -->
    <NuGetAuditLevel>low</NuGetAuditLevel>      <!-- report everything ... -->

    <!-- ... but only high/critical break the build; low/moderate stay as warnings
         and are handled by the scheduled audit pipeline instead of blocking a hotfix. -->
    <WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902</WarningsNotAsErrors>
    <WarningsAsErrors>$(WarningsAsErrors);NU1903;NU1904</WarningsAsErrors>

    <!-- .NET code-quality analyzers, including the CA2xxx/CA3xxx/CA5xxx security rules. -->
    <EnableNETAnalyzers>true</EnableNETAnalyzers>
    <AnalysisMode>Recommended</AnalysisMode>
    <AnalysisModeSecurity>All</AnalysisModeSecurity>

    <!-- Reproducible restore: CI fails if packages.lock.json does not match. -->
    <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
    <RestoreLockedMode Condition="'$(CI)' == 'true'">true</RestoreLockedMode>
  </PropertyGroup>
</Project>

2. .github/workflows/security.yml

The SHAs below are placeholders written as <sha-for-vX>. Replace each with the full 40-character commit SHA of the release you reviewed (shown on the action's Releases page), and keep the version in a trailing comment so Dependabot can update it.

.github/workflows/security.yml
name: security

on:
  pull_request:
    branches: [main]
  push:
    branches: [main]
  schedule:
    - cron: "17 3 * * 1"   # weekly: catch NEW advisories for UNCHANGED code

# Least privilege for the GITHUB_TOKEN. No job here gets AWS credentials.
permissions:
  contents: read

concurrency:
  group: security-${{ github.ref }}
  cancel-in-progress: true

jobs:
  sast-codeql:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write   # upload SARIF to code scanning
    steps:
      - uses: actions/checkout@<sha-for-v6>          # v6
      - uses: github/codeql-action/init@<sha-for-v4> # v4
        with:
          languages: csharp
          build-mode: none           # analyse C# without compiling
          queries: security-extended
      - uses: github/codeql-action/analyze@<sha-for-v4> # v4
        with:
          category: codeql-csharp
          output: sarif-results
          upload: always
      - uses: actions/upload-artifact@<sha-for-v5>   # v5 ⚠ VERIFY current major
        with:
          name: sarif-codeql
          path: sarif-results

  sca-nuget:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<sha-for-v6>
      - uses: actions/setup-dotnet@<sha-for-v5>     # v5 ⚠ VERIFY current major
        with:
          global-json-file: global.json
      # Restore fails on NU1903/NU1904 because of Directory.Build.props.
      - run: dotnet restore Harbourline.Accounts.slnx
        env:
          CI: "true"
      # Human-readable report for the PR log, including transitive packages.
      - run: dotnet package list --project Harbourline.Accounts.slnx --vulnerable --include-transitive

  secrets-gitleaks:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write     # gitleaks-action comments on the PR
    steps:
      - uses: actions/checkout@<sha-for-v6>
        with:
          fetch-depth: 0       # full history: a secret deleted later is still in Git
      - uses: gitleaks/gitleaks-action@<sha-for-v3> # v3
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }} # only needed for organisation repos

  iac-checkov:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@<sha-for-v6>
      - uses: bridgecrewio/checkov-action@<sha-for-v12> # v12
        with:
          directory: infra
          framework: terraform,cloudformation,dockerfile,github_actions
          output_format: cli,sarif
          output_file_path: console,checkov.sarif
          soft_fail: true      # the gate job decides; Checkov just reports
      - uses: github/codeql-action/upload-sarif@<sha-for-v4>
        if: always()
        with:
          sarif_file: checkov.sarif
          category: checkov
      - uses: actions/upload-artifact@<sha-for-v5>
        if: always()
        with: { name: sarif-checkov, path: checkov.sarif }

  image-trivy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@<sha-for-v6>
      - run: docker build -t hl-accounts-api:${{ github.sha }} -f src/Harbourline.Accounts.Api/Dockerfile .
      - uses: aquasecurity/trivy-action@<sha-for-v0.36.0> # v0.36.0 — never a tag older than v0.35.0
        with:
          image-ref: hl-accounts-api:${{ github.sha }}
          format: sarif
          output: trivy.sarif
          severity: CRITICAL,HIGH,MEDIUM
          ignore-unfixed: true
          exit-code: "0"        # the gate job decides
      - uses: github/codeql-action/upload-sarif@<sha-for-v4>
        if: always()
        with:
          sarif_file: trivy.sarif
          category: trivy-image
      - uses: actions/upload-artifact@<sha-for-v5>
        if: always()
        with: { name: sarif-trivy, path: trivy.sarif }

  gate:
    # Make THIS job the required status check on main.
    needs: [sast-codeql, sca-nuget, secrets-gitleaks, iac-checkov, image-trivy]
    if: always()
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<sha-for-v6>
      - uses: actions/setup-dotnet@<sha-for-v5>
        with: { global-json-file: global.json }
      - uses: actions/download-artifact@<sha-for-v5>  # ⚠ VERIFY current major
        with: { pattern: sarif-*, path: sarif, merge-multiple: true }
      # Fail if any upstream scanner job itself failed (NuGet audit, Gitleaks).
      - if: contains(needs.*.result, 'failure')
        run: echo "A scanner job failed - see its log." && exit 1
      - run: dotnet run tools/SarifGate/SarifGate.cs -- sarif security/suppressions.json

3. tools/SarifGate/SarifGate.cs — the policy as code

.NET 10 can run a single .cs file with dotnet run file.cs, so the gate needs no project file.

tools/SarifGate/SarifGate.cs
// Harbourline SARIF gate: applies the bank's scanning policy to every *.sarif file in a folder.
// Usage: dotnet run SarifGate.cs -- <sarif-folder> <suppressions.json>
// Exit code 0 = pass, 1 = blocking findings, 2 = bad input.
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;

if (args.Length != 2 || !Directory.Exists(args[0]) || !File.Exists(args[1]))
{
    Console.Error.WriteLine("Usage: SarifGate <sarif-folder> <suppressions.json>");
    return 2;
}

var today = DateOnly.FromDateTime(DateTime.UtcNow);
var suppressions = LoadSuppressions(args[1], today, out var expired);
foreach (var s in expired)
{
    Console.WriteLine($"::warning::Suppression {s.Id} for {s.RuleId} expired on {s.Expires:yyyy-MM-dd} and is ignored.");
}

var findings = new List<Finding>();
foreach (var file in Directory.EnumerateFiles(args[0], "*.sarif", SearchOption.AllDirectories))
{
    findings.AddRange(ReadSarif(file));
}

var blocking = 0;
foreach (var f in findings.OrderByDescending(f => f.Score))
{
    var suppressed = suppressions.FirstOrDefault(s => s.Matches(f));
    var decision = suppressed is not null ? $"SUPPRESSED by {suppressed.Id}"
                 : f.Score >= 7.0 ? "BLOCK"
                 : f.Score >= 4.0 ? "TICKET (fix within 30 days)"
                 : "INFO";
    if (decision == "BLOCK")
    {
        blocking++;
        // GitHub annotation: shows the finding on the PR's changed file.
        Console.WriteLine($"::error file={f.Path},line={f.Line}::[{f.Tool}] {f.RuleId} ({f.Score:0.0}) {f.Message}");
    }
    else
    {
        Console.WriteLine($"{decision,-28} [{f.Tool}] {f.RuleId} ({f.Score:0.0}) {f.Path}:{f.Line}");
    }
}

Console.WriteLine($"Findings: {findings.Count}, blocking: {blocking}, active suppressions: {suppressions.Count}");
return blocking == 0 ? 0 : 1;

static IEnumerable<Finding> ReadSarif(string path)
{
    var root = JsonNode.Parse(File.ReadAllText(path))!;
    foreach (var run in root["runs"]?.AsArray() ?? [])
    {
        var tool = run!["tool"]?["driver"]?["name"]?.GetValue<string>() ?? Path.GetFileName(path);

        // Rule metadata: GitHub's convention puts a CVSS-like score in properties."security-severity".
        var ruleScores = new Dictionary<string, double>(StringComparer.Ordinal);
        foreach (var rule in run["tool"]?["driver"]?["rules"]?.AsArray() ?? [])
        {
            var id = rule!["id"]?.GetValue<string>();
            var sev = rule["properties"]?["security-severity"]?.ToString();
            if (id is not null && double.TryParse(sev, NumberStyles.Float, CultureInfo.InvariantCulture, out var score))
            {
                ruleScores[id] = score;
            }
        }

        foreach (var result in run["results"]?.AsArray() ?? [])
        {
            // Results already suppressed in source (e.g. by the tool) are listed in "suppressions".
            if (result!["suppressions"] is JsonArray { Count: > 0 })
            {
                continue;
            }
            var ruleId = result["ruleId"]?.GetValue<string>() ?? "unknown";
            var level = result["level"]?.GetValue<string>() ?? "warning";
            var score = ruleScores.TryGetValue(ruleId, out var s) ? s : LevelToScore(level);
            var loc = result["locations"]?[0]?["physicalLocation"];
            yield return new Finding(
                tool,
                ruleId,
                score,
                loc?["artifactLocation"]?["uri"]?.GetValue<string>() ?? "",
                loc?["region"]?["startLine"]?.GetValue<int>() ?? 1,
                (result["message"]?["text"]?.GetValue<string>() ?? "").ReplaceLineEndings(" "));
        }
    }
}

// Fallback when a tool gives no numeric severity: SARIF "error" counts as high.
static double LevelToScore(string level) => level switch
{
    "error" => 7.0,
    "warning" => 5.0,
    "note" => 2.0,
    _ => 0.0,
};

static List<Suppression> LoadSuppressions(string path, DateOnly today, out List<Suppression> expired)
{
    var all = JsonSerializer.Deserialize<List<Suppression>>(File.ReadAllText(path),
        new JsonSerializerOptions(JsonSerializerDefaults.Web)) ?? [];
    foreach (var s in all)
    {
        // Governance: every field is mandatory, and no suppression may last more than 180 days.
        if (string.IsNullOrWhiteSpace(s.Reason) || string.IsNullOrWhiteSpace(s.ApprovedBy))
        {
            throw new InvalidOperationException($"Suppression {s.Id} needs a reason and an approver.");
        }
        if (s.Expires > today.AddDays(180))
        {
            throw new InvalidOperationException($"Suppression {s.Id} expires more than 180 days ahead.");
        }
    }
    expired = all.Where(s => s.Expires < today).ToList();
    return all.Where(s => s.Expires >= today).ToList();
}

record Finding(string Tool, string RuleId, double Score, string Path, int Line, string Message);

record Suppression(string Id, string RuleId, string PathPrefix, string Reason, string ApprovedBy, DateOnly Expires)
{
    public bool Matches(Finding f) =>
        string.Equals(RuleId, f.RuleId, StringComparison.Ordinal) &&
        f.Path.StartsWith(PathPrefix, StringComparison.Ordinal);
}

4. security/suppressions.json

security/suppressions.json
[
  {
    "id": "SUP-2026-014",
    "ruleId": "CVE-2026-00000",
    "pathPrefix": "hl-accounts-api",
    "reason": "Fictional example: vulnerable function in libexample is only reachable through the CLI tool, which is not present in the runtime image. Risk accepted until the base image ships the fix.",
    "approvedBy": "security-champions (ticket SEC-1234)",
    "expires": "2027-01-31"
  }
]

Protect it with CODEOWNERS:

.github/CODEOWNERS
/security/suppressions.json   @example-org/security-champions
/.github/workflows/           @example-org/platform-security

Code explained line by line

Directory.Build.props

  1. NuGetAuditMode all — audits transitive packages. For net10.0 this is already the default; stating it protects against a project that multi-targets an older framework.
  2. WarningsNotAsErrors with NU1901;NU1902 — because the solution uses TreatWarningsAsErrors, a newly published low advisory would otherwise break every build overnight, including an urgent fix. Low and moderate stay visible as warnings.
  3. WarningsAsErrors with NU1903;NU1904 — high and critical advisories stop the build.
  4. AnalysisModeSecurity All — enables every rule in the Security category of the built-in .NET analyzers (for example CA2100 SQL injection review, CA5350/CA5351 weak hash algorithms, CA2326/CA2327 unsafe JSON type handling).
  5. RestoreLockedMode in CI — restore fails if packages.lock.json does not match, so a dependency cannot change silently between review and build.

security.yml

  1. permissions: contents: read at the top — the GITHUB_TOKEN default is narrowed for every job; jobs add only what they need.
  2. schedule — a weekly run on unchanged code catches newly published CVEs. Without it, a service that nobody touches for months is never re-checked.
  3. build-mode: none — CodeQL extracts C# without compiling; results can be slightly less precise than a full build, which is an accepted trade-off for speed.
  4. queries: security-extended — adds lower-precision security queries to the default suite; expect more findings to triage.
  5. fetch-depth: 0 — Gitleaks must see every commit. A key that was committed and then deleted is still in history and still valid.
  6. soft_fail: true and exit-code: "0" — the scanners report but do not decide. One place (the gate) applies one policy, so the rules are consistent and auditable.
  7. needs: plus if: always() — the gate runs even when a scanner job fails, and then fails itself.
  8. @<sha-…> — a commit SHA cannot be moved by whoever controls the action's repository; a tag can.

SarifGate.cs

  1. Top-level statements and return codes — the file runs as a script; exit code 1 fails the job.
  2. LoadSuppressions — rejects any suppression without a reason or approver and any that lasts more than 180 days; expired ones are reported and ignored, so risk acceptances cannot quietly become permanent.
  3. security-severity — CodeQL, Trivy and others put a 0–10 score on each rule in this property; the gate falls back to the SARIF level when it is missing.
  4. Results with a suppressions array are skipped — that is how SARIF marks in-source suppressions some tools honour.
  5. Thresholds — 7.0 and above blocks, 4.0–6.9 creates a ticket with a 30-day SLA, below 4.0 is informational. These numbers belong to the bank's vulnerability-management standard, not to the developer.
  6. ::error file=…,line=…:: — GitHub workflow command syntax; the finding appears as an annotation on the pull request's diff.

Security considerations

⚠ Learning shortcut — not for production

The workflow lets the image scan run on a pull-request build and does not sign the image. In production, build once, generate an SBOM (Trivy can emit CycloneDX), sign the image (for example with AWS Signer or Sigstore Cosign) and deploy by digest, so what was scanned is provably what runs.

  • The pipeline is a production system. Its role can deploy code that moves money. Apply the same controls: least privilege, MFA for people who change it, change review for workflow files (CODEOWNERS on .github/workflows/), and logging.
  • No secrets in pull-request jobs. Never use pull_request_target with a checkout of the PR's head code: that combination runs untrusted code with repository secrets.
  • OIDC, not access keys. The release role trusts GitHub's OIDC provider with a sub condition naming one repository and one environment. A wildcard sub such as repo:example-org/* lets any repository in the organisation deploy.
  • Scanner output is sensitive. A list of exploitable vulnerabilities in a payments service is useful to an attacker. Keep code scanning results private and limit who can read them.
  • Secrets found = secrets rotated. Deleting a leaked key from Git is not remediation. Revoke or rotate it first, check CloudTrail for its use, then clean history if policy requires.
  • Do not log secret values. Run Gitleaks with --redact so CI logs do not become a second leak.

Banking use case

Harbourline's Secure SDLC standard (fictional, written by the CISO's team) contains this scanning policy for every service that handles customer or payment data:

FindingOn pull requestOn release to productionRemediation SLA
Verified live secretBlockBlockRotate within 4 hours; incident ticket
Any secret patternBlockBlockRemove and rotate if it was ever real
Critical (9.0–10.0), fix availableBlockBlockFix before merge
High (7.0–8.9), fix availableBlockBlockFix before merge, or approved suppression ≤ 30 days
Critical or high, no fix availableTicketRelease allowed with documented compensating controlReview weekly
Medium (4.0–6.9)TicketAllowed30 days
Low / informationalReport onlyAllowedNext maintenance cycle
IaC: public data store, unencrypted data store, 0.0.0.0/0 admin port, IAM *:*BlockBlockFix before merge

Suppression governance. A developer may propose a suppression in a pull request. Only the security champions group (via CODEOWNERS) may approve it. Each one expires within 180 days, links to a ticket, and is reported monthly to the risk committee as part of the technology risk register. That monthly report — count of open findings by severity, ages, suppressions granted and expired — is the evidence the bank shows internal audit. It is also the kind of evidence a PCI DSS assessor may look at for secure-development requirements; whether it is sufficient is the assessor's decision (see PCI DSS on AWS).

Separation of duties. The developer who writes the code cannot approve their own suppression, and the person who approves the release environment is not the author of the change. The full role design is in Federation and segregation of duties.

Common mistakes

  • Turning every scanner to "block everything" on day one → hundreds of old findings block all work, so teams disable the scanner. → Baseline existing findings, block only new high/critical findings, and burn the backlog down on a schedule.
  • Running scanners only on pull requests → unchanged services never get re-checked against new CVEs. → Add a scheduled run and ECR continuous scanning.
  • Pinning actions by tag → a compromised maintainer account moves the tag. → Pin by SHA and update via Dependabot.
  • Suppressing in many places (#pragma warning disable, checkov:skip, .trivyignore, NuGetAuditSuppress) with no reasons → nobody knows what risk was accepted. → Require reason/approver/expiry in every form and inventory them in one report.
  • Treating ignore-unfixed as "no risk" → an unfixable critical CVE still exists. → Record it and consider a compensating control (different base image, removing the package, network restriction).
  • Scanning the Dockerfile but not the image → the base image tag mcr.microsoft.com/dotnet/aspnet:10.0 changes underneath you. → Scan the built image and pin the base by digest.
  • Assuming CodeQL build-mode: none sees generated code → source generators' output may be missed. → Use autobuild or a manual build for services that rely heavily on generated code.

Troubleshooting

SymptomLikely causeFix
error NU1903: Package 'X' 1.2.3 has a known high severity vulnerabilityNuGet Audit found an advisory in a direct or transitive packagedotnet nuget why <project> X to find the path; update the closest direct package or pin a fixed version in Directory.Packages.props
warning NU1900: Error occurred while getting package vulnerability dataRestore cannot reach the audit source (private feed, proxy)Add an auditSources entry for https://data.nuget.org/v3/index.json in nuget.config, or allow it through the proxy
Upload SARIF fails with "Resource not accessible by integration"Job lacks security-events: writeAdd it to that job's permissions
Gitleaks finds nothing in a PR you know contains a keyShallow checkoutSet fetch-depth: 0
Gitleaks Action fails on an organisation repository with a licence errorMissing GITLEAKS_LICENSERequest a free key and store it as an encrypted secret, or run the Gitleaks CLI image instead
Trivy reports hundreds of OS CVEsFull Debian-based imageUse mcr.microsoft.com/dotnet/aspnet:10.0 Alpine or Azure Linux / chiseled variants ⚠ VERIFY current tag names; add ignore-unfixed
cdk synth fails with AwsSolutions-IAM5Wildcard in a generated policyNarrow it; if unavoidable, Validations.Of(...).Acknowledge(...) with the exact finding ID (for example AwsSolutions-IAM5[Resource::*]) and a specific reason
ECR describe-image-scan-findings returns ScanNotFoundExceptionRegistry uses enhanced scanning, or scan not yet completeUse aws inspector2 list-findings, or wait and retry
Checkov flags CKV_GHA_* on your workflowWorkflow security rules (e.g. unpinned actions, broad permissions)Fix them — these are real supply-chain risks

Cost and cleanup

Cost: free on the main path.

  • GitHub Actions minutes, CodeQL and code scanning are free for public repositories. For private repositories, Actions minutes are metered and CodeQL/code scanning need a paid GitHub security product ⚠ VERIFY current plan names and prices.
  • All scanners used locally are free and open source.
  • ECR: storage is about USD 0.10 per GB-month ⚠ VERIFY; a single 100 MB image deleted the same day costs a fraction of a cent. Basic scanning has no extra charge.
  • Enhanced scanning and Inspector code security are billed through Amazon Inspector after its free trial. Skip them or disable straight after the exercise.

Teardown for the optional AWS section:

# Switch the registry back to basic scanning if you enabled enhanced.
aws ecr put-registry-scanning-configuration --scan-type BASIC --rules '[]' --profile learn-sandbox

# Delete the repository and all images.
aws ecr delete-repository --repository-name hl-m05-accounts-api --force --profile learn-sandbox

# If you enabled Inspector only for this lesson, disable ECR scanning in Inspector.
aws inspector2 disable --resource-types ECR --profile learn-sandbox

# Check nothing tagged for the lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --profile learn-sandbox

If you deployed the CDK stack: cdk destroy hl-m05-pipeline-support. For Terraform: terraform destroy.

Exercises

  • 🟢 Guided: Add the Directory.Build.props above to a copy of the Accounts API, then add a deliberately old package (for example an old System.Text.Json version with a published advisory ⚠ VERIFY a current example). Run dotnet restore and record which NU190x code appears. Fix it with dotnet package update --vulnerable.
  • 🟡 Challenge: Create a test commit containing a fake AWS key in AWS's documented example format (AKIAIOSFODNN7EXAMPLE) and confirm Gitleaks blocks it both in a pre-commit hook and in CI. Then remove it in a second commit and prove that a shallow-clone CI scan misses it while fetch-depth: 0 finds it.
  • 🔴 Live problem: It is Friday 16:00. A critical CVE (CVSS 9.8) was published an hour ago for a transitive package in the Payments Service. The gate now blocks a pull request that contains an urgent fix for a production defect in standing-order processing. The package maintainers have not released a fix. Decide what happens, who decides, and what you record.

Assignment

Add a security/ folder to your portfolio repository containing: the workflow (with real pinned SHAs), the SARIF gate, a suppressions.json with one example entry, and a one-page SCANNING-STANDARD.md stating scope, tools, thresholds, SLAs and suppression rules. Include a screenshot-free description of a run: how many findings per tool and what you did with each.

Solutions

Knowledge check

Interview questions

  • "How would you add security scanning to an existing .NET pipeline without stopping delivery?" — Start with NuGet Audit and the built-in analyzers, add secrets scanning (blocking), then SAST, IaC and image scanning in report-only mode. Baseline existing findings, block only new high/critical, and set SLAs for the backlog. One gate applies one written policy.
  • "What can SAST not find?" — Business-logic and authorisation flaws, such as a customer reading another customer's account by changing an ID. That is why you also threat-model (STRIDE) and do code review against a checklist.
  • "A secret was committed and removed in the next commit. Is that fine?" — No. It is in Git history and may be in forks and CI logs. Revoke or rotate it immediately, check CloudTrail for its use, then clean history if policy requires.
  • "How do you secure the pipeline itself?" — OIDC roles scoped to repository and environment, no secrets in PR jobs, actions pinned by SHA, CODEOWNERS on workflow files, protected environments with reviewers, and logging of deployments.
  • "What is SARIF and why does it matter?" — The Static Analysis Results Interchange Format, a JSON standard for scanner output. It lets one gate, one dashboard and one evidence report handle many tools.

Certification practice

Completion checklist

  • I can name the five scanner families and one thing each cannot find
  • I enabled NuGet Audit with high/critical as errors and ran dotnet package list --vulnerable --include-transitive
  • I ran Gitleaks over full history and understood why fetch-depth: 0 matters
  • I scanned an image with Trivy and IaC with Checkov or cdk-nag
  • I wrote a gating policy and a suppression with reason, approver and expiry
  • I pinned every third-party action to a commit SHA
  • I deleted any ECR repository and confirmed enhanced scanning and Inspector are off

Key takeaways

  • Five scanner families find different defects; none finds business-logic flaws, which is why threat modelling and code review still matter.
  • Start with what .NET gives you free: NuGet Audit (transitive by default for net10.0) and the built-in security analyzers.
  • Scanners report; one gate applies one written policy — block new high/critical, ticket the rest with SLAs.
  • Suppressions are risk decisions: reason, independent approver, expiry, inventory.
  • The pipeline is production: pin actions by SHA, no secrets in PR jobs, OIDC roles scoped to repository and environment, and keep scanning images after release with ECR enhanced scanning. Scanning results are evidence for auditors, not proof of compliance.

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