Lesson · Security & Robustness Essentials
Secrets & Randomness
55 min readSecrets & Randomness
Secrets require stronger handling than ordinary configuration. Use cryptographically secure randomness, avoid source-code credentials, and prevent sensitive values from leaking through logs or error messages.
Learning goals
- Read configuration with
os.getenvand explain why every environment value arrives as a string (orNone), never as anintor abool. - Choose
secretsoverrandomfor tokens, passwords, and reset links, and say what makesrandompredictable. - Generate a URL-safe token with
secrets.token_urlsafeand explain why more random bytes make guessing harder. - Keep credentials out of source files and describe what to do when one was committed anyway.
- Name the channels a secret must never reach: logs, error messages, and version control.
Mental model
The chain is about custody: a secret enters from the environment or is generated by secrets, and every later step either protects the value or leaks it. The secrets module draws randomness from the operating system, which is what separates a real token from a value random produced. The last line is the one people forget: a secret that reached a log or a traceback has left your control even if no line of code prints it on purpose.
Mental model
read it top to bottom
configuration lives outside the code
↓ read it: os.getenv("API_KEY") returns str or None
secrets are generated, not invented: secrets.token_urlsafe(32)
↓ keep them out of every channel that persists
logs, error messages, source controlCore idea
The single idea behind this lesson is custody: every secret has a source and a lifetime, and both are your responsibility. Randomness must come from the operating system when the value protects something, configuration must come from outside the code, and any path that persists text (logs, tracebacks, commits) must never receive the value itself.
Environment variables
Environment variables cross the process boundary as strings. Convert and validate them immediately, and avoid treating their mere presence as proof of safe or well-formed configuration.
Secret handling
Secret handling is the set of habits that keep a credential's value out of places that persist: source files, logs, error messages, and version control. In practice that means reading secrets from the environment at startup, validating them once, and passing them to the code that needs them without printing or embedding them. When a secret does reach a persistent channel, the reliable fix is rotation, because deleting the line does not delete the value.
secrets
secrets uses an operating-system-backed source suitable for security-sensitive tokens and random choices. Do not replace it with random for authentication or reset links.
Avoiding credentials in source
Credentials in source are secrets typed directly into a .py file or a committed config, where they are copied into every clone and every backup of the repository history. The safe pattern keeps the credential in the environment, or in a file deliberately excluded from version control, and has the code read it at runtime with os.getenv. If a real credential was ever committed, treat it as compromised and rotate it: removing the line does not remove it from history.
Sensitive logging concerns
Sensitive logging concerns come from the fact that logs and error messages persist and travel: they are copied to disk, shipped to log aggregators, and read by people who never needed the secret. A token or key can leak even when no line prints it directly, for example through an exception message that embeds the rejected value. Log neutral facts about a secret (that it exists, its length, its source) and keep the value itself out of every message.
Walkthrough
os.getenv("API_KEY")reads the variable and returns a string, orNonewhen the name is unset. The example assigns that result without printing it, and a later use of aNonekey would fail far away from the line that caused the problem.secrets.token_urlsafe(32)asks the operating system for 32 random bytes and encodes them with URL-safe base64, so the token contains no+,/, or=characters that would need escaping inside a URL. Those 256 random bits are what make guessing hopeless; the printed character count is only a side effect.len(reset_token)prints 43 for 32 input bytes. The length is a neutral fact about the token, which is exactly the kind of detail that is safe to log.- The trailing comment states the rule the example cannot demonstrate by running: the app may use
api_keyandreset_token, but neither value may appear in logs, error messages, or a commit. Predict before running: whatos.getenvreturns when the variable is missing, and how many characterstoken_urlsafe(32)produces.
Experiments to try
- Run the example once with the
API_KEYvariable set in your shell and once with it unset; record the two valuesapi_keytakes and add a check that raises a clear error when it isNone. - Seed
randomwithrandom.seed(0), print[random.random() for _ in range(3)]twice, and confirm the lists repeat; then callsecrets.token_hex(4)twice and confirm that no seed call exists to reproduce it. - Trigger
int("sk_live_ABC123")and read theValueErrormessage: the rejected string, a secret in this scenario, is embedded in the exception text that a traceback would log. Then catch the error and print a replacement message that does not embed the value. - Generate
secrets.token_urlsafe(n)forn = 8, 16, 32and record the three lengths; decide which size you would use for a password-reset link and why the smallest one is uncomfortable.
Common mistakes
- Reaching for
randombecause the values look random:randomis seeded from a reproducible source and its sequence can be reconstructed, so a reset token built with it is guessable and offers no protection. - Committing a credential and planning to delete it later: the value survives in the repository history and in every clone, so the only reliable fix once it was pushed is to rotate it.
- Logging an ordinary variable that shares a line, a logger, or an error path with a secret: the leak happens in the shared channel, not in the secret code, so auditing only the "secret" module misses it.
- Treating
os.getenv("API_KEY")as either a value or an error: it returnsNonefor a missing variable and a raw string for a present one, so an unvalidated result fails later with an error that points at the wrong line.
Practice: Easy
- Run the worked example with
API_KEYset and unset; record the two valuesapi_keytakes, then addif api_key is None: raise SystemExit("API_KEY is not set")and rerun both cases. - Generate
secrets.token_urlsafe(n)forn = 8, 16, 32and record each length. State which size you would use for a password-reset link and one reason the 8-byte token is weaker. - Seed
randomwithrandom.seed(0)and print three values twice; confirm the repetition, then show that the same loop oversecrets.token_hex(4)cannot be made to repeat.
Practice: Medium
- Write
get_api_key()that readsAPI_KEYwithos.getenv, strips whitespace, rejects missing and empty values with distinctValueErrormessages, and returns the key; test the three cases. - Move a config literal such as
{"API_KEY": "...", "TIMEOUT": "30"}out of the source: read both values from the environment and convertTIMEOUTwithint()at startup, then explain why the timeout could stay in source while the key cannot. - Take an
except Exceptionhandler that prints both the exception and a token variable, rewrite it so the token never enters the message while the failure stays diagnosable, and trigger a real error to compare the two versions' output.
Practice: Hard
- Build a configuration module that reads
API_KEYandTOKEN_BYTESfrom the environment at import time, validates each with a specific error message, and exposesnew_token()returningsecrets.token_urlsafe(int(TOKEN_BYTES)); cover missing key, non-integer byte count, and zero bytes as failure tests plus one success path. - Run a leak audit on an example log excerpt and traceback you write yourself: mark every place a key or token could appear, rewrite each print or raise site to describe the value instead of echoing it, and note which leak a code reviewer would probably not catch.
- Demonstrate the disqualifying property of
randomwith evidence: generate tokens two ways across several runs, show which sequence is reproducible once its seed is known, and write the argument you would give a reviewer for why the reproducible one cannot protect a reset link.
Lesson checklist
- I can generate a security token with
secrets.token_urlsafeand explain whyrandomcannot substitute for it. - I can read configuration with
os.getenv, handle theNonecase immediately, and convert strings before using them. - I can keep credentials out of source files and state what has to happen if one was committed anyway.
- I can name the channels a secret must never reach and keep it out of log and error output while the failure stays diagnosable.
Remember
Randomness and credentials are custody problems: values that protect the system must come from the operating system (`secrets`) and from outside the code (`os.getenv`), and they must never reach a channel that persists text. The worked example shows the shape of safe handling: read the key, never print it, generate the token with `token_urlsafe`, and log only neutral facts such as the token's length.
Interview angles
What is the main purpose of **Environment variables**?+
Environment variables cross the process boundary as strings. Convert and validate them immediately, and avoid treating their mere presence as proof of safe or well-formed configuration.
What should you pay attention to when using **Secret handling**?+
Keep the value out of every channel that persists: source files, logs, error messages, and version control. Read secrets from the environment at startup, validate them once, pass them only to the code that needs them, and rotate a secret that ever reached a persistent channel.
How does **secrets** fit into this lesson?+
secrets uses an operating-system-backed source suitable for security-sensitive tokens and random choices. Do not replace it with random for authentication or reset links.
What makes `random` unsuitable for a password-reset token?+
random is seeded from a reproducible source, so its output sequence can be reconstructed and a determined attacker can predict the token. secrets asks the operating system for randomness instead, which is why it is the module for values that protect access.