Secrets and key management
Keep secrets out of code, give them a short life, and be ready to rotate any of them in minutes.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
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.
It happens for real
CircleCI · 4 Jan 2023CircleCI security incident: customer secrets stolen from productionAn attacker copied customers' environment variables, keys and tokens from CircleCI's production systems, and CircleCI told every customer to rotate all their secrets. All incidents tagged “security”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.
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
Authorizationheader. - Container images. OWASP says never to put secrets in Docker
ENVorARGlines. 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:
- One central store. OWASP says to centralize and standardize secrets management. 2
- Access policy. Each service reads only its own secrets. This is least privilege, applied to machines.
- An audit log. It records who asked for which secret, and when. OWASP says the log must resist tampering. 2
- 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-1The 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:
- 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.
- The app sends the DEK to KMS. KMS encrypts it, or wraps it, with the key encryption key (KEK). The KEK never leaves KMS.
- 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.
- 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.
- 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.
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 gitand folders withgitleaks 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.
Trade-offs
| Option | Survives a Git leak? | Rotation effort | Main risk | Use it when |
|---|---|---|---|---|
| Hard-coded in code | No History keeps it. 10 | High. A code change and a deploy. | Anyone with the repo has it. | Never. |
| Environment variable or CI variable | Yes , if never committed. | Medium. Update and restart. | Readable by other processes, logs and dumps. 2 | Small apps, with no better option yet. |
| Secrets manager, static secret | Yes | Low. Scheduled rotation. 7 | The store itself, and its bootstrap credential. | Third-party API keys and passwords you cannot make dynamic. |
| Dynamic or OIDC credential | Yes | Low. Each credential expires on its own. Vault's own root credential still needs rotating. 4 | Setup 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.
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.
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
.envfiles 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.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 12 sources and related lessons
- 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. - 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. - The Twelve-Factor App, III. Config (opens in a new tab)
Why config, including credentials, must be strictly separate from code. - 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. - 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. - GitHub Docs, Configuring OpenID Connect in Amazon Web Services (opens in a new tab)
The id-token permission and the configure-aws-credentials step. - 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. - 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. - 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. - GitHub Docs, Secret scanning (opens in a new tab)
Scanning all of Git history, the partner program, and what to do with an alert. - GitHub Docs, Push protection (opens in a new tab)
Blocking a push that contains a secret, and what happens on a bypass. - 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
- Authentication and authorization: tokens, sessions and least privilege.
- OWASP Top 10 and secure coding: where secrets fit among the common flaws.
- Dependency and supply-chain security: trusting the code you did not write.
- Threat modelling and zero trust: finding what an attacker would target before you build it.