Skip to content

Secrets and Configuration

Summary

Shows how API keys and environment variables work, the many ways a secret leaks, how to rotate one, and small traps like the trailing newline that break an app silently.

Concepts Covered

This chapter covers the following 19 concepts from the learning graph:

Concept Concept Impact Score
API Key 48
Secret 45
Environment Variable 116
Dotenv File 13
Env Example File 12
Configuration 89
Hardcoded Secret 7
Secret in Git History 6
Secret Leak Paths 5
Secrets in Chat and Email 2
Client-Side Secret Exposure 1
Secret Rotation 6
Revoking a Key 3
Secrets Vault 1
Trailing Newline Trap 6
Whitespace Trimming 5
Env Schema Validation 4
Secret Scanner 5
Test vs Live Keys 1

Prerequisites

This chapter builds on concepts from:


The Spare Key Under the Flowerpot

The owner of a small bakery keeps a spare key to the back door under a flowerpot by the step. It started for a good reason. The baker who opens at five kept forgetting hers, and nobody wanted to wait in the dark for the owner to drive over. Over the years the spare key got copied. One copy went to the cleaner who comes on Sunday nights. One went to the man who services the ovens. A contractor borrowed one while he redid the floor and said he'd return it. A cashier who left last spring still has one on her keyring.

One evening the owner tries to count the copies and can't. She knows about four. There might be six. The contractor moved away, and nobody remembers whether he gave his back. Nothing is missing from the shop. She just doesn't know who can open the door.

Welcome to Secrets and Configuration

Sawyer waving welcome Gate or wall? Every secret in this chapter is a wall. One leaked key can open a member's photos or your bank account, and you can't take a copy back once it's out. You'll learn where keys belong, how they leak, and how to change the lock fast.

She could spend a week tracking down every copy. She doesn't. She calls a locksmith, who changes the lock in half an hour. Every old copy is now a piece of metal that opens nothing. She hands new keys to the people who still need one, and this time she writes down who has them.

Your app has keys too, and they get copied the same way. A key gets pasted into a chat so a helper can test something. A file full of keys goes out in an email. A key slips into a commit. Each copy was made for a good reason, and each one opens the same door. This chapter is about knowing where your app's keys are, keeping the copies few, and changing the lock quickly when you lose count.

Secrets and API Keys

Start with the word itself. A secret is any value that grants access, proves identity or unlocks money, and that would cause harm if someone else got it. Passwords are secrets. So is the address of your database when it carries a password inside it. So is the value your server uses to sign members' sessions, and the value that proves a payment notice really came from your payment company. A secret's whole job is to be known by only the parties that should know it. Once it is known by anyone else, it has stopped doing its job, even if nobody has misused it yet.

You will handle API keys more often than any other kind of secret. An API key is a long string of characters that an outside service gives you so your app can call that service and be billed for it. Chapter 2 described an API as a fixed way for one program to ask another for something. The key is how the other program knows who is asking. Your app sends the key with every request, usually in a header, and the service checks it before doing any work. A valid key gets an answer. A missing or wrong key gets a 401 Unauthorized status code, which Chapter 2 introduced.

An API key is a bearer credential. That means the service doesn't ask who is holding it. Whoever presents the key gets treated as you. If a stranger finds your image-search key, the image-search company sees calls from your account, answers them, and sends you the bill. If a stranger finds your payment company's secret key, they can see your customers' payment records and issue refunds. The key carries no memory of who it was meant for.

Ask what the key opens

Sawyer thinking Before you paste a key anywhere, ask what it opens and who would be billed. Check what it holds up. That one question tells you how carefully to handle it.

The Keys in the Dating-Safety App

The dating-safety app from Chapter 1 runs about eight checks against outside services, and almost every one of those services needs a key. Here is what a typical set of secrets looks like for an app with this stack, and what each one would let a stranger do. The names are illustrative. The kinds of access are the ones this stack really has.

Secret What it is What a stranger could do with it
DATABASE_URL The database address, with a username and password inside it Read, change or delete every member's scans, photos list and account
STRIPE_SECRET_KEY The payment company's secret key See payment records, issue refunds, create charges
STRIPE_WEBHOOK_SECRET Proves a payment notice came from the payment company Send fake "payment succeeded" notices and unlock paid features
SESSION_SECRET Signs the cookie that keeps a member signed in Forge a cookie and sign in as any member
IMAGE_SEARCH_API_KEY Key for the reverse image search vendor Run searches on your account and your bill
AI_MODEL_API_KEY Key for the AI model vendor Run any amount of AI work on your bill
PEOPLE_SEARCH_API_KEY Key for the public-records vendor Look up people on your account, under your name
SMS_AUTH_TOKEN Key for the text-message vendor Send texts that appear to come from your app
STORAGE_ACCESS_KEY Key for the private photo bucket Download members' private photos

Read down the right-hand column. Three rows lose money, and that is the harm most builders picture first. The rows that worry a safety app more are the ones that expose members: the database, the session secret and the photo bucket. In the language of Chapter 1, every secret in this table is a must-be-right part. A leak can't be undone, and the blast radius of the top row is every member the app has.

Two things in the table aren't API keys in the narrow sense. The session secret is a value your app made up itself. The webhook secret is a signing value the payment company gives you so your server can check that a notice came from it; your app never sends it anywhere. Neither one is used to call a service. They are still secrets, because a stranger who holds them can pretend to be someone they aren't. That is why this chapter talks about secrets in general and treats API keys as the most common case.

Tell your agent

"List every secret this app uses: API keys, database passwords, signing secrets, webhook secrets, storage keys. For each one, give its name, which outside service or part of the app uses it, and one sentence on what a stranger could do with it. Show me names only. Don't print any secret values."

Configuration and Environment Variables

Your app needs to know more than its secrets. It needs to know which port to listen on and where the database lives. It needs to know how many scans a member may run in a day, and which AI model to call. Configuration is the set of values that tell an app how to behave in a particular place, kept apart from the code so they can change without changing the code. The same code runs on your laptop, on a test server and in production. What differs between them is the configuration.

