All lessons · Guided routes

Capstone 5 of 10

Capstone 5: A pipeline that ships only what it can trust

An auditor asks how you know what is in production, who built it, and that nothing vulnerable or unsigned can get there. You build a nine-gate pipeline and prove that each gate blocks the problem it exists for.

What you build

  1. Unit tests

    The pipeline stops if a change breaks the service.

    Lessons: Python Testing, Typing, and Shipping Tools, From Commit to Running Code

  2. Static analysis

    Bandit (1.9.4) at medium severity and above; every suppression must name the rule and give a reason.

    Lessons: Application Security Testing in the Pipeline: SAST, SCA, Secrets, IaC, Containers, DAST, and Prioritisation

  3. Dependency audit

    pip-audit (2.10.1) checks the pinned tools the pipeline installs against known vulnerabilities.

    Lessons: Software Supply Chain: SBOMs, Provenance, and Signing

  4. Secret scan

    Trivy finds a cloud access key committed by mistake, before it is built into anything.

    Lessons: Least Privilege and Secrets, Vault & Secrets Management

  5. Image scan

    The build fails on fixable CRITICAL vulnerabilities in the image.

    Lessons: Container & Supply Chain Security

  6. SBOM

    Syft writes a CycloneDX software bill of materials for the image.

    Lessons: Software Supply Chain: SBOMs, Provenance, and Signing

  7. Sign and attest

    Cosign (2.4.1) signs the image digest in a local registry and attaches the SBOM as a signed attestation.

    Lessons: Secret Rotation, Secretless Workloads, and Verifying Signatures and SBOMs at Deploy

  8. Policy

    Conftest (0.56.0, OPA) checks the Deployment manifest: digest pinned, non-root, read-only, no escalation, capabilities dropped, limits set. The policy has its own tests.

    Lessons: Policy as Code with OPA and Kubernetes, Kubernetes Admission Control: Webhooks, ValidatingAdmissionPolicy, and Failing Safely

  9. Deploy what is signed

    The deploy step verifies the signature and the attestation, and refuses tags, unsigned images, and images signed with another key.

    Lessons: Kubernetes Security

Before you start

ToolVersion
docker24 or later
trivy0.50 or later
syft1.0 or later
python3 with venv3.10 or later
jq1.6 or later
curlany

Ports: 18085, 5002 on 127.0.0.1. Resources: About 1 GB of disk for images and tools.

What it creates (and the reset removes): containers cap-sec-registry and cap-sec-orders; images cap-sec-orders:* and localhost:5002/orders:*; a throwaway cosign key pair and a Python virtual environment in ~/labs/capstones/devsecops. Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.

Get the files

One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.

mkdir -p ~/labs && cd ~/labs
curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz
tar -xzf capstones-lab.tar.gz && cd capstones-lab
ls

Run it

All in one, with the reset afterwards even if a step fails:

bash run.sh 05-devsecops

Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):

bash 05-devsecops/setup.sh
bash 05-devsecops/verify.sh
bash 05-devsecops/reset.sh

Expected output

This is a real run of run.sh 05-devsecops, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.

== 1. Install the pinned pipeline tools in a virtual environment
bandit 1.9.4
pip-audit 2.10.1

== 2. Start a local registry and create a signing key pair
cosign.key
cosign.pub

== 3. Run the pipeline

== Pipeline for orders 1.0.0
  gate 1  unit tests                         pass
  gate 2  static analysis (bandit)           pass
  gate 3  dependency audit (pip-audit)       pass
  gate 4  secret scan (trivy)                pass
  gate 5  build + image scan (CRITICAL)      pass
  gate 6  SBOM (syft, CycloneDX)             pass
  gate 7  push, sign, attest (cosign)        pass
  gate 8  policy (conftest)                  pass
  gate 9  deploy signed digest only          pass
PIPELINE PASSED: localhost:5002/orders@sha256:23db1f2fd1d7c4bd7716db7c36940fbba35de56efca7f8a7b5d877b850a155af

== The release
  PASS  the signed image is running and ready
  PASS  it runs as user 10001 with a read-only root filesystem
  PASS  it runs the exact digest the pipeline signed
  PASS  the signed SBOM attestation verifies (966 components)

