Secrets and supply chain: managers, rotation, envelope encryption, signing, audit

Assume every credential leaks eventually: scope it narrowly, keep its lifetime short, and make its use auditable. Short-lived federated credentials beat rotation.

Read the briefing
About 4 min to read 8 drills

What to remember

  1. Short lifetime beats rotation. A 90-day rotation still leaves 90 days of exposure, and is usually untested.
  2. Environment variables leak through /proc and crash dumps. Prefer projected files or credentials fetched at start-up.
  3. Envelope encryption: root key never leaves the KMS. Fresh data key per object, wrapped by the root — so rotation is re-wrapping, not re-encrypting.
  4. Signing without verification changes nothing. Verify at admission or the signature is decoration.
  5. Kubernetes Secrets are base64, not encrypted. Enable etcd encryption at rest and restrict RBAC.

The big picture

Secrets questions test whether you can design for the day a credential leaks: where secrets live and who can read them, how rotation happens without downtime, how envelope encryption limits what a stolen ciphertext is worth, how least privilege is expressed concretely, how the software supply chain is pinned and verified, and how any of it would be detected. On infrastructure holding signing keys, this is the highest-stakes topic in the loop.

The mental model

Assume every credential will eventually be exposed, and design so the blast radius is small and the exposure is short. Three levers: scope (one identity per workload, permissions on specific resources), lifetime (short-lived beats rotated beats permanent), and detection (immutable audit of who read what, alerted on the anomalous).

In depth

Where secrets live, and rotation

A secrets manager (AWS Secrets Manager, Vault, GCP Secret Manager, Kubernetes Secrets backed by an external store) buys four things a file or environment variable cannot: access control per identity, an audit trail of reads, versioning, and rotation hooks. Environment variables leak through /proc/<pid>/environ, crash dumps, child processes, and logs of the process table; files with tight modes or tmpfs-mounted volumes are better; short-lived credentials fetched at start-up and refreshed are better still. In Kubernetes, plain Secrets are base64, not encryption: enable encryption at rest for etcd, restrict RBAC on secrets (a namespace-wide get secrets is a fleet compromise), and prefer a CSI driver or external-secrets that projects short-lived values.

Zero-downtime rotation has a fixed shape: create the new version, roll consumers to it, verify, then retire the old, which requires consumers that reload without a restart (or a rolling restart) and a period where both versions are valid. Databases usually need two credentials alternating; API providers usually support overlapping keys. A rotation nobody has tested is a scheduled outage.

Envelope encryption and least privilege

Envelope encryption: a root key in a KMS/HSM never leaves the service; each object gets a fresh data key generated locally, the object is encrypted with it, and the data key is stored alongside, wrapped by the root key. This means bulk data can be encrypted at high speed without shipping data to the KMS, key rotation is a matter of re-wrapping data keys rather than re-encrypting everything, and a stolen ciphertext plus a stolen wrapped key is worthless without a KMS decrypt call, which is logged and permission-controlled.

Least privilege is expressed on three axes: who (one identity per workload, not one shared role per team), what (specific actions on specific resource ARNs, with conditions such as source VPC endpoint, tag, or organization), and how long (short-lived assumed roles, IRSA/workload identity, OIDC federation from CI instead of static keys). The test for a policy is not "does the app work" but "what could this identity do if the process were taken over".

Supply chain and audit

The pipeline is a credential-rich environment and a code-execution surface. Basics: pin dependencies, base images, and CI actions by digest or hash; generate and keep an SBOM; sign artifacts (Sigstore/cosign) and verify signatures at deploy time with an admission policy, otherwise signing is theatre; isolate build from deploy credentials; require review for changes to pipeline definitions; and treat third-party actions as vendored code.

Audit closes the loop: secret reads and IAM activity logged immutably to a separate, locked account (CloudTrail with object-lock, or the equivalent), centralized, retained, and alerted on the anomalous, a role reading a secret it has never read, access from an unexpected region, a key used outside its normal hours. The design question interviewers like is "how would you know?", and the answer must be a mechanism, not a habit. Plan the response too: what gets rotated, in what order, when a key is suspected leaked, and how the blast radius was bounded in advance.

Myths and facts

Myth: Kubernetes Secrets are encrypted.

Fact: They are base64-encoded objects in etcd; encryption at rest and tight RBAC are separate things you must enable.

Myth: Rotating secrets every 90 days is the main control.

Fact: Short lifetimes and narrow scope matter more; a 90-day rotation still leaves 90 days of exposure and often is not tested.

Myth: Environment variables are a fine place for secrets in containers.