Some configuration is secret and most of it isn't. The port number and the daily scan cap are plain settings. Nobody gains anything by learning that your app allows 20 scans a day. The database address and the payment key are secrets. Both kinds belong outside the code, but for different reasons. Plain settings stay outside the code so you can change them without a new deploy. Secrets stay outside the code so they never land in the code's history.

Here is the configuration of the dating-safety app, sorted by kind.

Name Example value Secret? Why it lives outside the code
PORT 3000 No Different on each machine
NODE_ENV production No Tells the code which environment it is in
DAILY_SCAN_CAP 20 No The builder may change it without a deploy
AI_MODEL_ID the name of the model the message check calls No Chapter 9 explains why model names belong in one place
VITE_STRIPE_PUBLISHABLE_KEY pk_live_... No, public by design Different for test and live
DATABASE_URL postgres://user:password@host/db Yes Holds a password
STRIPE_SECRET_KEY sk_live_... Yes Grants access to payments

The publishable key in the fifth row is worth a second look. Payment companies issue two keys. The secret key stays on your server. The publishable key is made to be shipped to the browser, and it can only start a payment, never read one.

Environment Variables

Most apps hand configuration to a running program through environment variables. An environment variable is a named value that the operating system gives to a program when the program starts. Every running program gets a small list of these name-and-value pairs, like a note slipped under its door before it begins work. The program reads the note and acts on it. The code never contains the values, only the names.

In a Node.js server, which Chapter 3 described, the list is available as process.env. The line below reads the payment key by name. The name is in the code. The value isn't.

// Read the payment key from the environment, not from the code.
const stripeKey = process.env.STRIPE_SECRET_KEY;

Where does the value come from? It depends on where the app runs.

  • In production, the hosting platform supplies it. Railway, Vercel and similar platforms have a settings page where you type each name and value, and the platform hands them to your app every time it starts. Chapter 14 covers this platform secret store in detail.
  • On your laptop, a small file supplies it, as the next section shows.
  • In a test run, the test tool may set a few values of its own, often fake ones.

This split makes environment variables useful. The code is the same in all three places, and it can be copied, shared and stored in git without carrying a single secret. The values live with the machine.

Environment variables have one property that matters later in this chapter. Every value is a plain string of characters. The operating system doesn't know that DAILY_SCAN_CAP should be a number or that STRIPE_SECRET_KEY should start with sk_. It hands over exactly the characters it was given, including any space or line break someone typed by accident. The program has to check what it received.

One Request, Followed to the Key

Here is how the payment key travels when a member upgrades to a paid plan. Each step uses ideas from Chapter 2.

  1. The builder types STRIPE_SECRET_KEY and its value into the hosting platform's settings page once.
  2. When the server starts, the platform hands that value to the Node.js process as an environment variable.
  3. A member clicks "Upgrade" in the browser. The browser sends a POST request to the app's own server, with no key in it.
  4. The server reads process.env.STRIPE_SECRET_KEY and sends its own request to the payment company, with the key in a header.
  5. The payment company checks the key, creates the checkout, and answers 200 OK.
  6. The server passes the checkout link back to the browser.

The key traveled from the settings page to the server and from the server to the payment company. It never went to the browser and never appeared in the code. That path is the one to aim for with every secret. The rest of this chapter is about the ways a key leaves it.

Tell your agent

"Make a table of every environment variable this app reads, front end and back end. For each one, show its name, where in the code it is read, whether it is a secret, and what the app does if it is missing. Don't print any values."

Dotenv File

Your laptop has no settings page, so builders use a file. A dotenv file is a plain text file named .env that sits in the project folder and lists environment variables, one per line, for the app to load when it starts on your machine. The name starts with a dot, which hides it in most file browsers. A small package, also called dotenv, reads the file and puts each line into process.env before the rest of the code runs. Vite reads .env files on its own.

A dotenv file for the dating-safety app looks like this. Every value here is fake.

# .env  (on the builder's laptop only, never committed)
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://dev:dev@localhost:5432/safety
STRIPE_SECRET_KEY=sk_test_abc123
IMAGE_SEARCH_API_KEY=img_abc123
DAILY_SCAN_CAP=20

The file is convenient, and it is also the single most dangerous file in the project. It holds every secret in one place, in plain text, in the same folder as the code you commit. Chapter 5 introduced the .gitignore file, which lists files git should leave out. The first line of protection is a .gitignore that names .env, so git skips it when it gathers files for a commit. The second line, a secret scanner, comes later in this chapter, because a .gitignore can be edited, renamed or missed.

Notice the third and fourth lines. On a laptop the database is a local copy and the payment key is a test key. That is the habit to keep: the laptop's .env should hold the weakest keys that still let you work. Many vendors, though, offer only one kind of key. The image-search key on a laptop may be the same paid key that production uses. Treat every line of a dotenv file as live unless you know for certain it isn't.

Env Example File

If the .env file is never committed, how does a new helper, or a new agent session, know which variables the app needs? The answer is a second file. An env example file is a file named .env.example that lists every environment variable the app reads, with blank or fake values, and is committed to the repository so anyone can see what to fill in.

# .env.example  (committed; copy to .env and fill in)
PORT=3000
NODE_ENV=development
# Postgres address. Local default shown; production comes from the host.
DATABASE_URL=postgres://dev:dev@localhost:5432/safety
# Payment company secret key. Use a sk_test_ key here, never sk_live_.
STRIPE_SECRET_KEY=
# Reverse image search vendor key. Ask the owner; it is in the vault.
IMAGE_SEARCH_API_KEY=
DAILY_SCAN_CAP=20

The example file does three jobs. It is the list of what the app needs. It is a place for a short comment on each value, such as which kind of key to use. And it makes the gap visible when the code starts reading a new variable that nobody added to the list. The dating-safety app had no .env.example for a while, which is one of the documentation gaps Chapter 15 returns to. Without it, the only full list of the app's settings was the .env file itself, and the easiest way to share a list is to share the file.

Tell your agent

"Check that .env and every .env.* file except .env.example are listed in .gitignore. Then create or update .env.example so it names every environment variable the code reads, with a one-line comment on each and no real values. Show me the diff before you commit."

Hardcoded Secrets