== Each gate blocks what it exists to block
  PASS  gate 1 blocks a change that breaks the health check
  PASS  gate 2 blocks shell injection (subprocess with shell=True)
  PASS  gate 2 blocks a suppression without a reason
  PASS  gate 3 blocks a dependency with known vulnerabilities (requests 2.19.1)
  PASS  gate 4 blocks a committed cloud access key
  PASS  gate 8 blocks a manifest that may run as root, writable, without limits
  PASS  the policy names each problem (4 violations listed)

== Deploy refuses anything not signed by our key
  PASS  an unsigned digest is refused
  PASS  a tag instead of a digest is refused
  PASS  a digest signed with someone else's key is refused
  PASS  nothing refused was started
  PASS  the signed release is still the one running

RESULT: all checks passed

The files

05-devsecops/deploy.sh
#!/usr/bin/env bash
# Deploys one image digest, but only when its signature and its SBOM attestation verify against
# cosign.pub. In a cluster an admission controller (Kyverno, Sigstore policy-controller) does this.
#   deploy.sh REGISTRY/orders@sha256:...
source "$(dirname "$0")/../lib.sh"
work devsecops
REF="$1"; PORT="${PORT:-18085}"
case "$REF" in *@sha256:*) ;; *) echo "refused: deploy a digest, not a tag ($REF)"; exit 1;; esac
cosign() { docker run --rm --network host -u 0 -v "$WORK:/w" -w /w gcr.io/projectsigstore/cosign:v2.4.1 "$@"; }

if ! cosign verify --key cosign.pub --insecure-ignore-tlog=true --allow-http-registry "$REF" > "$WORK/verify.json" 2> "$WORK/verify.err"; then
  echo "refused: no valid signature for $REF"; grep -m1 -i error "$WORK/verify.err" || true; exit 1
fi
if ! cosign verify-attestation --key cosign.pub --type cyclonedx --insecure-ignore-tlog=true \
     --allow-http-registry "$REF" > /dev/null 2>&1; then
  echo "refused: no valid SBOM attestation for $REF"; exit 1
fi
echo "signature and SBOM attestation verified for $REF"

docker rm -f cap-sec-orders > /dev/null 2>&1 || true
docker run -d --name cap-sec-orders -p "127.0.0.1:$PORT:8080" --read-only --cap-drop ALL \
  --security-opt no-new-privileges --memory 128m --cpus 0.5 --pids-limit 64 "$REF" > /dev/null
wait_for "http://127.0.0.1:$PORT/readyz" 30
echo "deployed: cap-sec-orders on http://127.0.0.1:$PORT"
05-devsecops/k8s/deploy.yaml
# The manifest gate 8 checks. IMAGE is replaced with the signed digest before the check.
apiVersion: apps/v1
kind: Deployment
metadata: {name: orders, labels: {app: orders}}
spec:
  replicas: 2
  selector: {matchLabels: {app: orders}}
  template:
    metadata: {labels: {app: orders}}
    spec:
      automountServiceAccountToken: false
      containers:
        - name: orders
          image: IMAGE
          ports: [{containerPort: 8080}]
          securityContext:
            runAsNonRoot: true
            runAsUser: 10001
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: {drop: [ALL]}
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {cpu: 500m, memory: 128Mi}
05-devsecops/pipeline.sh
#!/usr/bin/env bash
# The DevSecOps pipeline: nine gates in order; the first gate that fails stops the release.
#   pipeline.sh SRC_DIR VERSION      (setup.sh runs it; verify.sh runs it again on broken copies)
# Needs: WORK (the capstone folder, holding .venv and cosign.key) and REG (the registry host:port).
source "$(dirname "$0")/../lib.sh"
work devsecops
SRC="$(cd "$1" && pwd)"; VERSION="$2"
LOGS="$SRC/.pipeline"; rm -rf "$LOGS"; mkdir -p "$LOGS"
VENV="$WORK/.venv/bin"
COSIGN_IMG=gcr.io/projectsigstore/cosign:v2.4.1
CONFTEST_IMG=openpolicyagent/conftest:v0.56.0
cosign() { docker run --rm --network host -u 0 -v "$WORK:/w" -v "$SRC:/src" -w /w -e COSIGN_PASSWORD "$COSIGN_IMG" "$@"; }
conftest() { docker run --rm -u 0 -v "$SRC:/src" -v "$CAP_ROOT/05-devsecops/policy:/policy:ro" -w /src "$CONFTEST_IMG" "$@"; }