Fact: They leak through /proc, crash dumps, child processes, and orchestration APIs; prefer projected files or fetched short-lived credentials.

Myth: Signing images makes the supply chain secure.

Fact: Only if signatures are verified at admission; unverified signatures change nothing.

Myth: If we log everything, we have auditing.

Fact: Auditing means immutable storage, centralization, retention, and alerts on anomalies; logs a compromised root can edit are not evidence.

How pros do it

  • One identity per workload with resource-scoped permissions and conditions; no shared team credentials.
  • Prefer short-lived federated credentials (OIDC, IRSA, workload identity) over stored secrets; store what remains in a manager with audit.
  • Design and test zero-downtime rotation (create, roll, verify, retire) including the database two-credential pattern.
  • Pin dependencies, base images, and CI actions by digest; sign artifacts and verify at admission.
  • Ship secret-access and IAM audit logs to a locked separate account with anomaly alerts, and rehearse the leaked-key response.

Questions people ask

A key may have leaked in a log. What is the order of operations?

Give the order and the reason for it: revoke or rotate first because a public exposure is a compromise, then determine what the credential did from audit logs (and check for persistence), then fix the leak path, then add a detection so the next one is found automatically. Anything that starts with 'work out whether it was really used' gives the attacker the window.

How do pods get cloud credentials without static keys?

Say 'workload identity federation' and then the mechanism in one sentence: the cluster signs a service-account token, the cloud trusts the cluster's issuer, and STS exchanges the token for short-lived role credentials pinned to one namespace and service account (IRSA or EKS Pod Identity on AWS, Workload Identity on GCP). Add why: the node's credentials are readable by every pod on it.

How do we keep secrets out of Terraform state?

Say the principle first: do not let Terraform see the secret where you can avoid it. Let the provider own it (manage_master_user_password on RDS), create the secret object empty and populate it out of band, pass values at apply time as sensitive variables rather than defaults, and on 1.10+ use ephemeral values and write-only arguments. Then treat what remains as a credential store: encrypted backend, tight IAM on the bucket, no secrets in outputs.

Is Vault worth it over the cloud provider's manager?

Make a call with the deciding features: Vault when you need dynamic credentials (per-session database users), multi-cloud or on-prem, or fine-grained leasing and revocation; otherwise the managed service is less to operate and integrates with IAM and CloudTrail for free. Name the cost you are trading: an HA Vault cluster is a tier-0 service you now run.

What does 'verify at admission' mean concretely?

Describe the gate: an admission controller (Kyverno, Gatekeeper, or a policy engine) rejects any image whose cosign signature or attestation does not verify against your trusted keys or identities, at deploy time, where it cannot be skipped. Say the line that scores: signing without verification at admission is decoration.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Scenario: what do you do next?

14:05. GitHub secret scanning alerts: an AWS access key pair belonging to the IAM user ci-deployer was pushed to a public repository 40 minutes ago inside a terraform.tfvars file. That key is used by a legacy Jenkins job to push images to ECR and update an ECS service. Jenkins has a production deploy scheduled at 15:00.

Step 1. What do you do first?

  1. Query CloudTrail first to see whether the key was actually used before deciding anything. The investigation is essential and comes next, but it does not shorten the exposure window; mitigate, then investigate.
  2. Deactivate the exposed access key in IAM now (delete it once Jenkins is updated), create a replacement, and accept that the 15:00 deploy may fail until Jenkins has the new credential. Public exposure means assume compromise — scrapers harvest public commits within minutes. Revocation is cheap and reversible; every minute the key stays active is not.
  3. Force-push to rewrite history and remove the file so nobody else sees it. It has already been seen; forks, caches and scrapers keep it, and rewriting history does nothing to the credential itself.
  4. Wait until after the 15:00 deploy so the release is not disrupted, then rotate. Trading a confirmed credential exposure for schedule convenience is a decision nobody will defend in the postmortem.

Step 2. The key is deactivated. CloudTrail shows, from an unfamiliar IP twelve minutes after the push: sts:GetCallerIdentity, s3:ListAllMyBuckets, secretsmanager:ListSecrets, then an AccessDenied on secretsmanager:GetSecretValue. What next?

  1. Treat it as an active intrusion: enumerate what the key was permitted to do, check for persistence (new users, keys, roles, trust-policy or Lambda changes), rotate any secret the key could have read, and open an incident with a written timeline. Reconnaissance calls followed by a denied read are an attacker probing; the denial shows least privilege held on that call, but you must verify nothing was left behind and rotate whatever was reachable.
  2. Delete the ci-deployer IAM user immediately. Deactivating the key already stopped the attacker; deleting the user before the investigation destroys evidence such as last-used data and breaks Jenkins for no additional safety.
  3. The AccessDenied proves the attacker failed; close the incident and write it up as a near miss. You saw the calls logged in this region by this trail; 'denied once' is not 'failed everywhere', and reconnaissance often precedes a second attempt with another key.
  4. Rotate every secret in the account right now. Rotate what the key could reach, prioritised by evidence; blanket rotation of hundreds of secrets mid-incident causes its own outages and buries the timeline.