Sometimes the key never makes it into an environment variable at all. A hardcoded secret is a secret written directly into the source code as a literal value, so that anyone who can read the code can read the secret. It looks like this.

// A hardcoded secret: the value is in the code itself.
const client = new ImageSearch({ apiKey: "img_live_9f8e7d6c5b4a" });

Hardcoding happens for ordinary reasons. An agent is asked to "get the image search working," the builder pastes the key into the chat, and the agent puts it where it's needed so the call succeeds. The test passes. The key now lives in a source file, and the next commit carries it into git. Nothing on screen looks wrong.

An agent can fix it in one line, in seconds.

// The same call, reading the key from the environment.
const client = new ImageSearch({ apiKey: process.env.IMAGE_SEARCH_API_KEY });

Moving the key out of the code still doesn't take it out of the past. If the hardcoded version was ever committed, the key is still in git, and the next section explains why that matters. A hardcoded secret that reached a commit has to be treated as leaked, which means it has to be rotated, not just moved.

Tell your agent

"Search all source files, config files, scripts and tests for anything that looks like a hardcoded secret: API keys, tokens, passwords, connection strings with a password in them. List the file and line for each one, with the value masked. Tell me which ones were ever committed, because those need rotating. Then wait for my OK before you move each one into an environment variable and add it to .env.example."

How Secrets Leak

A secret can leave its intended path in only a handful of ways, and they repeat across almost every app. The secret leak paths are the routes by which a secret ends up somewhere it wasn't meant to be: in git history, in chat and email, in the browser bundle, in logs, and in screenshots and screen shares. Each one is ordinary. None needs an attacker to start it. Each one makes a copy, and copies are what the bakery owner lost count of.

Secret in Git History

Chapter 5 described git as a record of every save point, kept forever so you can go back. That record is the reason a leak into git is so hard to clean up. A secret in git history is a secret that was included in any past commit, which stays readable in the repository's history even after a later commit deletes it from the current files.

Here is how it happens. A commit adds a file with a live key in it. The builder notices an hour later and makes a second commit that deletes the line. The current files look clean, and a search of the project finds nothing. But the first commit is still there, and anyone with the repository can run one command to see it. So can anyone who copied the repository during that hour, and any service that keeps a copy.

Two facts make this worse than it sounds.

  • Public repositories are watched. Automated tools scan every push to public GitHub for strings shaped like keys. A key pushed to a public repository can be found and used within minutes, well before a builder notices.
  • Private repositories are copied. A private repository is safer, but it is still copied many times. Every laptop that downloads it gets a copy. So does every agent session that reads it, and every service connected to it, such as a hosting platform or a code review bot. Private limits who can look. It doesn't limit how many copies exist.

There are tools that rewrite git history to remove a file from every past commit. They are worth using sometimes, and Chapter 5's warnings about rewriting shared history apply. But rewriting history doesn't reach the copies already made. The only fix that reaches every copy is to make the key itself stop working, which is the subject of the section on revoking and rotating.

Secrets in Chat and Email

Chat and email feel like the most harmless path. Secrets in chat and email means secrets pasted into a message, attached to an email or shared in a chat tool. From there they are stored on the provider's servers, synced to every recipient's devices, kept in backups and search indexes, and forwarded further. Deleting the message on your side removes one copy out of many.

This path now includes AI chat. When you paste a key into a conversation with a coding agent so it can "just test the call," the key is in that conversation's transcript, on your machine and often on the provider's servers. The agent may also write it into a file. A safer habit is to put the key in .env yourself and tell the agent the variable's name.

Client-Side Secret Exposure

Another path catches many builders who use a framework like Vite. Client-side secret exposure is a secret leaking because it was included in the code sent to the browser, where any visitor can read it with the browser's built-in tools. Chapter 2 explained that the front end runs on the member's device. Everything in it, including every value it reads, is downloaded to that device in a file called the bundle.

Vite has a rule to stop this happening by accident. It only puts environment variables into the bundle if their names start with VITE_. That rule is good, and it creates a trap. When a front-end call fails because the browser can't see a key, the quick fix is to rename IMAGE_SEARCH_API_KEY to VITE_IMAGE_SEARCH_API_KEY. The call starts working, and the key is now in the bundle for every visitor to read. The working fix is to move the call to the server, as the worked example in the previous section showed. Only values that are public by design, such as the payment company's publishable key, belong under VITE_.

The rename that ships your key

Sawyer warning If an agent fixes a failing front-end call by adding VITE_ to a key's name, stop and look. The call works because the key is now in every visitor's browser. Move the call to the server instead.

Logs and Screens

Two more paths round out the list. Logs are the running record a server writes about what it is doing, and a key ends up there when code prints a whole request, a whole config object or a whole error that contains one. Chapter 12 covers secrets in logs and how to keep them out. Screens are the last path. A screenshot of a settings page, a screen share during a demo, or a recorded walkthrough can show a key to everyone watching, and the recording keeps it.

Diagram: Where a Secret Lives and Where It Leaks

Run the Where a Secret Lives and Where It Leaks MicroSim Fullscreen

Where a Secret Lives and Where It Leaks

Type: graph-model sim-id: secret-homes-and-leaks
Library: vis-network
Status: Specified
Bloom Level: Understand
Bloom Verb: classify
Learning Objective: The learner will classify each of ten places an API key can end up as either an intended home for the key or a leak path, and state for each leak path why deleting the copy there isn't enough.

Prerequisites: secret, API key, environment variable, dotenv file, hosting platform settings, git history, browser bundle, logs (all defined in the sections above).

Evidence of Mastery: Before any node's answer is shown, the learner marks every one of the ten nodes "Intended home" or "Leak path" and presses Check. A node is correct when the mark matches the answer column in Content. Mastery is 9 of 10 correct on the first attempt. Clicking a node to read its infobox after Check is exploration, not evidence.

Misconceptions: (1) A private repository is a safe place for a key. (2) Deleting a message or a commit removes the leaked key. (3) A VITE_ variable is still private because it is an environment variable. (4) The local .env file is a leak in itself.

Instructional Rationale: Classifying places is an Understand task: the learner has to apply the definition of a leak path (a copy the owner no longer controls) to each place. Marking all nodes before any answer appears forces a prediction instead of recognition.

Content:

Ten nodes, each with a label, an answer and infobox text.

Node Answer Infobox text
Vendor dashboard (where the key is created) Intended home The vendor made the key and can revoke it here. This is where rotation starts.
Password vault Intended home The one place people go to find the key. Access is limited and every read is recorded.
Hosting platform settings Intended home The platform hands the key to the server as an environment variable at start-up.
Server process (environment variable) Intended home The running server holds the key in memory and sends it only to the vendor.
Local .env file, listed in .gitignore Intended home Allowed on the builder's laptop, as long as git ignores it and it holds the weakest keys that still work.
Git history Leak path Every clone and fork has a copy. Deleting the line in a later commit leaves it in the earlier one.
Email attachment Leak path Copies sit on mail servers, every recipient's devices and backups, and can be forwarded.
Chat message (team chat or AI agent chat) Leak path The provider stores the message and syncs it to every device. Deleting your copy leaves the others.
Browser bundle (VITE_ variable) Leak path Every visitor downloads the bundle and can read the key with the browser's tools.
Server log line Leak path Logs are copied to log services and kept for weeks, and more people can read them than can read secrets.

Edges (solid arrows show the intended path; dashed arrows show how a key reaches a leak path):

From To Style Edge label
Vendor dashboard Password vault solid builder saves new key
Password vault Hosting platform settings solid builder enters key
Hosting platform settings Server process solid given at start-up
Password vault Local .env file solid builder copies test key
Local .env file Git history dashed .env committed
Local .env file Email attachment dashed file sent to share settings
Password vault Chat message dashed key pasted to a helper or agent
Hosting platform settings Browser bundle dashed key renamed with VITE_
Server process Server log line dashed whole config printed

Provenance: The ten places are from this chapter's sections "Dotenv File," "How Secrets Leak" and its subsections. The VITE_ prefix rule is from the Vite documentation on environment variables (vitejs.dev/guide/env-and-mode). The edge stories are illustrative.

Rules: A node is an intended home if the owner controls every copy there and can name who can read it. A node is a leak path if a copy exists that the owner can't delete or can't list. No node is both.

Learner Activity:

  1. The learner sees all ten nodes and all nine edges, with every node unmarked and every node the same neutral style.
  2. The learner clicks each node and chooses "Intended home" or "Leak path." Changing a mark before Check is allowed.
  3. When all ten are marked, the Check button becomes active. The learner presses Check.
  4. Each node shows a correct or incorrect sign. Nodes take the style of their answer, so homes and leak paths now look different.
  5. The learner clicks any node to read its infobox text.

Feedback: One attempt; marks lock after Check. A correct node shows "Right. " followed by its infobox text when clicked. An incorrect node shows "Not quite. " followed by its infobox text. A summary reads "n of 10 correct." If the learner marked "Local .env file" as a leak path, an extra line appears: "The file is allowed on your laptop. It becomes a leak when it is committed, emailed or pasted."

Starting State: Ten unmarked nodes and nine edges. The prompt reads "A key can end up in each of these places. Which are homes you control, and which are leaks?"

