Platform Engineering · Lesson 257

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

Two supply lines feed every workload: the credentials it uses and the software it runs. Both are attack paths. For credentials, the goal is secretless: workload identity instead of stored keys, and where secrets must exist, short-lived dynamic credentials or automatic rotation with overlap so nothing breaks. For software, generating SBOMs and signatures is only half the job; the other half is verifying them at deploy time: the image is signed by your pipeline's identity, has SLSA provenance from your builder, and its SBOM shows no blocked components, enforced by admission control. This lesson follows one deployment, and shows two failures: a rotation that broke production because the old secret was revoked first, and a signed-images policy that only warned while a typosquatted package shipped.

Difficulty: Master · Know this first: Lesson 255, Lesson 250

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from a deploy request to a running, verified workload. It is a worked example, not a measurement. The rotation and dependency hops are where credentials and software attacks get through.

Try it: credentials and verification

Pick how the database credential is managed, how rotation works, and how the admission policy runs. Then see what happens on rotation day and when a malicious package arrives.

1 ha leaked credential lasts
no outagerotation day
rejecteda malicious package

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Credential and supply-chain security grows in four levels: finding secrets and dependencies, removing static secrets, verifying software at deploy, and running both as programmes.

Basic — Find what you have

At the basic level you know which secrets and dependencies a service has.

  • Secrets in use, where they are stored, when they were last rotated.
  • Direct and transitive dependencies from the lock file or SBOM.
  • Signatures on images, and who signed them.

Where it breaks: a secret nobody knows exists, in an environment variable set years ago.

Try it: Basic

How do you check who signed an image?

Now do it: Verify one image's signature with cosign.

Intermediate — Remove static secrets

At the intermediate level static secrets are the exception.

  • Workload identity for every cloud API call.
  • Dynamic database credentials or IAM database authentication.
  • Remaining secrets rotated automatically, with overlap and reload.

Try it: Intermediate

Pods read a password only at start. How do you rotate it without an outage?

Now do it: Rotate one secret in a test environment with overlap.

Advanced — Verify at deploy

At the advanced level the cluster runs only verified software.

  • Keyless signing in CI; SLSA provenance from a trusted builder; SBOM attestations.
  • Admission verification of signer identity, provenance, and SBOM policy, enforced.
  • Dependency defences: hashed lock files, a proxy registry, scoped internal names.

Try it: Advanced

What stops dependency confusion?

Now do it: Check how your package manager resolves internal names.

Master — Programmes, not projects

At the master level both are measured and kept current.

  • An inventory of every credential with owner, scope, lifetime, and last rotation.
  • SBOMs indexed for fleet-wide queries; malicious-package feeds acted on in hours.
  • Policies moved from audit to enforce on a schedule; exceptions with expiry.

Trade-off: enforcement breaks unsigned workloads on day one; an audit period with a fixed end date finds them first.

Try it: Master

A policy has been in audit mode for eight months. What do you do?

Now do it: List the policies in your clusters that are still in audit mode.

Go deeper

Verifying signature, provenance, and an SBOM attestation by hand (keyless signatures from GitHub Actions; check the cosign and slsa-verifier documentation for current flags):

IMG=registry.example.com/payments-api@sha256:9f2c...
cosign verify "$IMG" \
  --certificate-identity-regexp '^https://github.com/example-org/payments-api/.github/workflows/release.yml@refs/heads/main$' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com
cosign verify-attestation "$IMG" --type cyclonedx \
  --certificate-identity-regexp '^https://github.com/example-org/' --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  | jq -r '.payload' | base64 -d | jq '.predicate.components[].name' | sort | head
slsa-verifier verify-image "$IMG" --source-uri github.com/example-org/payments-api --source-branch main

The same check enforced at admission with Kyverno (Enforce, not Audit):

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: {name: verify-release-images}
spec:
  validationFailureAction: Enforce
  webhookTimeoutSeconds: 15
  rules:
  - name: signed-by-release-workflow
    match: {any: [{resources: {kinds: [Pod]}}]}
    verifyImages:
    - imageReferences: ["registry.example.com/*"]
      attestors:
      - entries:
        - keyless:
            subject: "https://github.com/example-org/*/.github/workflows/release.yml@refs/heads/main"
            issuer: "https://token.actions.githubusercontent.com"

Rotation with overlap for a database password (the alternating-users pattern): two database users, A and B; the application uses A; rotation sets a new password on B, publishes B as current, rolls or reloads consumers, waits until no sessions use A, then changes A's password, ready for the next rotation the other way round.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The policy that only watched.