Step 3. The postmortem is next week. What is the action item that removes this class of failure, rather than a reminder?

  1. Add a written rule that developers must never commit tfvars files. A rule is a reminder; the next paste lands in a README or a shell history.
  2. Replace the static IAM user with a role assumed through short-lived credentials (OIDC or an instance role for Jenkins), turn on push protection and secret scanning across the organisation, add pre-commit scanning as defence in depth, and alert on credential use from unexpected IPs or regions. It removes long-lived keys — the thing that leaked — and adds detection for the next leak; the class of failure, not the instance, is addressed.
  3. Make all repositories private. Private repositories leak too — through contractors, tokens, mirrors and laptops; the credential's lifetime is the root problem.
  4. Encrypt tfvars with git-crypt and document the decryption key in the repository README. A key stored next to the ciphertext is obfuscation, not encryption.
In short

Deactivate the leaked key at once, then read CloudTrail and check for persistence, then replace the static key with short-lived OIDC credentials.

Why

The scored shape is mitigate, investigate, then mechanise. Revoking first accepts a possible broken deploy in exchange for closing the window; the CloudTrail read afterwards is what turns "a key leaked" into "here is exactly what the attacker tried and what least privilege prevented". Persistence checks matter because credential theft is usually a foothold, not the goal. The durable fix is to make the leaked thing impossible to leak — credentials that expire in an hour are worthless in a public commit found tomorrow — and to add detection for the leaks that will still happen.

The common mistake

Starting with 'check CloudTrail to see whether it was used' or with rewriting git history. Both leave the credential live; scrapers harvest public commits within minutes and forks keep the file.

Read the docs

2 Answer out loud

Twelve services share one Postgres role whose password lives in a secrets manager. Design a rotation that no service notices, and explain where the usual attempts break. Three to six sentences, to a staff engineer.

In short

A strong answer uses two alternating database roles and makes services fetch the credential on each new connection, so no restart is needed.

What a strong answer does
  • rotation mechanics: Two database roles with identical grants (alternating-user) or an explicit dual-validity window; new credential written as the pending version and only promoted to current once valid; consumers fetch on each new connection or reload on signal rather than caching at boot; the old credential retired only after every consumer is observed using the new one.
  • failure modes: Explains that Postgres checks the password only at connect, so live connections survive but every reconnect with a cached value fails; names connection pools, autoscaled instances that start mid-rotation, and a canary-first rollout with auth-failure metrics as the verification.
  • communication: Leads with the invariant (at every instant the version consumers read is valid), then mechanism, then how it is verified; precise about ordering.
Why

Rotation is a distributed-systems problem dressed as a security chore: producers and consumers of a credential must agree on which version is valid without a global pause. The alternating-user pattern (or an explicit dual-validity window) gives that agreement, and fetch-on-connect makes consumers converge without restarts. Candidates who say "restart the services" have designed a rotation that requires an outage, which is why rotation never happens in those organisations.

The common mistake

'Rotate it and restart the services.' That is a rotation that requires an outage, which is why rotation never happens in those organisations; and forgetting that pools and autoscaled instances reconnect at unpredictable times.

Read the docs

3 Pick the strongest answer

A reviewer asks you to change uses: actions/checkout@v4 to uses: actions/checkout@<40-character commit SHA> # v4.x.y. What does the SHA pin protect against that the tag does not?

  1. Pinning by SHA means you stop receiving security fixes, so it is a net negative. Fixes arrive as reviewed bumps of the pin (Dependabot or Renovate open the pull request), which is exactly the review step a floating tag skips.
  2. Nothing — GitHub verifies that v4 points to a release signed by the publisher before running it. GitHub does not verify or freeze tag targets for actions; a tag is an ordinary ref the repository owner can force-move at any time.
  3. The SHA pin makes the action run faster because the runner skips ref resolution. Resolution cost is negligible either way; the change is about what code can run, not how fast it starts.
  4. A tag is a mutable Git ref: the maintainer of actions/checkout — or anyone who compromises their account — can move v4 to different code and every workflow using it runs that code on its next run; a commit SHA is content-addressed and cannot be pointed at different code. Immutability is the property; the tag gives you convenience and the upstream's promise, the SHA gives you the bytes you reviewed.