Chapter Anchors: Ten places, five intended homes, five leak paths. The leak paths named in the chapter are git history, chat and email, the browser bundle, logs, and screenshots and screen shares (the last is described in prose only and isn't a node). Vite puts only VITE_ variables in the bundle.

The Three Leaks in the Running Example

The dating-safety app had three secret leaks found after launch. Each one followed a path from the list above, and each one started with an ordinary reason.

What happened Leak path What it exposed
A live API token was committed in a source file Git history One vendor account, on the app's bill
A whole .env file was committed Git history Every secret in that file at once
A production .env file went out by email Email Every production secret, including the database

Each row is worse than the one above it. A single token reaches one vendor. A whole .env file reaches everything in it. A production .env file reaches the database that holds every member's scans. This is blast radius from Chapter 1, applied to secrets: the more keys a single copy holds, the more one slip exposes.

None of these is unusual, and none says anything about the builder. They are the three most common leaks in apps built quickly, by people with training or without it. What matters is the response, and the cheap habits that stop the next one.

Tell your agent

"Search this repository's full git history, not just the current files, for anything that looks like a secret, and for any .env file that was ever committed. For each hit, give the commit, the date, the file and the variable name, with the value masked. Don't change any history yet. I need the list so I can decide which keys to rotate."

Test Keys and Live Keys

Before getting to the response, one distinction makes leaks less costly. Many vendors give you two sets of keys. Test vs live keys is the split between two kinds of key. Test keys work only against a vendor's practice system, where nothing is real and nothing is charged. Live keys work against the real system with real money and real data. The payment company in the dating-safety app marks them in the key itself: test secret keys start sk_test_, and live ones start sk_live_.

A test key that leaks is a small problem. A stranger can make fake charges in your practice account and nothing more. A live key that leaks is a large one. That gives you a rule worth keeping: live keys exist only in production, and every other place, including your laptop and every agent session, uses test keys. When a vendor offers no test mode, which is common for image search and people search, ask whether they offer a second key with a low spending limit for development. Then treat that key as live anyway.

A gate and a wall in one vendor

Sawyer thinking Gate or wall? A test key is a gate: if it leaks, you swing it shut and move on. A live key is a wall. Keeping live keys in production only means most of your mistakes land on gates.

Because of the prefix, code can check itself. A server that starts in production with a sk_test_ key will take no real payments, and a laptop that starts with a sk_live_ key is one bug away from a real charge. Both can be caught at start-up, as the env schema section shows.

Tell your agent

"For each outside service this app uses, tell me whether the vendor offers separate test and live keys, and how to tell them apart. Then check which kind .env.example asks for and which kind the code expects in each environment. Don't print any key values."

When a Key Leaks: Revoke and Rotate

The bakery owner didn't chase down every copy of the key. She changed the lock. The same move works for secrets, and it's the only move that reaches every copy at once, including the ones in git history, in someone's inbox and in a stranger's notes.

Revoking a key means telling the service that issued it to stop accepting it, so that any request carrying that key fails from then on. Every vendor dashboard has a button for this, usually labeled "revoke," "delete" or "roll." Revoking is instant and complete. It also breaks your own app, if your app was still using that key.

Secret rotation is replacing a secret with a new one everywhere it is used, and then revoking the old one, so the app keeps working and the old value becomes useless. Rotation is revoking with a replacement ready first. You can rotate because of a leak, because someone with access left the project, or on a schedule as routine care.

Rotating the Committed Live Token

Take the first leak from the dating-safety app: a live API token for one vendor, committed in a source file. Suppose the repository is private and the vendor's usage page shows no calls the app didn't make. Here is the rotation, step by step.

  1. Create a new key in the vendor's dashboard. Most vendors let two keys be active at once, which is what makes a smooth rotation possible.
  2. Save the new key in the vault, described in the next section, so there is one place it's written down.
  3. Put the new key where the app reads it: the hosting platform's settings for production, and a test key in your local .env if the vendor has one.
  4. Deploy, and check that the app works with the new key. Run one scan and confirm the check that uses this vendor came back with a result, not "not checked."
  5. Revoke the old key in the vendor's dashboard. From this moment the copy in git history opens nothing.
  6. Check the vendor's usage log for the period between the commit and the revoke. Calls you didn't make tell you the key was used by someone else, and how much it cost.
  7. Fix the code so it reads the key from an environment variable, and add a secret scanner so the next commit like this one is blocked. Both come later in this chapter.

Steps three to five come in this order to avoid downtime. The app switches to the new key before the old one stops working. That order is right when nothing suggests the key is being misused.

When something does suggest it, the order flips. Say the key was pushed to a public repository, or the usage log shows calls you didn't make. Then revoke first, and accept a few minutes of a broken check while you put the new key in place. This is a trade-off of the kind Chapter 1 described. Minutes of "not checked" on one of eight checks is a two-way door. A stranger running up your bill or reading your members' data is a one-way door. When a leaked key is being used, the one-way door wins.

The other two leaks in the dating-safety app rotate the same way, with more keys. A committed .env file means rotating every secret in it. An emailed production .env file means rotating every production secret. That includes the database password, which needs a few minutes with the app offline while it changes. It also includes the session secret, and changing it signs every member out once. Neither is pleasant. Both are much cheaper than leaving the keys alive.

Diagram: Leak Response Drill

Run the Leak Response Drill MicroSim Fullscreen

Leak Response Drill

Type: microsim sim-id: leak-response-drill
Library: p5.js
Status: Specified
Bloom Level: Evaluate
Bloom Verb: prioritize
Learning Objective: The learner will prioritize the response to three leaked-secret incidents from the dating-safety app, putting rotation steps in a safe order and choosing which values in a leaked file must be rotated, with no leaked secret left working at the end.

Prerequisites: secret, API key, dotenv file, test vs live keys, revoking a key, secret rotation, secret in git history, secrets in chat and email (all defined in the sections above).

Evidence of Mastery: Incident 1: the learner orders the six real steps and discards the two distractor steps; correct when the order matches the answer exactly and both distractors are discarded. Incidents 2 and 3: the learner marks each line of the leaked file "Rotate" or "Leave"; correct when every line matches the answer column. Mastery is all three incidents correct, with at most one retry in total.

Misconceptions: (1) Deleting the file and committing again fixes a leak. (2) Rewriting git history makes the key safe. (3) Only the payment key needs rotating. (4) Every line in a .env file is a secret. (5) A key from a local .env file is harmless because it isn't production.

Instructional Rationale: Evaluating a response means weighing steps against a standard (no leaked key left working, the least downtime when there is no sign of misuse). Ordering steps and choosing what to rotate makes the learner judge each item rather than recall a list.

Content:

Incident 1 (from the dating-safety app): a live API token for the image search vendor was committed in a source file. The repository is private. The vendor's usage log shows no calls the app didn't make.

Step cards, shown shuffled. The answer order is:

  1. Create a new key in the vendor's dashboard.
  2. Save the new key in the password vault.
  3. Put the new key in the hosting platform's settings.
  4. Deploy and run one scan to confirm the image check returns a result.
  5. Revoke the old key in the vendor's dashboard.
  6. Check the vendor's usage log for calls between the commit and the revoke.

Distractor cards, to be discarded:

  • "Delete the key from the file and commit again." Why discard: the old commit still holds the key.
  • "Rewrite git history to remove the key, and stop there." Why discard: copies already made keep the key, and it still works until revoked.

Incident 2 (from the dating-safety app; file contents illustrative): the builder's local .env file was committed.

Line Answer Why
PORT=3000 Leave A plain setting.
NODE_ENV=development Leave A plain setting.
DATABASE_URL=postgres://dev:dev@localhost:5432/safety Leave This address works only on the builder's own laptop.
STRIPE_SECRET_KEY=sk_test_... Rotate A test key, so lower urgency, but it still opens the practice account.
IMAGE_SEARCH_API_KEY=img_... Rotate The vendor has no test mode, so this is the same paid key production uses.
AI_MODEL_API_KEY=... Rotate Anyone can run AI work on the app's bill.
VITE_STRIPE_PUBLISHABLE_KEY=pk_test_... Leave Public by design.
DAILY_SCAN_CAP=20 Leave A plain setting.

Incident 3 (from the dating-safety app; file contents illustrative): the production .env file went out as an email attachment.

Line Answer Why
PORT=3000 Leave A plain setting.
NODE_ENV=production Leave A plain setting.
DATABASE_URL=postgres://app:...@db.host/safety Rotate Opens every member's data. Needs a short maintenance window.
STRIPE_SECRET_KEY=sk_live_... Rotate Opens payment records and refunds.
STRIPE_WEBHOOK_SECRET=whsec_... Rotate Lets a stranger fake "payment succeeded."
SESSION_SECRET=... Rotate Lets a stranger sign in as any member. Rotating signs everyone out once.
IMAGE_SEARCH_API_KEY=img_... Rotate Searches on the app's bill.
SMS_AUTH_TOKEN=... Rotate Texts that appear to come from the app.
VITE_STRIPE_PUBLISHABLE_KEY=pk_live_... Leave Public by design.
DAILY_SCAN_CAP=20 Leave A plain setting.

Provenance: The three incidents are from the dating-safety app's gaps in research/seed-notes.md. The file contents are illustrative and must be labeled "illustrative file." The step order is from this chapter's section "A Worked Example: Rotating the Committed Live Token."

Rules: A line is "Rotate" if a stranger holding it could reach data, money, or a vendor account, or could pretend to be the app or a member. A line is "Leave" if it is a plain setting, is public by design, or works only on the builder's own machine. In incident 1, steps 3 to 5 must be in the order shown, because there is no sign of misuse; the feedback for incident 1 notes that with signs of misuse, step 5 moves first.

Learner Activity:

  1. The learner sees incident 1's description and eight shuffled cards.
  2. The learner drags six cards into a numbered list and drags two cards to a "Discard" area, then presses Check.
  3. Each card shows a correct or incorrect sign. If any is wrong, the learner may retry incident 1 once with the cards reshuffled.
  4. The learner moves to incident 2 and sees the eight lines of the file, each with a Rotate and a Leave button. The learner marks every line and presses Check.
  5. Each line shows a correct or incorrect sign and its Why text.
  6. The learner moves to incident 3 and repeats steps 4 and 5 with its ten lines.
  7. A summary shows each incident as correct or not, and counts the keys rotated: 1 in incident 1, 3 in incident 2, 6 in incident 3.

Feedback: One retry in total, usable on any incident. Correct items: "Right. " plus the Why text. Incorrect items: "Not quite. " plus the Why text. After incident 1 is checked, a note reads: "If the key had been in a public repository, or the usage log showed calls you didn't make, you would revoke first and accept a few minutes of a broken check."

Starting State: Incident 1's description and eight shuffled cards. The prompt reads "A live key was committed. Put the response in order, and throw out the steps that don't help."

Chapter Anchors: Three incidents: a live token committed, a whole .env committed, a production .env emailed. Seven steps in the worked example, of which the first six are cards here and the seventh (fix the code, add a scanner) is shown in the summary. Steps 3 to 5 avoid downtime. With signs of misuse, revoke first. Rotating the session secret signs every member out once.

Tell your agent

"Write a rotation runbook for each secret this app uses, in a new file called docs/rotating-secrets.md. For each one: where to create a new key, every place the app reads it (hosting platform, local .env, the automatic checks that run on every push), how to check the app works after the change, where to revoke the old key, and anything that breaks during the switch, such as members being signed out. No secret values in the file."

Where Secrets Should Live: The Vault

The bakery owner ended by writing down who had keys. Apps need the same list. A secrets vault is a tool that stores secrets encrypted, controls who can read each one, and records every time one is read or changed, so there is one trusted place to find a key and no reason to send one around. For a small team, a password manager with shared folders, such as 1Password or Bitwarden, does the job. Larger apps use a dedicated secrets manager, such as Doppler, AWS Secrets Manager or HashiCorp Vault, which can also hand secrets straight to the hosting platform.

A vault answers the question that causes most chat and email leaks: "Can you send me the key?" With a vault, the answer is "It's in the vault." The helper gets access to that one item, and you can take it away later. When a key is rotated, it changes in one place. Chapter 14 covers the hosting platform's own secret store, which is where the running app reads its keys. The vault is where the people who run the app keep theirs.

Tell your agent

"Make a list of every secret this app uses and where each one is stored today: the hosting platform, local .env files, the vault, or nowhere written down. Mark any secret that exists only in the hosting platform or only on one laptop. Don't print any values."

The Trailing Newline Trap

Every secret so far has leaked by being copied too widely. The next problem is the opposite. The key is in the right place, nobody else has it, and the app still can't use it.

The author of this book once lost a whole working session to this. An app called an outside service for data that he knew existed, and the app kept showing nothing. There was no error on the screen and nothing alarming in the app's output. The search was right, and the data was there. The key had been set on the hosting platform, and the platform showed it was there. The session went into checking everything else first. The cause turned out to be one invisible character at the end of the key.

The trailing newline trap is what happens when a secret is stored with an invisible line break at its end. The service sees a key that doesn't match and rejects every request, while the stored value looks correct to anyone who reads it. A line break is a real character, written \n. When you type a value and press Enter, or when a command prints a value and ends the line, that character can come along.

It usually gets in through a command-line tool that reads the value from what you type, or from the output of another command fed into it, which is called piping. Hosting platforms and automated build services have tools like this, and Chapter 14 shows them. The command echo adds a line break to whatever it prints. The command printf prints only what you give it. Piping a key through echo stores the key plus a line break.

You can see the difference with od -c, a command that prints a value one character at a time. Here is a fake key, printed both ways.

$ echo 'sk_test_abc123' | od -c
0000000    s   k   _   t   e   s   t   _   a   b   c   1   2   3  \n
$ printf 'sk_test_abc123' | od -c
0000000    s   k   _   t   e   s   t   _   a   b   c   1   2   3

The first line ends with \n. On a settings page, both versions look identical.

The app showed "no data" and not an error because two problems were stacked together. The vendor received a key with a line break in it and answered 401 Unauthorized. Then the app's code treated any answer that wasn't a success as "no results found." Chapter 9 calls this a failure read as empty, and it's the same trap behind the no-false-all-clear rule from Chapter 1. Either fix alone would have saved the session. With a trimmed key, the call succeeds. With an adapter that reports a 401 as an error, the screen says the vendor rejected the key, and the cause is found in a minute.

Invisible on purpose

Sawyer encouraging If you've lost an afternoon to a bug like this, you weren't careless. The character can't be seen on any settings page. Now you know to look for it, and od -c will show it.

Whitespace Trimming

The fix for the line break is small. Whitespace trimming is removing spaces, tabs and line breaks from the start and end of a value before using it, so that invisible characters picked up in copying or pasting don't change what the app sends. Every language has a built-in way to do it. In JavaScript it's .trim().

Here is a small helper that reads an environment variable and trims it. Code that reads secrets through this helper can't be caught by the trailing newline.

// Read an environment variable, with stray spaces and line breaks removed.
function envStr(name: string, fallback = ""): string {
  return (process.env[name] ?? fallback).trim();
}

const imageKey = envStr("IMAGE_SEARCH_API_KEY");

Trimming the value when the code reads it is the defensive half. The careful half is to store it clean in the first place: use printf and not echo when a tool reads the value from a pipe, and check what was stored with od -c when you can. Do both. A teammate editing the value on a settings page next year won't know about the printf habit, and the trim will still catch the slip.

Trimming has limits. It removes invisible characters only from the two ends of a value. It does nothing about a key wrapped in quote marks, a key with one character missing, or a test key in production. Those need the check in the next section.

Diagram: Trailing Newline Inspector

Run the Trailing Newline Inspector MicroSim Fullscreen

Trailing Newline Inspector

Type: microsim sim-id: trailing-newline-inspector
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: demonstrate
Learning Objective: The learner will demonstrate, for six stored versions of one API key shown character by character, whether the vendor accepts the key as stored, after trimming, and whether a start-up schema check rejects it, getting at least 16 of 18 predictions right.

Prerequisites: API key, environment variable, 401 Unauthorized, trailing newline trap, whitespace trimming, env schema validation (the last is introduced in the next section; the sim's Starting State gives its two rules in one line).

Evidence of Mastery: For each of the six stored values, the learner commits three predictions before the reveal: the vendor's answer for the raw value (200 or 401), the vendor's answer after trimming (200 or 401), and whether the schema check stops the app at start-up (Yes or No). That is 18 predictions. A prediction is correct when it matches the answer columns in Content. Mastery is 16 of 18 correct.

Misconceptions: (1) If the value looks right on a settings page, it is right. (2) Trimming fixes every bad key. (3) A key that passes the start-up check is sure to work. (4) A 401 means the data isn't there.

Instructional Rationale: Applying the trim and schema rules to concrete stored values, character by character, makes the learner carry out the procedure rather than recall it. Committing all three predictions before the reveal separates evidence from watching.

Content:

The vendor accepts exactly one key: sk_test_abc123. Each stored value is shown as a row of character boxes. Invisible characters are drawn as labeled boxes: a space as ␠, a line break as \n, a carriage return as \r.

# Stored value (character boxes) How it got this way Raw After trim Schema stops start-up? Why
1 sk_test_abc123 Stored with printf 200 200 No Exact match.
2 sk_test_abc123\n Piped through echo 401 200 No Trim removes the line break; then it matches.
3 ␠sk_test_abc123 Pasted with a leading space 401 200 No Trim removes the space.
4 sk_test_abc123\r\n Copied from a file saved with Windows line endings 401 200 No Trim removes both \r and \n.
5 "sk_test_abc123" Pasted on a settings page with the quote marks 401 401 Yes Quote marks aren't whitespace, so trim leaves them. The value doesn't start with sk_, so the schema stops start-up.
6 sk_test_abc12 Last character cut off in copying 401 401 No It looks like a valid key, so the schema passes it. Only the vendor's 401 reveals it, and the app must report that as an error.

Provenance: The trailing newline story is the author's own, from research/seed-notes.md (story 4). The six values are illustrative and use a fake key. The echo and printf behavior is standard POSIX shell behavior.

Rules: Trim removes the characters space, tab, \n and \r from the start and end only. The vendor returns 200 if and only if the value it receives equals sk_test_abc123 exactly; otherwise 401. The schema check runs on the trimmed value and stops start-up if the value is empty, or doesn't start with sk_test_ or sk_live_, or contains any whitespace character. The schema doesn't call the vendor.

Learner Activity:

  1. The learner sees value 1 as a row of character boxes and three prediction toggles: Raw (200 or 401), After trim (200 or 401), Schema stops start-up (Yes or No).
  2. The learner sets all three toggles and presses Lock in.
  3. The sim animates the request: the boxes travel to a "Vendor" box, which shows 200 or 401. Then the trim step removes any edge boxes, and the request is sent again. Then the schema step shows pass or stop.
  4. Each prediction shows correct or incorrect, with the Why text.
  5. The learner moves to the next value, in the fixed order 1 to 6.
  6. After value 6, a summary shows the score out of 18 and one line: "Trim fixes 2, 3 and 4. The schema catches 5. Nothing at start-up catches 6, so the adapter has to report a 401 as an error."

Feedback: One attempt per value. Correct prediction: "Right. " plus the Why text. Incorrect: "Not quite. " plus the Why text. Answers are revealed after Lock in. A running count "n of 18" is shown.

Starting State: Value 1 with three unset toggles. A line above reads "The vendor accepts exactly sk_test_abc123. The start-up check trims the value, then requires it to start with sk_test_ or sk_live_ and contain no spaces or line breaks." The prompt reads "What will the vendor say?"

Chapter Anchors: echo adds a line break and printf doesn't. od -c shows \n at the end of the echo version. Trimming removes invisible characters only from the two ends. Trimming does nothing about quote marks, a missing character or a test key in production. A 401 read as "no results" is Chapter 9's failure read as empty.

Tell your agent

"Find every place this app reads an environment variable. Make each one go through a single helper that trims the value. Then find every adapter that calls an outside service and tell me what it does with a 401 or 403 answer. If any of them treat it as 'no results,' show me the change you'd make so it reports a clear error that names the key that was rejected, without printing its value, and wait for my OK."

An Env Schema That Checks at Start-Up

Trimming handles the invisible characters. A key in quote marks, a missing variable and a test key in production need a check that knows what each value should look like. Env schema validation is checking every environment variable against a written description of what it must be when the app starts, and stopping the app with a clear message if any value is missing or malformed. A schema is a written description of the shape of some data. Here the data is the app's configuration.

A schema changes when you find out. Without a schema, a missing payment key is discovered when the first member tries to upgrade, perhaps days after the deploy, and the error appears deep inside the payment code. With a schema, the server refuses to start, and the deploy fails with a line such as STRIPE_SECRET_KEY: must start with sk_live_ in production. Many hosting platforms keep the old version running when a new one fails to start, so the members never see the problem.

Fail loud, fail early

Sawyer giving a tip A server that refuses to start is a good outcome. It turns a quiet bug that members would find days later into a red deploy that you find in a minute.

Here is a schema for part of the dating-safety app, written with Zod, a popular TypeScript library for checking data. Before the code, here is what each piece means.

  • z.object describes the whole set of variables.
  • z.string().trim() says the value is text, with whitespace removed from both ends.
  • .min(1) says it can't be empty.
  • .regex(/^\S+$/) says it contains no spaces or line breaks.
  • z.coerce.number() turns the text "20" into the number 20.
  • The DATABASE_URL rule accepts an address starting with postgres:// or postgresql://. Hosts write it either way, and Railway uses the second.
import { z } from "zod";

// Text with no stray whitespace at the ends, no empty values,
// and no spaces or line breaks in the middle.
const key = z.string().trim().min(1).regex(/^\S+$/, "contains spaces or line breaks");

const EnvSchema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]),
  PORT: z.coerce.number().int().positive(),
  DATABASE_URL: key.regex(/^postgres(ql)?:\/\//, "must start with postgres:// or postgresql://"),
  STRIPE_SECRET_KEY: key.startsWith("sk_"),
  IMAGE_SEARCH_API_KEY: key,
  DAILY_SCAN_CAP: z.coerce.number().int().positive(),
});

// Check everything once, at start-up. A bad value stops the app here.
export const env = EnvSchema.parse(process.env);

// Live keys only in production, test keys everywhere else.
const isLive = env.STRIPE_SECRET_KEY.startsWith("sk_live_");
if (env.NODE_ENV === "production" && !isLive) {
  throw new Error("STRIPE_SECRET_KEY must start with sk_live_ in production");
}
if (env.NODE_ENV !== "production" && isLive) {
  throw new Error("STRIPE_SECRET_KEY must not be a live key outside production");
}

The rest of the app imports env from this file and never touches process.env again. That gives three benefits for one file. Every value is trimmed in one place. Every value is checked before the first request arrives. And the schema is a list of everything the app needs, which an agent can compare with .env.example to keep the two in step.

Two Bad Deploys

Here is what the schema does in two situations the dating-safety app could meet.

In the first, a helper sets up a test copy of the app, called staging, and pastes the payment key on the settings page with its quote marks, as "sk_test_abc123". Without the schema, the server starts, and every upgrade fails with an error from the payment company that mentions an invalid key. With the schema, the server refuses to start, and the deploy log names STRIPE_SECRET_KEY and says it must start with sk_. The helper sees the quote marks and removes them.

In the second, the builder copies the laptop's settings into production while moving hosts, and the payment key is the test key. Without the schema, the app runs normally, members click "Upgrade," the checkout page appears, and no real money ever arrives. That can go on for days, because nothing looks broken. With the schema, the server refuses to start with STRIPE_SECRET_KEY must start with sk_live_ in production.

