Reliability and security · L2Secrets and key management

Secrets and key management

Keep secrets out of code, give them a short life, and be ready to rotate any of them in minutes.

L2 SeniorReliability and security18 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 9 Nov 2026 · How we check content
Section 1 of 8

What broke

On 4 January 2023, CircleCI told its customers to rotate every secret they kept in it. CircleCI runs build and deploy jobs. Teams store API keys, tokens and cloud keys there, so those jobs can deploy. 1

The attack began on 16 December 2022. Malware on one engineer's laptop stole a valid single sign-on session. The session already had two-factor authentication behind it. So the attacker could act as the engineer from far away. 1

That engineer could create production access tokens. With them, the attacker reached some production databases and stores. On 22 December, they copied customer data, including environment variables, tokens and keys. 1

The data was encrypted at rest. But the attacker "extracted encryption keys from a running process", so they could potentially read it. 1

On 29 December, a customer reported odd GitHub OAuth activity. From 31 December, CircleCI rotated customers' GitHub OAuth tokens. On 4 January, it told customers to "assume they have been accessed" and rotate their secrets. The next day it revoked Project API tokens. 1

One laptop forced every customer into an emergency. The lesson for us: many secrets sat in one store, and the keys to decrypt them were in a running process.

Section 2 of 8

The idea in simple words

A secret is anything that gives access. OWASP lists database credentials, SSH keys, certificates and API keys. 2 OAuth tokens, signing keys and TLS private keys count too.

Three rules cover most of the work:

  • Keep secrets out of code and build output. The Twelve-Factor App asks for "strict separation of config from code". Its test: could you open-source the code today "without compromising any credentials"? 3
  • Make secrets short-lived and small. A stolen secret should work for minutes, not years, and reach one system, not all.
  • Be able to rotate any secret fast. Leaks will happen. Rotation is how you recover.

The key idea. Assume every secret will leak one day. Then design so a leak does little harm: short lifetimes, small scopes, an audit log, and a rotation you have already practised.

Section 3 of 8

How it works

How secrets leak

Secrets leak through ordinary paths:

  • Git commits. Deleting the line in a later commit does not help. The old commit still holds it. That is why GitHub's scanner checks "your entire Git history on all branches". 10
  • Logs and CI output. A debug line prints a request with its Authorization header.
  • Container images. OWASP says never to put secrets in Docker ENV or ARG lines. 2
  • Client apps. Anything shipped inside a mobile app or a JavaScript bundle can be read by anyone who downloads it.
  • Chat and AI tools. Someone may paste a config file into a chat or an AI prompt to get help.

Environment variables: better than code, not the end

The Twelve-Factor App says to put config in environment variables. They change per deploy without code changes, and they are unlikely to be committed by accident. 3

OWASP adds a warning. Environment variables "are generally accessible to all processes and may be included in logs or system dumps". It does not recommend them unless the other methods are not possible. 2 A better option is a file that the orchestrator mounts at run time, never one built into the image. 2

A secrets manager

A secrets manager, such as HashiCorp Vault, AWS Secrets Manager or GCP Secret Manager, gives you four things:

  1. One central store. OWASP says to centralize and standardize secrets management. 2
  2. Access policy. Each service reads only its own secrets. This is least privilege, applied to machines.
  3. An audit log. It records who asked for which secret, and when. OWASP says the log must resist tampering. 2
  4. Rotation. The store can change the secret on a schedule.

Short-lived credentials instead of stored keys

The best secret is one that does not exist until you need it.

Dynamic secrets. Vault's database engine creates a new database user when a client asks. Each user has a lease, for example 1 hour, which the client can renew up to a maximum, for example 24 hours. When the lease ends, Vault revokes the user. 4 Every service gets its own username. So you can trace a strange query back to one service instance. 4

OIDC from CI. A GitHub Actions job can deploy to a cloud with no stored cloud key. The job gets a signed token from GitHub's OIDC provider. The cloud checks it and returns an access token that "is only valid for a single job". 5

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      id-token: write   # lets the job request an OIDC token
      contents: read
    steps:
      # <pinned-sha> stands for a full commit SHA
      - uses: aws-actions/configure-aws-credentials@<pinned-sha>
        with:
          role-to-assume: arn:aws:iam::123456789012:role/deploy
          aws-region: eu-west-1

The id-token: write line does not give write access to anything. It only lets the job ask for the token. 6 OWASP gives the same advice for pipelines: avoid static bootstrap credentials and use short-lived OIDC tokens. 2

Rotation with two valid versions

A rotation has a risky moment. If the password changes before every app has the new one, some calls fail.