In short

A tag can be moved to different code at any time; a commit SHA cannot, so the SHA pin fixes exactly what runs.

Why

Every uses: line imports code that runs with your workflow's token and secrets. A version tag is a promise from the upstream that it will not move — a promise that breaks the day their account is phished or a maintainer decides v4 should include "one more fix". A full commit SHA is a hash of the tree, so the only way to change what runs is to change your workflow file, which goes through your review. The same logic applies to base images (FROM node:20@sha256:…) and to dependency lockfiles: pin by content, update by pull request.

Read the docs

4 Pick the strongest answer

An application stores 10 TB of objects encrypted with AWS KMS envelope encryption. Security asks you to 'rotate the KMS key'. What actually happens to the existing 10 TB?

  1. Each object was encrypted directly by the KMS key, so every object must be sent back to KMS and re-encrypted. Sending 10 TB through KMS would be impossible on size and cost alone; the whole point of the envelope is that KMS handles only the small data keys.
  2. Nothing is re-encrypted. Each object was encrypted locally with its own data key; only the data keys were wrapped by the KMS key. Rotation adds new key material for future wraps while KMS retains the old material to unwrap existing data keys, so the objects stay readable and untouched. Envelope encryption puts the KMS key one level above the data; rotating it changes how future data keys are wrapped and nothing about stored ciphertext.
  3. Existing objects become unreadable until they are re-encrypted with the rotated key. Rotation keeps every previous version of the key material for that key, so anything wrapped under old material still unwraps.
  4. KMS re-encrypts all 10 TB in the background using the new key material. KMS never sees the objects; its Encrypt and Decrypt operations accept at most 4 KB, which is why bulk data is encrypted client-side with data keys.
In short

Nothing is re-encrypted: only the small data keys were wrapped by the KMS key, and KMS keeps the old key material to unwrap them.

Why

Envelope encryption: generate a fresh data key per object, encrypt the object locally with it, ask KMS to encrypt (wrap) the data key under the root key, and store the wrapped data key next to the ciphertext. To read, send the wrapped key to KMS, get the plaintext data key back, decrypt locally. The root key never leaves the service and never touches the data, so rotating it only changes which key material wraps new data keys; old wrapped keys still unwrap because KMS keeps the old material. If a compliance rule really requires the data keys themselves to be re-wrapped, that is an explicit re-encrypt job you run, not a side effect of rotation.

Read the docs

5 Find what's broken

This is the permissions policy of the role your CI pipeline assumes via OIDC to deploy the api service. Security rejected it. Which three lines, and why?

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DeployToEcs",
      "Effect": "Allow",
      "Action": [
        "ecs:UpdateService",
        "ecs:DescribeServices"
      ],
      "Resource": "arn:aws:ecs:us-east-1:123456789012:service/prod/api"
    },
    {
      "Sid": "ReadSecrets",
      "Effect": "Allow",
      "Action": "secretsmanager:*",
      "Resource": "*"
    },
    {
      "Sid": "PassRole",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "*"
    },
    {
      "Sid": "Logs",
      "Effect": "Allow",
      "NotAction": "cloudtrail:*",
      "Resource": "*"
    }
  ]
}
In short

The three faults are secretsmanager:* on every secret (line 16), iam:PassRole on * (line 23), and Allow with NotAction (line 28).

What's broken
  • Line 16: secretsmanager:* on every resource lets the deploy role read, overwrite, and delete every secret in the account, not just fetch the ones the api service needs.
  • Line 23: iam:PassRole on Resource '*' is privilege escalation: the pipeline can attach any role in the account — including administrative ones — to the task it deploys and then act as that role.
  • Line 28: Allow with NotAction cloudtrail:* grants every action in every service except CloudTrail — an admin-equivalent grant disguised as a logging statement.
Why

Least privilege has three axes and this policy fails all of them: what (wildcard actions), on which resources (wildcard ARNs), and for whom the grant can be repurposed (PassRole is the classic escalation because it lets the caller borrow another identity's permissions). NotAction inside an Allow is the most dangerous idiom in IAM — it reads like a restriction but is a grant of the complement. The first statement is what good looks like: named actions on a named service ARN. iam:PassRole itself (line 22) is legitimate — ECS needs a task role passed to it — the fault is the unbounded resource on the next line.

Read the docs

6 Read the output

What does the call return, and which statement decides it?

# Identity policy attached to arn:aws:iam::123456789012:role/app-role
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret"],
    "Resource": "*"
  }]
}

# Resource policy on arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db-AbCdEf
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Deny",
    "Principal": "*",
    "Action": "secretsmanager:GetSecretValue",
    "Resource": "*",
    "Condition": {
      "StringNotEquals": { "aws:PrincipalArn": "arn:aws:iam::123456789012:role/payments-role" }
    }
  }]
}

# Executed with credentials from an assumed app-role session, same account
$ aws secretsmanager get-secret-value --secret-id prod/db
  1. Success. A Deny with Principal '*' applies only to anonymous or cross-account callers, not to roles in the same account. Principal '*' means every principal; combined with StringNotEquals on aws:PrincipalArn it denies everyone but the one named role.
  2. AccessDenied, but because the identity policy lacks kms:Decrypt for the key that encrypts the secret. Nothing here says a customer-managed key is in use (the default aws/secretsmanager key needs no separate grant), and the evaluation already ends at the explicit Deny before any KMS check.
  3. AccessDenied. The resource policy's Deny matches — the caller's aws:PrincipalArn is app-role, not payments-role — and an explicit Deny anywhere in the evaluation overrides the identity policy's Allow. Deny wins over any Allow regardless of which policy type it lives in; the condition simply excludes everyone except payments-role.
  4. Success. The identity policy allows GetSecretValue on every resource, and identity policies take precedence over resource policies. There is no precedence between policy types; the evaluation collects all applicable statements and any explicit Deny ends it.
In short

The call is denied: the resource policy's explicit Deny matches app-role, and an explicit Deny beats any Allow.

Why

Evaluation order: collect every policy that applies (identity, resource, permissions boundary, SCP, session), and if any statement is an explicit Deny that matches, the answer is Deny — full stop. Otherwise look for an Allow. The resource policy here is a deliberate allow-list pattern: deny everyone whose principal ARN is not the one role. For assumed-role sessions aws:PrincipalArn resolves to the role ARN, not the session ARN, which is what makes this condition usable. Note the pattern's cost: it also locks out administrators and Terraform until they are added to the condition.

Read the docs

7 Quick recall

A CVE lands in a library tomorrow and security asks which of your 200 deployed images contain it; you want the answer from a query, not from rebuilding everything. What machine-readable inventory of each artifact's components must you have produced and attached to every image at build time?

In short

The answer is an SBOM (software bill of materials).

Accepted

SBOM · sbom · Sbom

Why

A software bill of materials (SBOM), typically in SPDX or CycloneDX format, is generated per artifact and attached to its digest so a newly disclosed vulnerability can be matched to every deployed image that contains the affected component.

Read the docs

8 Pick the strongest answer

You operate validators for a proof-of-stake network. The validator process must sign votes and blocks continuously with a 'hot' identity key, so the key has to be online. Which placement best follows the general rule for secrets that must stay online?

  1. Bake the keypair file into the validator image; the registry is private. An image is a distribution artifact copied to every node, CI cache and laptop that pulls it; 'private' is not per-principal access control, and there is no audit trail or rotation.
  2. Inject the key as an environment variable so it never touches disk. Environment variables are inherited by every child process, readable from /proc by the same uid, and captured by crash dumps and debug endpoints; 'never on disk' ends at the first core dump.
  3. Keep the key inside a dedicated signer — an HSM- or KMS-backed service, or a remote-signer process on a hardened host — that the validator reaches over an authenticated local channel; the validator never holds the raw key, every signing request is auditable, and compromising the validator host does not yield the key. Put the secret behind a boundary that performs the operation (sign) instead of handing out the material — the same principle that makes KMS keys non-exportable.
  4. Store it in a secrets manager, fetch it once at startup into memory, and treat that as equivalent to a signer. Fetching from a manager is far better than env or image, but the validator process still holds the raw key; a signer boundary means host compromise does not equal key compromise.
In short

Keep the key inside a dedicated signer (HSM, KMS, or remote signer) so the validator never holds the raw key.

Why

Hot keys cannot be kept offline, so the goal shifts from "hide the material" to "shrink who can use it and see every use". A signer service that exposes only a sign operation, authenticates the caller, rate-limits, and logs each request achieves that; the validator becomes a client with no key to steal. Where a client cannot use a remote signer, the fallback is a file on tmpfs with owner-only permissions, fetched at start from a manager, on a host that runs nothing else — still better than env vars or a baked image, but with a wider blast radius that the design should acknowledge.

Next lesson Terraform core: state, plan/apply, lifecycle, providers, modules
Drill · Secrets and supply chain
0:00

Loading…