A schema error message must name the variable and the rule it broke, and never print the value. A message that prints the bad key puts it in the deploy log, which is one of the leak paths. Zod's messages name the variable and the rule, which is what you want. Check any message you write yourself.

Tell your agent

"Add an env schema to this app using Zod. List every environment variable the code reads, trim every value, reject empty values and values with spaces or line breaks, check the prefix of each key where the vendor uses one, and fail at start-up if a live payment key is used outside production or a test key in production. Make the rest of the code read from the checked env object. Error messages must name the variable and never print its value. Before you deploy it, tell me which of the current production settings would fail the check, because a failing check stops the app from starting."

A Secret Scanner

Every habit so far depends on someone remembering it. The last one doesn't. A secret scanner is a tool that reads files, commits or a whole git history and flags any text that looks like a secret, using patterns for known key formats and checks for long random-looking strings. Gitleaks and TruffleHog are free scanners you can run yourself. GitHub runs its own scanning and can block a push that contains a known key format before the push lands.

A scanner can run in three places, and each one catches a different moment.

Where it runs What it catches When you find out
Once, over the whole git history Secrets already committed, including the ones from before you had a scanner Today, as a list of keys to rotate
On your laptop before each commit A key or a .env file about to be committed Before the commit exists, so nothing needs rotating
On every push, in the project's automatic checks Anything that got past the laptop, including commits made by an agent or a helper Within minutes, before the change is merged