For rotation by a Lambda function, AWS Secrets Manager offers two strategies for database secrets. "Single user" changes one password. AWS calls it the simplest, and fine for most cases. There is a short window when the database may deny calls, so retry. 7 "Alternating users" keeps two users and changes them in turn. After a rotation, both users' credentials are valid. AWS says it fits apps that need high availability. 7

The same idea works for API keys and signing keys. Add the new key. Move every client to it. Then remove the old one.

Encryption keys: KMS and envelope encryption

Encrypting data creates a new problem: you must protect the key. AWS defines envelope encryption as "encrypting plaintext data with a data key, and then encrypting the data key under another key". 8

Google Cloud names the two keys. The data encryption key (DEK) encrypts the data. The key encryption key (KEK) wraps the DEK, and "the KEK never leaves Cloud KMS". 9 Step through it:

Envelope encryption: a data key locks the data, and a key in KMS locks the data keyYour app KMS holds the KEK Database new DEKdata + DEK= ciphertext DEKwrapped DEKKEK wrapsthe DEK stores ciphertextand wrapped DEKnever the plain DEK Read: KMS unwraps DEK, app decrypts Stolen database alone: no KEK, no data SeniorPath
  1. To save a record, your app makes a new data encryption key (DEK). It encrypts the data with the DEK, for example with AES-256-GCM.
  2. The app sends the DEK to KMS. KMS encrypts it, or wraps it, with the key encryption key (KEK). The KEK never leaves KMS.
  3. The app stores the ciphertext next to the wrapped DEK. It never stores the plain DEK. A new DEK for each write means DEKs do not need rotation.
  4. To read, the app sends the wrapped DEK to KMS. KMS checks the caller's permission, unwraps the DEK and sends it back. The app decrypts the data.
  5. A copy of the database holds only ciphertext and wrapped DEKs. To unwrap them, an attacker must call KMS with your permissions. The plain DEK in memory is still a weak point.
Step 1 of 5

Why not send all the data to KMS? Cloud KMS's Encrypt and Decrypt calls accept at most 64 KiB, because the service was built to manage KEKs. 9 Google also says to make a new DEK for every write, and never to share one DEK between two users. 9 That fits multi-tenancy well.

At the top sits a hardware security module (HSM). AWS KMS keys never leave the service's FIPS 140-3 Level 3 HSMs unencrypted. 8 OWASP says a dedicated HSM of your own is only needed when a law, contract or security policy demands it. 2 KMS also holds asymmetric keys, for example for signing. Their private keys never leave AWS KMS unencrypted. 8

Secret scanning

Catch secrets before they land, and find the ones that already did.

  • GitHub secret scanning checks all history. It is free and automatic on public repos. Private organization repos need GitHub Secret Protection. For partner secrets, GitHub tells the provider, which may revoke the credential. 10
  • Push protection blocks a push that contains a secret. For users it is on by default for public repos. For repositories, it needs GitHub Secret Protection, and an admin must turn it on. Anyone with write access can bypass it by giving a reason. The bypass raises an alert. 11
  • Gitleaks scans Git history with gitleaks git and folders with gitleaks dir. It also runs as a pre-commit hook. It is now in maintenance: security fixes only. 12

When a secret leaks

OWASP's order is: revoke, rotate, then delete the secret from the exposed system. 2 Do not start with a history rewrite. GitHub says removing a secret from history is slow and often not needed once the credential is revoked. 10

Then ask OWASP's questions: who had access, when was it used, and when was it last rotated? 2 Assume it was used, as CircleCI told its customers. 1 Treat it as an incident.

Section 4 of 8

Trade-offs

OptionSurvives a Git leak?Rotation effortMain riskUse it when
Hard-coded in codeNo History keeps it. 10High. A code change and a deploy.Anyone with the repo has it.Never.
Environment variable or CI variableYes , if never committed.Medium. Update and restart.Readable by other processes, logs and dumps. 2Small apps, with no better option yet.
Secrets manager, static secretYes Low. Scheduled rotation. 7The store itself, and its bootstrap credential.Third-party API keys and passwords you cannot make dynamic.
Dynamic or OIDC credentialYes Low. Each credential expires on its own. Vault's own root credential still needs rotating. 4Setup work, and a new runtime dependency.Databases, cloud access and CI deploys.

Simple rule: use short-lived credentials where the system supports them. Put everything else in a secrets manager with rotation.

Section 5 of 8