Timeline

  • Month 0An image verification policy is deployed in Audit mode, to give teams time to sign their images.
  • Month 8, day 0A pull request adds "reqeusts" by mistake. SCA marks it malicious; the pipeline refuses to sign. The deploy goes ahead from a manual pipeline run; admission logs "unsigned image" and admits it.
  • Days 0–3On import, the package sends environment variables, including a service token, to an outside server.
  • Day 3Egress monitoring flags the destination. The image is removed, the token revoked and the role's access reviewed; SBOM queries find the package in two other images from the same week.

What changed after

The policy moved to Enforce with an exception process, the release pipeline is the only identity whose signatures are accepted, the registry proxy blocks packages younger than seven days unless approved, and the service moved from a stored token to workload identity.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Linux with OpenSSL and Python 3. The keys made here are throwaway lab keys.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make two signing keys: one for the release pipeline, one for an impostor.

    Reversible

    mkdir -p ~/labs/verify && cd ~/labs/verify
    for who in release impostor; do
      openssl genpkey -algorithm ed25519 -out $who.key 2>/dev/null
      openssl pkey -in $who.key -pubout -out $who.pub
    done
    ls *.pub

    Expect: impostor.pub release.pub.

    Clean up: rm -rf ~/labs/verify.

  2. Build an "artifact", record its digest, and sign the digest with the release key, as a pipeline would.

    Reversible

    printf "payments-api v87 image layers" > artifact.tar
    sha256sum artifact.tar | cut -d" " -f1 > artifact.digest
    openssl pkeyutl -sign -inkey release.key -rawin -in artifact.digest -out artifact.sig
    cat artifact.digest

    Options: -rawin signs the data directly, as Ed25519 requires.

    Expect: The artifact's SHA-256 digest; the signature is in artifact.sig.

  3. Verify at "admission": the release key accepts it; the impostor's key and a modified artifact do not.

    Reversible

    openssl pkeyutl -verify -pubin -inkey release.pub -rawin -in artifact.digest -sigfile artifact.sig
    openssl pkeyutl -verify -pubin -inkey impostor.pub -rawin -in artifact.digest -sigfile artifact.sig
    printf "tampered" >> artifact.tar && sha256sum artifact.tar | cut -d" " -f1 > tampered.digest
    openssl pkeyutl -verify -pubin -inkey release.pub -rawin -in tampered.digest -sigfile artifact.sig

    Expect: Signature Verified Successfully once, then two failures: the wrong signer and a changed artifact are both rejected. Admission controllers do the same check with cosign and the signer's identity.

2. Python: rotation_and_admission.py

This program replays a password rotation for a fleet of pods that read the secret only at start, revoking first and then with an overlap window, and counts failed connections. Then it runs an admission check: signer identity, a policy against known-malicious and look-alike package names in the SBOM, and the difference between audit and enforce mode. Save it as rotation_and_admission.py, then run it.

# rotation_and_admission.py
PODS, RESTART_EVERY = 12, 4                    # pods roll one at a time, every 4 minutes

def rotate(overlap):
    failures = 0
    valid = {"old", "new"} if overlap else {"new"}     # revoke first: old is invalid from minute 0
    pod_secret = ["old"] * PODS
    for minute in range(0, PODS * RESTART_EVERY + 1):
        if minute % RESTART_EVERY == 0 and minute // RESTART_EVERY < PODS:
            pod_secret[minute // RESTART_EVERY] = "new"     # this pod restarts and reads the new value
        failures += sum(1 for s in pod_secret if s not in valid)
        if overlap and all(s == "new" for s in pod_secret):
            valid = {"new"}                    # confirmed unused: now revoke old
    return failures

print(f"revoke first:      {rotate(False):>4} pod-minutes of failed connections")
print(f"overlap, then revoke: {rotate(True):>3} pod-minutes of failed connections")
print()

POPULAR = ["requests", "urllib3", "numpy", "pandas", "cryptography"]
MALICIOUS = {"reqeusts"}
def distance(a, b):
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]

def admit(image, mode):
    reasons = []
    if image["signer"] != "release.yml@refs/heads/main":
        reasons.append(f"signed by {image['signer'] or 'nobody'}")
    for c in image["sbom"]:
        if c in MALICIOUS:
            reasons.append(f"{c} is known malicious")
        elif c not in POPULAR and any(distance(c, p) <= 2 for p in POPULAR):
            reasons.append(f"{c} looks like a typosquat")
    if not reasons:
        return "ADMITTED"
    return ("REJECTED: " if mode == "enforce" else "ADMITTED (audit log): ") + "; ".join(reasons)