gate() {
  local n="$1" name="$2"; shift 2
  printf '  gate %s  %-34s ' "$n" "$name"
  # run the gate in a subshell with errexit on, so any failing command inside it fails the gate
  # (inside "if ...; then" bash would silently ignore set -e)
  local rc=0
  set +e; ( set -e; "$@" ) > "$LOGS/$n.log" 2>&1; rc=$?; set -e
  if [ "$rc" -eq 0 ]; then echo pass
  else
    echo "BLOCKED"; sed 's/^/        | /' "$LOGS/$n.log" | tail -12
    echo "PIPELINE BLOCKED at gate $n ($name)"; exit $((10 + n))
  fi
}

unit_tests() { cd "$SRC" && python3 -m unittest -q test_orders; }

static_scan() {
  # every suppression must name the rule and give a reason, like: # nosec B104 - why it is safe
  if grep -nE '#\s*nosec' "$SRC"/*.py | grep -vE '#\s*nosec B[0-9]{3} - .{8,}'; then
    echo "the nosec comment above has no rule id or no reason"; return 1
  fi
  "$VENV/bandit" -q -r "$SRC" -x "$SRC/test_orders.py,$SRC/.pipeline" --severity-level medium --confidence-level medium
}

dependency_audit() { "$VENV/pip-audit" --no-deps --disable-pip --progress-spinner off -r "$SRC/requirements-ci.txt"; }

secret_scan() { trivy fs --quiet --scanners secret --exit-code 1 --skip-dirs "$SRC/.pipeline" "$SRC"; }

build_and_scan() {
  docker build -q -t "cap-sec-orders:$VERSION" --build-arg "VERSION=$VERSION" "$SRC"
  trivy image --quiet --scanners vuln --severity CRITICAL --ignore-unfixed --exit-code 1 "cap-sec-orders:$VERSION"
}

sbom() {
  syft -q "cap-sec-orders:$VERSION" -o "cyclonedx-json=$SRC/sbom.cdx.json"
  jq -e '[.components[] | select(.name == "python")] | length > 0' "$SRC/sbom.cdx.json"
  jq -r '"\(.components | length) components recorded"' "$SRC/sbom.cdx.json"
}

push_sign_attest() {
  docker tag "cap-sec-orders:$VERSION" "$REG/orders:$VERSION"
  docker push -q "$REG/orders:$VERSION"
  docker image inspect "$REG/orders:$VERSION" --format '{{range .RepoDigests}}{{println .}}{{end}}' \
    | grep "^$REG/orders@" > "$SRC/digest.txt"
  cosign sign --key cosign.key --tlog-upload=false --allow-http-registry -y "$(cat "$SRC/digest.txt")"
  cosign attest --key cosign.key --type cyclonedx --predicate /src/sbom.cdx.json \
    --tlog-upload=false --allow-http-registry -y "$(cat "$SRC/digest.txt")"
}

policy() {
  sed "s|image: IMAGE|image: $(cat "$SRC/digest.txt")|" "$SRC/k8s/deploy.yaml" > "$SRC/k8s/deploy.rendered.yaml"
  conftest verify --no-color --policy /policy
  conftest test --no-color --policy /policy k8s/deploy.rendered.yaml
}

deploy() { bash "$CAP_ROOT/05-devsecops/deploy.sh" "$(cat "$SRC/digest.txt")"; }

set -e
say "Pipeline for orders $VERSION"
gate 1 "unit tests"                    unit_tests
gate 2 "static analysis (bandit)"      static_scan
gate 3 "dependency audit (pip-audit)"  dependency_audit
gate 4 "secret scan (trivy)"           secret_scan
gate 5 "build + image scan (CRITICAL)" build_and_scan
gate 6 "SBOM (syft, CycloneDX)"        sbom
gate 7 "push, sign, attest (cosign)"   push_sign_attest
gate 8 "policy (conftest)"             policy
gate 9 "deploy signed digest only"     deploy
echo "PIPELINE PASSED: $(cat "$SRC/digest.txt")"
05-devsecops/policy/deployment.rego
# Rules every Deployment must meet before it may ship. Run: conftest test --policy policy k8s/deploy.yaml
package main

import rego.v1

containers contains c if {
	input.kind == "Deployment"
	some c in input.spec.template.spec.containers
}

deny contains msg if {
	some c in containers
	not contains(c.image, "@sha256:")
	msg := sprintf("%s: pin the image by digest (image@sha256:...), not %q", [c.name, c.image])
}

deny contains msg if {
	some c in containers
	not c.securityContext.runAsNonRoot == true
	msg := sprintf("%s: set securityContext.runAsNonRoot: true", [c.name])
}

deny contains msg if {
	some c in containers
	c.securityContext.privileged == true
	msg := sprintf("%s: privileged containers are not allowed", [c.name])
}

deny contains msg if {
	some c in containers
	not c.securityContext.allowPrivilegeEscalation == false
	msg := sprintf("%s: set securityContext.allowPrivilegeEscalation: false", [c.name])
}

deny contains msg if {
	some c in containers
	not c.securityContext.readOnlyRootFilesystem == true
	msg := sprintf("%s: set securityContext.readOnlyRootFilesystem: true", [c.name])
}

deny contains msg if {
	some c in containers
	not "ALL" in object.get(c, ["securityContext", "capabilities", "drop"], [])
	msg := sprintf("%s: drop all Linux capabilities (capabilities.drop: [ALL])", [c.name])
}

deny contains msg if {
	some c in containers
	some r in ["cpu", "memory"]
	not c.resources.limits[r]
	msg := sprintf("%s: set resources.limits.%s", [c.name, r])
}
05-devsecops/reset.sh
#!/usr/bin/env bash
# Removes capstone 5: the cap-sec-* containers and images, the registry, the keys, and the work folder.
source "$(dirname "$0")/../lib.sh"
REG="localhost:${REG_PORT:-5002}"
docker rm -f cap-sec-orders cap-sec-registry > /dev/null 2>&1 || true
docker image ls --format '{{.Repository}}:{{.Tag}}' | grep -E "^(cap-sec-orders|$REG/orders):" | xargs -r docker image rm -f > /dev/null 2>&1 || true
rm -rf "$HOME/labs/capstones/devsecops"
echo "capstone 5 reset: containers cap-sec-orders and cap-sec-registry, their images, the keys and the work folder removed"
05-devsecops/setup.sh
#!/usr/bin/env bash
# Capstone 5, DevSecOps: tests -> static analysis -> dependency audit -> secrets -> image scan -> SBOM
# -> signing and attestation -> policy -> deploy only what is signed.
# A local registry listens on 5002 and the service on 18085.
source "$(dirname "$0")/../lib.sh"
need docker trivy syft jq curl python3
work devsecops
export REG="localhost:${REG_PORT:-5002}"
port_free "${REG_PORT:-5002}"; port_free "${PORT:-18085}"
mkdir -p "$WORK/src/k8s"
cp "$APP_SRC/orders.py" "$APP_SRC/test_orders.py" "$APP_SRC/Dockerfile" "$CAP_ROOT/05-devsecops/requirements-ci.txt" "$WORK/src/"
cp "$CAP_ROOT/05-devsecops/k8s/deploy.yaml" "$WORK/src/k8s/"
cd "$WORK"

say "1. Install the pinned pipeline tools in a virtual environment"
python3 -m venv .venv
.venv/bin/pip install -q --disable-pip-version-check -r src/requirements-ci.txt
.venv/bin/bandit --version | head -1
.venv/bin/pip-audit --version

say "2. Start a local registry and create a signing key pair"
docker run -d --name cap-sec-registry -p "127.0.0.1:${REG_PORT:-5002}:5000" registry:2.8.3 > /dev/null
wait_for "http://$REG/v2/" 20
# a throwaway key with an empty password, for this lab only; real keys live in a KMS, or use keyless signing
export COSIGN_PASSWORD=""
docker run --rm -u 0 -v "$WORK:/w" -w /w -e COSIGN_PASSWORD gcr.io/projectsigstore/cosign:v2.4.1 generate-key-pair > /dev/null 2>&1
ls cosign.key cosign.pub

say "3. Run the pipeline"
bash "$CAP_ROOT/05-devsecops/pipeline.sh" src 1.0.0
05-devsecops/verify.sh
#!/usr/bin/env bash
# Checks capstone 5: the release passed every gate, and each gate blocks the problem it exists for.
source "$(dirname "$0")/../lib.sh"
need docker jq curl
work devsecops
cd "$WORK"
export REG="localhost:${REG_PORT:-5002}" COSIGN_PASSWORD=""
PORT="${PORT:-18085}"
P="$CAP_ROOT/05-devsecops/pipeline.sh"
D="$CAP_ROOT/05-devsecops/deploy.sh"
COSIGN_IMG=gcr.io/projectsigstore/cosign:v2.4.1
cosign() { docker run --rm --network host -u 0 -v "$WORK:/w" -w /w -e COSIGN_PASSWORD "$COSIGN_IMG" "$@"; }
DIGEST="$(cat src/digest.txt)"

say "The release"
check "the signed image is running and ready" curl -fsS "http://127.0.0.1:$PORT/readyz"
[ "$(docker inspect cap-sec-orders --format '{{.Config.User}} {{.HostConfig.ReadonlyRootfs}}')" = "10001:10001 true" ] \
  && ok "it runs as user 10001 with a read-only root filesystem" || bad "user or read-only setting is wrong"
[ "$(docker inspect cap-sec-orders --format '{{.Config.Image}}')" = "$DIGEST" ] \
  && ok "it runs the exact digest the pipeline signed" || bad "the running image is not the signed digest"
n=$(cosign verify-attestation --key cosign.pub --type cyclonedx --insecure-ignore-tlog=true --allow-http-registry "$DIGEST" 2>/dev/null \
  | jq -s '[.[0].payload | @base64d | fromjson | .predicate.components[]] | length')
[ "${n:-0}" -gt 0 ] && ok "the signed SBOM attestation verifies ($n components)" || bad "the SBOM attestation did not verify"

# each case copies the good source, breaks one thing, and expects the pipeline to stop at one gate
break_test()   { sed -i 's/self.send(200, {"status": "ok"})/self.send(500, {"status": "ok"})/' orders.py; }
break_shell()  { printf 'import subprocess\n\n\ndef run(name):\n    return subprocess.call("echo " + name, shell=True)\n' > tools.py; }
break_nosec()  { sed -i 's/# nosec B310 - .*/# nosec/' orders.py; }
break_dep()    { echo "requests==2.19.1" >> requirements-ci.txt; }
break_secret() { printf 'AWS_ACCESS_KEY_ID = "%s"\n' "AKIA$(head -c 400 /dev/urandom | tr -dc 'A-Z2-7' | head -c 16)" > settings.py; }
break_policy() {
  sed -i -e 's/runAsNonRoot: true/runAsNonRoot: false/' -e 's/readOnlyRootFilesystem: true/readOnlyRootFilesystem: false/' \
         -e '/limits:/d' k8s/deploy.yaml
}
expect_block() {
  local name="$1" want="$2" desc="$3" got=0
  rm -rf "bad-$name"; cp -r src "bad-$name"; rm -rf "bad-$name/.pipeline"
  ( cd "bad-$name" && "break_$name" )
  bash "$P" "bad-$name" "9.9.$want-$name" > "bad-$name.log" 2>&1 || got=$?
  if [ "$got" = $((10 + want)) ]; then ok "gate $want blocks $desc"
  else bad "gate $want did not block $desc (exit $got; see $WORK/bad-$name.log)"; tail -5 "bad-$name.log"; fi
}

say "Each gate blocks what it exists to block"
expect_block test   1 "a change that breaks the health check"
expect_block shell  2 "shell injection (subprocess with shell=True)"
expect_block nosec  2 "a suppression without a reason"
expect_block dep    3 "a dependency with known vulnerabilities (requests 2.19.1)"
expect_block secret 4 "a committed cloud access key"
expect_block policy 8 "a manifest that may run as root, writable, without limits"
n=$(grep -c "^FAIL" bad-policy/.pipeline/8.log || true)
[ "$n" -ge 4 ] && ok "the policy names each problem ($n violations listed)" || bad "the policy listed $n violations"

say "Deploy refuses anything not signed by our key"
docker build -q -t cap-sec-orders:unsigned --build-arg VERSION=unsigned src > /dev/null
docker tag cap-sec-orders:unsigned "$REG/orders:unsigned"
docker push -q "$REG/orders:unsigned" > /dev/null
U=$(docker image inspect "$REG/orders:unsigned" --format '{{range .RepoDigests}}{{println .}}{{end}}' | grep "^$REG/orders@")
refused() {  # refused "description" "expected message" REF
  local out got=0
  out=$(PORT=18095 bash "$D" "$3" 2>&1) || got=$?
  if [ "$got" -ne 0 ] && grep -q "$2" <<< "$out"; then ok "$1"; else bad "$1 (exit $got: $out)"; fi
}
refused "an unsigned digest is refused" "refused: no valid signature" "$U"
refused "a tag instead of a digest is refused" "not a tag" "$REG/orders:1.0.0"
cosign generate-key-pair --output-key-prefix other > /dev/null 2>&1
cosign sign --key other.key --tlog-upload=false --allow-http-registry -y "$U" > /dev/null 2>&1
refused "a digest signed with someone else's key is refused" "refused: no valid signature" "$U"
docker ps --format '{{.Ports}}' | grep -q 18095 && bad "something started on the test port" || ok "nothing refused was started"
[ "$(docker inspect cap-sec-orders --format '{{.Config.Image}}')" = "$DIGEST" ] \
  && ok "the signed release is still the one running" || bad "the running release changed"
summary

If it fails

SymptomCauseFix
Gate 3 fails on the good sourceA new vulnerability was published for a pinned tool since this page was written.Read the advisory in the gate log, raise the pin in requirements-ci.txt to the fixed version, and run again. That is the gate working.
Gate 7 fails with "connection refused"The registry is not up yet, or REG_PORT differs between setup and verify.Use the same REG_PORT for every step, or run the reset and start again.
Gate 4 blocks your own copyA file you added looks like a credential.Remove it, rotate the credential if it was real, and keep secrets in a secret store.

Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.

Clean up

bash 05-devsecops/reset.sh

It removes: containers cap-sec-registry and cap-sec-orders; images cap-sec-orders:* and localhost:5002/orders:*; a throwaway cosign key pair and a Python virtual environment in ~/labs/capstones/devsecops. Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.

In the cloud

Not run by this course. The local capstone above is the tested part. These are the managed services that do the same jobs on each provider; they cost money while they exist, and their names and prices change, so check the provider's current documentation before you build them. Use a separate learning account with a budget alert, as Start here explains.
ProviderEquivalent
AWSCodeBuild or GitHub Actions with Amazon Inspector scanning, signing with AWS Signer (Notation) or cosign with a KMS key, and admission checks on EKS.
AzureAzure Pipelines or GitHub Actions, Defender for Containers scanning, Notation signing with Key Vault, and Azure Policy for AKS.
Google CloudCloud Build, Artifact Analysis scanning, and Binary Authorization to admit only attested images to GKE.

How it is assessed

verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.

CriterionMeetsExceeds
CoverageAll nine gates run, in this order, and stop the release on failure.You can say what each gate cannot catch.
EvidenceThe running image is the exact digest that was signed.Its SBOM attestation verifies, and you can query it for a package.
SuppressionsEvery nosec has a rule and a reason.Suppressions are reviewed like code and expire.
PolicyThe policy blocks the bad manifest and passes the good one.The policy has tests for every rule, and runs in the cluster as admission control.

Take it further

Then test what you know with the assessments.

Next capstone: Run an incident from alert to postmortem. All capstones · Guided routes