At work: how a senior uses this

  • For every secret, ask: "If this leaks tonight, who can rotate it, and how long does it take?"
  • Keep a list of secrets with owner, scope and last rotation date. Put expiry dates in monitoring.
  • Replace stored cloud keys in CI/CD with OIDC. Delete the old keys after.
  • Turn on push protection and a pre-commit scanner for every repo. On private organization repos, push protection needs GitHub Secret Protection.
  • Practise a rotation of your main database password before you need it.
  • In review, look for secrets in logs, test fixtures, Dockerfiles and front-end code.
  • Give each service its own credentials. Shared credentials make audit logs useless.
Section 6 of 8

With AI

Coding agents read your files and run commands. Treat them like any tool that can see secrets.

What to ask the agent

"Scan this repo and its Git history for hard-coded secrets. List file, commit and secret type. Do not print the secret values."

"Rewrite this GitHub Actions workflow to use OIDC with AWS instead of stored access keys. Pin every action to a commit SHA."

"Add envelope encryption for the ssn column using AWS KMS. Use a new data key for every write and store only the wrapped key."

What to check yourself

  • No real secret appears in the prompt, in .env files the agent can read, or in its output.
  • The agent did not log a secret while debugging, even "just for now".
  • New code reads secrets at run time from the secrets manager, not from a constant.
  • Envelope encryption code never writes the plain data key to disk or logs.
  • OIDC trust policies limit which repo and branch can assume the role.
  • If a secret was pasted into a chat, treat it as leaked and rotate it.
Section 7 of 8

Check yourself

1. An engineer pushed an AWS access key to a public repo 10 minutes ago. What do you do first?

Show answer

Revoke or rotate the key, then check its use since the push. OWASP puts revocation and rotation first. GitHub says that once a credential is revoked, removing it from history is often not needed.

2. In envelope encryption, what do you store next to the encrypted data?

Show answer

The data encryption key, wrapped by the key encryption key. Google Cloud's steps are to store the wrapped DEK with the data and never store a plain DEK. The KEK never leaves Cloud KMS.

3. Why does AWS say the alternating-users strategy fits apps that need high availability?

Show answer

Two database users take turns, so a valid set of credentials exists during the change. After rotation, both users' credentials are valid. An app that reads the secret mid-rotation still gets working credentials.

4. Your GitHub Actions workflow deploys to AWS. What removes the need for a stored AWS key?

Show answer

OpenID Connect, where the job swaps a GitHub token for a short-lived AWS token. With OIDC, the cloud issues a token that is valid for one job and then expires. No cloud key is stored in GitHub.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 12 sources and related lessons
  1. Rob Zuber, CircleCI Jan 4, 2023 security incident report (CircleCI blog, 12 January 2023) (opens in a new tab)
    The company's own timeline of the stolen session, the stolen secrets and the mass rotation.
  2. OWASP Cheat Sheet Series, Secrets Management Cheat Sheet (opens in a new tab)
    Central secrets managers, rotation, dynamic secrets, CI/CD, containers, detection and what to do after a leak.
  3. The Twelve-Factor App, III. Config (opens in a new tab)
    Why config, including credentials, must be strictly separate from code.
  4. HashiCorp Vault documentation, Database secrets engine (opens in a new tab)
    How Vault creates a unique database user for each client, with a lease that ends.
  5. GitHub Docs, OpenID Connect (opens in a new tab)
    How a GitHub Actions job gets a short-lived cloud token instead of a stored key.
  6. GitHub Docs, Configuring OpenID Connect in Amazon Web Services (opens in a new tab)
    The id-token permission and the configure-aws-credentials step.
  7. AWS Secrets Manager User Guide, Lambda function rotation strategies (opens in a new tab)
    Single-user and alternating-users rotation, and when each one fits.
  8. AWS Key Management Service Developer Guide, AWS KMS cryptography essentials (opens in a new tab)
    Envelope encryption, root keys, and the HSMs that KMS keys never leave unencrypted.
  9. Google Cloud Documentation, Cloud Key Management Service, Envelope encryption (opens in a new tab)
    DEKs and KEKs, the exact encrypt and decrypt steps, and rules for new DEKs.
  10. GitHub Docs, Secret scanning (opens in a new tab)
    Scanning all of Git history, the partner program, and what to do with an alert.
  11. GitHub Docs, Push protection (opens in a new tab)
    Blocking a push that contains a secret, and what happens on a bypass.
  12. Gitleaks, README (github.com/gitleaks/gitleaks) (opens in a new tab)
    An open-source secret scanner for Git history, folders and pre-commit hooks.

Real incident: CircleCI, 4 Jan 2023: CircleCI security incident: customer secrets stolen from production

Related: Authentication and authorization · OWASP Top 10 and secure coding · TLS and secure connections · CI/CD and trunk-based development · Working with coding agents · Incident response and postmortems · Multi-tenancy and noisy neighbours

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper