Secrets and API security
Vaults, rotation, environment variables and their limits, TLS everywhere, mTLS between services, and rate limits as security.
A secret is a value that gives whoever holds it your privileges. The engineering problem is not choosing a good one — it is that a secret has to reach a running process without being written down anywhere it can be read, copied, or kept.
Most of this lesson is about the places it gets written down anyway.
The one that survives being fixed
Somebody commits a token, notices, and removes it in the next commit:
### the working tree is clean:
### api.token=${API_TOKEN}
### git log --oneline:
### 7b29a3d Move the token to an environment variable
### 49c49b7 Add configThe repository looks correct. The commit message says the right thing. And then, from that same repository, with one command:
$ git log -p -S 'PLACEHOLDER-NOT-A-SECRET'
### 49c49b7 Add config
### +api.token=PLACEHOLDER-NOT-A-SECRET-123Removing a secret from a file does not remove it from history. It is in every clone, every fork, every CI cache, and every backup, and git log -S finds it in seconds — which is exactly what the bots scanning public repositories do, in under a minute, automatically.
So the rule is short and non-negotiable:
Prevention is cheap and worth having before you need it: .gitignore the file, a pre-commit secret scanner (gitleaks, trufflehog), and the same scan in CI so a bypassed hook is still caught. This project runs a secret scan over the diff on every edit and again at the end of each turn, which is the shape to copy.
Environment variables, and what they are actually good for
The standard answer is "put it in an environment variable", and it is a genuine improvement over a file in the repository — the value is not in version control, and it differs per environment without a code change.
Their limits are worth knowing precisely, because "we use environment variables" is often where a team stops:
- They are visible to the process and its children. Anything you shell out to inherits them.
- They leak into diagnostics. A crash reporter, a debug endpoint, an
/actuator/env, a stack dump, adocker inspect— several of these print the environment by default. - They do not rotate. Changing one means restarting the process.
- They are often in a file anyway — a
.env, a Compose file, a Kubernetes manifest — and that file ends up in a repository surprisingly often.
This project's own arrangement is a reasonable middle: secrets live in /etc/code10x.env, owned by root with mode 0600, referenced by the systemd unit's EnvironmentFile=. Not in the repository, not in the unit file, readable only by root, and there is exactly one definition of each value.
A secret manager is what the next step looks like
Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault — all the same idea: the application asks for the secret at run time, authenticating as itself, instead of being handed it at start time.
What that buys, in order of how much it matters:
- Rotation without a deploy. The manager changes the value; the application picks it up on its next fetch or on a refresh.
- An audit trail. Who read which secret, when. You cannot ask that of an environment variable.
- Short-lived credentials. The best version: the manager issues a database password valid for an hour, and a leaked one expires on its own.
- Access control per secret, rather than per machine.
The cost is real and should be named: another dependency on the start-up path, and a bootstrap problem — the application needs a credential to authenticate to the secret manager. Cloud platforms solve that with workload identity, where the instance's own role is the credential and nothing is stored at all.
Rotation is a property of the system, not an event
The question that decides whether you actually have rotation: can you change this secret right now, without downtime? If the answer is "we would need a maintenance window", you do not have rotation, and the next forced rotation — after an incident, at the worst moment — will be an outage on top of an incident.
What makes it possible is accepting two valid secrets at once during the change:
- Add the new secret alongside the old; both are accepted.
- Move every consumer to the new one.
- Remove the old.
That is expand → migrate → contract again — the same shape as the schema migrations lesson and the API versioning lesson. It is the general answer to changing something that other things depend on.
And rotate on a schedule, not only after an incident. A rotation you have performed fifty times is routine; one you have never performed is a plan.
TLS, and the "internal traffic" assumption
TLS everywhere, including between your own services. "It is internal" is an assumption about the network being trusted, and it is the assumption every lateral-movement attack is built on: one compromised pod on the same network reads everything.
- Terminate TLS at the edge — nginx, a load balancer — and use TLS inside as well. A service mesh will do the second for you.
- Verify certificates. Disabling verification to make a self-signed certificate work in development, and leaving that in a shared configuration, is a recurring way to turn TLS into theatre.
- mTLS is the step beyond: both sides present certificates, so the server knows which service is calling and not merely that somebody is. That gives you service identity without a shared token, and its real cost is certificate lifecycle — issuing, distributing and rotating them, which is why it usually arrives with a mesh rather than by hand.
Abuse protection is part of security
An API with perfect authentication and no limits is still exploitable, just not by breaking in:
- Rate limits per principal, with
Retry-After, as the rate-limiting lesson covers. A login endpoint without one is a brute-force target and a denial of service against your own hashing. - Bound every payload. A maximum request body size, a maximum page size, a maximum array length. Without them a single request can exhaust memory.
- Cap anything unbounded a client can ask for — a date range that scans a year of data, a regular expression a client supplies, a nesting depth in JSON.
- Timeouts on every outbound call. A dependency that hangs becomes your outage, and a thread pool full of waiting requests is indistinguishable from being down.
Under the hood: what a live rotation actually does, and why an env var can't do it without a restart
"Two secrets valid at once" is not a policy choice you bolt on — for some kinds of secret it is a hard requirement forced by how long the old value's consumers live. A database password is comparatively simple: create a second role, point new connections at it, drain the pool of connections still authenticated as the old role, drop the old role. But a JWT signing secret is harder in a specific, mechanical way: every token issued under the old secret keeps presenting itself for verification until it expires, and there is no way to reach into a client's storage and make it stop. So the verifier has to accept signatures produced by either the old or the new secret for a window at least as long as the longest-lived unexpired token from before the rotation — which, if you followed this course's sessions-and-tokens lesson and kept access tokens short-lived, is measured in minutes; if a token's lifetime was never bounded, the "instant" rotation is actually bounded by whatever that forgotten lifetime turns out to be. Rotation and token lifetime are not separate decisions — the second one sets a floor under how fast the first one can ever be.
The gap between an environment variable and a secrets manager is also mechanical, not a maturity difference. A process's environment block is handed to it once, by the operating system, at the moment it is created (exec) — there is no POSIX operation that reaches into a running process and changes what getenv() returns for it; the only way to give a process a new environment is to start a new process with one. That is the literal reason "changing an env var means restarting the process" is true and not just a convention: the value is copied into the process's own memory at creation and is never re-read from anywhere afterward. A secrets manager sidesteps this by not putting the value in the environment at all — the application holds a reference (an address, a key name) and fetches the actual value over the network, either on every use or on a refresh timer, so a rotation is visible the moment the next fetch happens, with no process restart required, because nothing about the process's own creation-time state has to change.
Try it yourself
Work out how long "two valid secrets" has to last
A service issues JWT access tokens signed with secret-A, each valid for 15 minutes, no refresh-token rotation involved. At 10:00 the team begins rotating the signing secret to secret-B, updating the verifier to accept both.
Before reading on: what is the earliest moment it is safe to make the verifier stop accepting secret-A, and why that specific moment rather than "as soon as secret-B is deployed"?
10:15 — a full token lifetime after the last token signed with the old secret could have been issued
The moment secret-B is deployed, the verifier accepts both — but tokens signed with secret-A before that moment are still out in the world, in browsers and API clients, and stay valid until their own 15-minute expiry, completely independent of when the server-side rotation happened. If the verifier drops secret-A acceptance the instant secret-B goes live, every caller holding a still-unexpired secret-A token gets rejected mid-session — a rotation that was supposed to be invisible becomes a self-inflicted mass sign-out. The safe moment to drop the old secret is the last possible issuance time plus the token's own lifetime: if the last secret-A token could have been minted right up until the deploy at 10:00, the last one expires at 10:15, and only then is dropping secret-A acceptance truly harmless. A shorter token lifetime is, among other things, a shorter mandatory wait before a rotation can finish.
Misconceptions
- "Rotating a secret means the old value stops working the moment the new one is issued." The opposite is what makes rotation safe: the old value has to keep working for a deliberate overlap window (see the exercise above) while every consumer moves to the new one. Skipping that overlap is what turns a routine rotation into an outage — it is the same expand → migrate → contract shape this lesson names for schema changes, and skipping the "expand" step is the mistake in both cases.
- "An environment variable is basically as protected as a secrets-manager value, just less convenient." They are not equivalent in exposure. A secret sitting in a process's environment is typically readable by anything running as the same user or root (via the process's own environment inspection, a crash dump, a container inspection command), inherited automatically by every child process whether or not that child needed it, and carries no per-secret access log; a secrets manager can grant access per secret, to a specific identity, and record every read. Convenience is a real difference, but it is not the only one.
Sources
- OWASP Secrets Management Cheat Sheet.
- NIST Special Publication 800-57 Part 1 — Recommendation for Key Management (rotation and cryptoperiods).
- RFC 7519 — JSON Web Token (JWT), for the token-lifetime dependency this lesson's rotation discussion relies on.