images = [
    {"name": "payments-api v87", "signer": "release.yml@refs/heads/main", "sbom": ["requests", "urllib3"]},
    {"name": "payments-api v88", "signer": None, "sbom": ["reqeusts", "urllib3"]},
    {"name": "reports v12", "signer": "release.yml@refs/heads/main", "sbom": ["pandsa", "numpy"]},
]
for mode in ("audit", "enforce"):
    print(f"policy in {mode} mode:")
    for im in images:
        print(f"  {im['name']:<17} {admit(im, mode)}")

Run it, and you should see this output:

$ python3 rotation_and_admission.py
revoke first:       264 pod-minutes of failed connections
overlap, then revoke:   0 pod-minutes of failed connections

policy in audit mode:
  payments-api v87  ADMITTED
  payments-api v88  ADMITTED (audit log): signed by nobody; reqeusts is known malicious
  reports v12       ADMITTED (audit log): pandsa looks like a typosquat
policy in enforce mode:
  payments-api v87  ADMITTED
  payments-api v88  REJECTED: signed by nobody; reqeusts is known malicious
  reports v12       REJECTED: pandsa looks like a typosquat

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/secret-rotation-secretless-workloads-and-sbom-verification && cd ~/labs/secret-rotation-secretless-workloads-and-sbom-verification) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Secret Rotation, Secretless Workloads, and Verifying Signatures and SBOMs at Deploy", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Make two signing keys: one for the release pipeline, one for an impostor.'
  'Build an "artifact", record its digest, and sign the digest with the release key, as a pipeline would.'
  'Verify at "admission": the release key accepts it; the impostor'\''s key and a modified artifact do not.'
)

step_1() {
mkdir -p ~/labs/verify && cd ~/labs/verify
for who in release impostor; do
  openssl genpkey -algorithm ed25519 -out $who.key 2>/dev/null
  openssl pkey -in $who.key -pubout -out $who.pub
done
ls *.pub
}

step_2() {
printf "payments-api v87 image layers" > artifact.tar
sha256sum artifact.tar | cut -d" " -f1 > artifact.digest
openssl pkeyutl -sign -inkey release.key -rawin -in artifact.digest -out artifact.sig
cat artifact.digest
}

step_3() {
openssl pkeyutl -verify -pubin -inkey release.pub -rawin -in artifact.digest -sigfile artifact.sig
openssl pkeyutl -verify -pubin -inkey impostor.pub -rawin -in artifact.digest -sigfile artifact.sig
printf "tampered" >> artifact.tar && sha256sum artifact.tar | cut -d" " -f1 > tampered.digest
openssl pkeyutl -verify -pubin -inkey release.pub -rawin -in tampered.digest -sigfile artifact.sig
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

A company has 200 static secrets in Kubernetes, rotates them yearly by hand, and has an image signing policy in audit mode. Design its move to secretless workloads and enforced verification.

Clarifying questions to ask

Which secrets become workload identity, which become dynamic, and which stay static? How is rotation automated without outages? How are images signed and attested? How is verification rolled out to enforce? How are dependency attacks stopped? How do you respond when a package is reported malicious?

Rough sizing

Say 200 static secrets (90 cloud keys, 60 database passwords, 50 third-party API keys), 40 services, 6 clusters, and 400 images.

Shape of the answer

Cloud keys replaced by workload identity first; database passwords moved to Vault dynamic credentials or IAM database authentication; third-party keys stored in the secrets manager with alternating-key rotation every 90 days and reload on change; keyless cosign signing, SLSA provenance, and CycloneDX attestations from the release pipeline; Kyverno verifyImages in Audit for one month with published violations, then Enforce per namespace with expiring exceptions; hashed lock files, a proxy registry with an age quarantine and scoped internal names; SBOMs indexed for fleet queries and a runbook for malicious-package reports.

Trade-offs to name

Workload identity needs platform work per cloud and per legacy system; enforcement blocks unsigned images, which is the point and needs an exception path; a package age quarantine delays urgent dependency updates by days unless approved.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Rotation without overlapHop 3: RotationBreaksA scheduled rotation changes the database password at 09:00, revoking the old one immediately. External Secrets syncs the new value into the Kubernetes Secret within minutes, but running pods read the password only at start.
Verification in audit modeHop 4: DependencyBreaksA pull request adds "reqeusts", a typosquat published the week before that steals environment variables on import.
Verification in audit modeHop 8: AdmissionDegradesThe policy has been in Audit for eight months "while teams migrate"; it logs the unsigned image and lets it run.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Workload identity → Dynamic secrets → Rotation → Dependency → SBOM → Signature → Provenance → Admission → Re-evaluation. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 258
Service Design from Scratch: Requirements, NFRs, and the Design Brief

Every service I have designed started as one sentence from someone who did not know it was a design problem. "Customers keep calling to ask where their parcel is. Can we show them?" That sentence is not a design. It is an ask.

Go to Lesson 258 →

Or browse the full course from the Lessons index.