Start with the first row. Run a scanner over the full history once, and you get the complete list of secrets that need rotating, including the ones nobody remembers committing. The second and third rows stop the next leak. The laptop check, called a pre-commit hook, is fast and catches the leak before it exists, but each person has to install it, and it can be skipped. The check on every push can't be skipped, which makes it the one to trust. Chapter 17 shows how to set up both, and why a check that runs on its own beats a habit that has to be remembered.

A scanner makes mistakes in both directions. It flags some strings that aren't secrets, such as a long test ID, and you mark those as allowed. It misses some secrets that don't match a pattern, such as a short password. It is still the cheapest protection in this chapter, because it works on commits made by agents, by helpers and by you on a tired evening, and it never forgets. A scanner on every push plus a pre-commit hook would have flagged all three of the dating-safety app's leaks at the moment they happened.

Tell your agent

"Run Gitleaks over this repository's full git history and give me the list of findings with values masked. Stop there so I can plan the rotations. When I say go, add a Gitleaks check that runs on every push and fails the build if it finds a secret, and a pre-commit hook that runs the same check locally. Add an allow-list file for any finding that isn't a real secret, with a comment on each entry saying why."

Back to the Flowerpot

The bakery owner never found out whether anyone used the old copies. Once the lock was changed, it stopped mattering. You can't recall a copy of a secret once it's made, so the answer to a leak is to make the copy useless. A written rotation runbook means changing the lock takes half an hour, like the locksmith's visit, and not a day of guessing.

Chapter 7 takes up the next wall: who is allowed through the door once they're inside, and how the server checks it on every request.

Key Takeaways

  • Keep secrets out of the code. The code reads environment variables by name, and .env is never committed.
  • Every copy of a key in git, chat, email, the browser bundle or a log is a leak you can't recall.
  • When a key leaks, rotate it: put a new key in place, then revoke the old one. If the key is being misused, revoke first.
  • Trim every value, and check them all with a schema at start-up.
  • Run a secret scanner on every push.

The lock is yours again

Sawyer celebrating You can now find every key your app uses, spot the paths they leak through, and rotate one without downtime. Good enough for now, and you know why. Next comes who gets through the door once they're inside.

See Annotated References