The Analogy: A Darkroom Technician Handling Undeveloped Film
A darkroom technician spends the day handling rolls of film that have been exposed in a camera but not yet developed. Each roll carries a latent image -- a picture that is really there but not yet visible -- and it is ruinously sensitive to light. The technician works under a dim red safelight, never a white bulb, because the whole craft rests on one hard fact: a single flash of ordinary light wipes the image out, and nothing brings it back.
So the handling is built entirely around that fragility. The canister is cracked open only inside a light-tight changing bag; the film is wound onto the developing reel by touch, in the dark; it travels from container to tank and back without ever crossing a lit bench. The roll leaves its protective shell for the exact seconds it must be worked on and no longer. Nobody carries an open reel around "just in case" -- exposure is granted on a strict need basis, for the shortest possible time.
When the technician has to identify or annotate a roll, they do it without looking at the frames. They read the edge printing and the frame numbers along the border, or they log the roll by the job reference clipped to its bag -- never by holding a negative up to the light to see what is on it. The record that leaves the darkroom carries the reference, not the picture. That indirection is the whole point: you can track and route the film without ever exposing the image it holds.
The failure mode is impatience meeting irreversibility. A technician in a hurry lifts a strip toward a white bulb "just to check the roll is really on the reel," and in that instant the latent image fogs and the roll becomes scrap. What matters is that there is no undo: you cannot un-expose film, only reshoot. Secrets behave exactly the same way. The moment a token is echoed to a terminal that scrolls into a CI log, printed in a stack trace, or committed to git, it is exposed -- and deleting the line afterwards does not un-expose it. The value is now compromised and must be rotated. Redaction has to happen before the secret is ever emitted, never after.
Syntax or Core Structure
A secret should enter a script the way film enters the darkroom: through a controlled channel, handled for the shortest time, and never held up to the light. The minimal safe pattern reads the value from the environment, refuses to run if it is missing, and reports only facts about the secret -- never the secret itself.
#!/usr/bin/env bash
set -euo pipefail
# A secret arrives through the environment, never written into the script.
API_TOKEN="${API_TOKEN:-}"
if [ -z "$API_TOKEN" ]; then
echo "API_TOKEN is not set" >&2
exit 1
fi
echo "user: deployer"
echo "token length: ${#API_TOKEN}"
Output:
user: deployer
token length: 12
With a twelve-character token exported in the environment, the script confirms it loaded a secret and prints its length for a sanity check, but the value itself never reaches the terminal. That is the core discipline: the script proves the secret is present and usable without ever emitting it.
Technical Depth: Where Secrets Come From and How to Redact Them
Secrets should never be baked into a script or passed on the command line, where any user running ps can read them. The safe sources are the process environment, a file with tight permissions, or a dedicated secret store that injects the value at start-up. Once the value is in hand, the job is to reference it without exposing it -- and the table further down sums up the three redaction habits that keep it out of your output.
Reading Secrets Without Hard-Coding
The ${VAR:?message} form is the darkroom door: if the variable is unset or empty the script aborts at once with your message, so it can never run half-authenticated. For local development a .env file is common, sourced at start-up and never committed:
set -a
. ./.env
set +a
The set -a marks every variable that follows for export; sourcing the file loads the key-value pairs; set +a turns the marking off again. The .env file itself must be listed in .gitignore and created with chmod 600, so only its owner can read it, and a committed .env.example should carry placeholder keys instead of live values.
Masking and Redaction
| Technique | What it does | When to use it |
|---|---|---|
| Last-four mask | Shows only the final four characters, hides the rest | Log lines a human must still correlate |
| Full redaction | Replaces the entire value with a fixed marker | Anything machine-parsed, shared, or archived |
| Length only | Prints the character count and nothing else | Confirming a secret loaded, with zero exposure |
The two techniques below cover most needs: a mask that reveals a controlled tail, and a substitution that scrubs a secret out of a larger string before it is logged.
The mask helper shows only the last four characters, and treats an empty value specially so that a blank secret cannot quietly masquerade as a real one:
mask() {
local v="$1"
if [ -z "$v" ]; then
echo "(empty)"
else
echo "****${v: -4}"
fi
}
mask "sometoken"
mask ""
Output:
****oken
(empty)
Redacting a whole line uses pattern substitution: every occurrence of the secret in a string is swapped for a marker before the string is ever printed. Note the space in ${v: -4} -- without it, ${v:-4} means something entirely different (a default value), which is a classic source of leaks.
token="s3cr3t"
line="connecting with token=s3cr3t to api"
echo "${line//$token/***REDACTED***}"
Output:
connecting with token=***REDACTED*** to api
File Permissions and the Blast Radius
When a secret does live in a file -- a .env, a service-account key, a .netrc -- the file's permissions are the only thing standing between it and every other account on the host. Create such files with chmod 600 so only the owner can read them, and set a restrictive umask 077 at the top of any script that writes secret material to disk, so that even a temporary file made with mktemp is born unreadable to group and world. A secret written to a world-readable temp file has already leaked to every user who can run ls -l /tmp, whether or not anyone bothered to look; on a shared build host that is a routine exposure, not a hypothetical one.
The wider habit is to think in terms of blast radius: every place a secret can be read from is a place it can leak. The environment is inherited by every child process, so a token exported for one curl call is equally visible to a crash handler that dumps /proc/self/environ, a misbehaving dependency, or a shell that logs its own environment on exit. A file is readable by anyone the permissions allow and by any backup that sweeps the directory. Reducing blast radius means granting the narrowest access for the shortest time -- unset a variable the moment the call that needed it returns, prefer a local to an export, and never widen a secret's reach for convenience. Like the darkroom technician who lets the film out of its canister for exactly the seconds it must be worked and no longer, you keep the window of exposure as small as the task allows, because everything that can see the secret is something that can spill it.
Real World Example: A Deploy Script That Never Leaks Its Token
A deployment script is the classic place a secret leaks. It receives a token, uses it to authenticate an API call, and -- if written carelessly -- prints the full request URL, token and all, straight into the CI log where it lives forever. The script below does the same job while treating the token as undeveloped film: it refuses to start without the token, logs only a masked form, reports the length as a sanity check, and scrubs the value out of the request URL before printing it.
#!/usr/bin/env bash
set -euo pipefail
: "${DEPLOY_TOKEN:?DEPLOY_TOKEN must be set}"
masked="****${DEPLOY_TOKEN: -4}"
echo "loaded token (masked): $masked"
echo "token length: ${#DEPLOY_TOKEN}"
url="https://api.example.com/deploy?key=$DEPLOY_TOKEN"
safe_url="${url//$DEPLOY_TOKEN/****}"
echo "request: $safe_url"
echo "deploy accepted"
With a twelve-character token ending in wxyz exported as DEPLOY_TOKEN, the script prints the same four safe lines on every run:
Output:
loaded token (masked): ****wxyz
token length: 12
request: https://api.example.com/deploy?key=****
deploy accepted
The script front-loads its safety. The : command combined with ${DEPLOY_TOKEN:?...} aborts immediately with a message if the token is unset or empty, so the script never runs half-authenticated. It then derives a masked form showing only the last four characters, reports the length for a sanity check, and builds the request URL -- but before printing that URL it replaces every occurrence of the token with ****. Every line that reaches the log is safe by construction.
The headline flaw is that none of this survives trace mode. Run the script with bash -x deploy.sh -- exactly what a frustrated operator does when a deploy fails -- and bash prints every expansion as it happens, including the line where url is assigned the real token in full, long before the redaction runs. The in-script masking protects the script's own output but is powerless against xtrace, which sees the raw values. A secret that can be printed by set -x must be treated as exposed the moment anyone debugs the script.
Three narrower gaps remain even without tracing. The last-four mask still discloses four real characters and ${#DEPLOY_TOKEN} discloses the exact length, both of which shrink the space an attacker must search. The URL scrub uses the token as the search pattern in ${url//...}, which is glob matching rather than a literal compare -- a token containing * would over-match and mangle the URL, while a token that has already been percent-encoded elsewhere would not be found and so would not be redacted at all. And the substitution only cleans this one string: a stack trace, a mid-pipe abort, or a child process such as curl -v would each leak the token untouched. Redaction is a discipline applied at every exit, not a single call.
Common Mistakes
- Hard-coding a secret as a default value. Writing
API_TOKEN="${API_TOKEN:-supersecret}"bakes the fallback into the script and into git history forever. Use${API_TOKEN:?message}to fail loudly when the value is missing, never a real secret as the default.
- Passing secrets on the command line. A call like
myscript --token abcd1234wxyzis visible to every user throughps auxwwand lands in shell history. Pass secrets through the environment or a file instead, never as an argument.
- Committing the
.envfile. A.envholding live credentials that is not in.gitignoregets pushed on the first commit and exposed to everyone with repo access. Add it to.gitignorebefore you create it, and commit only a.env.examplewith placeholder values.
- Echoing the secret to debug. Adding
echo "token is $API_TOKEN"while chasing a bug writes the value to the terminal, the CI log, and anyone watching. Print a masked form or the length only; treat the value like undeveloped film.
- Leaving
set -xon in production. Trace mode prints every expansion, including raw secret values, straight into the log. Enable xtrace only around a specific block that touches no secret, and turn it off again withset +x.
- Redacting after logging instead of before. Scrubbing a log file afterwards assumes the secret only reached that one file -- but it was already shipped to the aggregator, the terminal scrollback, and any open
tail -f. Redact before the value is emitted, at every print site.
- Masking too little of the value. Showing the last eight characters of a twelve-character token leaves only four unknown. Reveal at most the last four, and only when a human genuinely needs to correlate; machine logs should get full redaction.
- Trusting substitution with a pattern-bearing token.
${line//$token/****}treats the token as a glob pattern, so a value containing*or?over-matches and a value encoded differently is not matched at all. Use a redaction step you have tested against your real token format.
- Forgetting that child processes inherit the environment. A secret exported for your script is visible to every command it runs, including ones that dump their own environment or crash with a full trace. Unset secrets you no longer need, and avoid
exportwhen a plain variable will do.
Best Practices
- Source secrets from the environment or a secret store, never the script. Read
${VAR:?}at start-up so a missing secret aborts immediately, and keep the value out of the code and out of git history.
- Keep
.envfiles out of version control. List them in.gitignore, create them withchmod 600, and commit only a.env.exampleof placeholder keys so teammates know what to set.
- Redact before you emit, at every print site. Build a masked string first and log that; never print the raw value and plan to clean it up later, because later is after it has already leaked.
- Reveal as little as possible. Prefer full redaction to a partial mask; when a human must correlate, show at most the last four characters and never the length of a short secret.
- Never pass secrets as command-line arguments. They appear in
psand in shell history. Use the environment, a file with tight permissions, or standard input instead.
- Keep xtrace away from secrets. Do not ship scripts with
set -xenabled, and when debugging, turn it on only around blocks that touch no secret, thenset +ximmediately after.
- Rotate on any suspected exposure. Treat a logged, printed, or committed secret as compromised even after you delete it -- exposure is irreversible, so rotate the credential rather than hoping nobody saw it.
- Scope and unset secrets. Avoid
exportwhen a local variable suffices, and unset secret variables once the call that needed them returns, so child processes and crash dumps cannot pick them up.
Practice Exercises
- Build a masking helper. Write a
maskfunction that prints(empty)for a blank value and****followed by the last four characters otherwise. Test it with a full token, a four-character token, and an empty string, and confirm no full value is ever printed.
- Make a secret mandatory. Take a script that reads
${TOKEN:-}and change it to${TOKEN:?TOKEN is required}. Show that running it with the variable unset aborts immediately with the message, and that setting it lets the script proceed.
- Redact a log line, then defeat it. Write a script that builds a request URL containing a token and prints a version with every occurrence of the token replaced by
****. Then run the script underbash -xand observe the raw token leaking in the trace; explain in a comment why the in-script redaction did not help.
- Audit a script for leaks. Take an existing script and find every place a secret variable is printed, exported, or interpolated into a string that gets logged. List each site and state whether it needs masking, full redaction, or removal.