Skip to content

Module 08 · Lesson 8.2

Secrets and Configuration Hygiene

40 minUpdated 19 Nov 2026Part of Security Review and Hardening · Existing Project Engineering
On this page
  1. What you will learn
  2. What counts as a secret, and what is just configuration
  3. Worked scenario: finding the EDI token and the debug default
  4. The fix sequence: report, rotate, read from the environment, remove
  5. Catching secrets before they are committed
  6. Step-by-step workflow
  7. Using an AI assistant with secrets
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

A key left under the doormat works for anyone who knows where to look. A secret in code is worse. Every copy of the repository carries it, and Git remembers every old version. Deleting the line from today's file is like taking a photo out of the front page of an album while it stays on page three.

In this lesson you find the hard-coded EDI token and an unsafe setting in the fictional Tidewell Wholesale service. You fix them in the right order: report, replace, move, remove. You then add a check that stops the next secret before it is saved. All keys here are fake, and the outputs come from a scratch Git repository.

What you will learn

  • Search tracked files and Git history for secrets, and record how you searched.
  • Fix an exposed credential in the right order: report, rotate, read from the environment, remove, decide about history.
  • Change a production setting so that a missing value gives the safe result.
  • Add an automatic scan that stops secrets before they are committed.

Before you start

What counts as a secret, and what is just configuration

Not every setting is secret. A web address is not. A password is. The test is simple: could someone use this value to pretend to be us, or to open something that should stay closed?

Secret
A value that proves who you are or unlocks something: a password, an API token, a private key. It is like a key to the stockroom.
Configuration
Settings that change from place to place: a database address, a debug switch, an email server. They are like the notes that say which shelf holds what in each shop.
Environment variable
A named value that the system hands to a program when it starts. It is kept outside the code. Think of a sticky note on the machine, instead of a line written into the recipe.
Rotation
Replacing a secret with a new one and switching the old one off. It is like changing the locks after a key goes missing.
Git history
The record of every past version of every file. A secret that was ever committed is in the history, even after it is deleted from the latest file.
Fail closed
When something is missing or unclear, the system picks the safe choice. A turnstile that stays shut when its card reader breaks fails closed.

The Twelve-Factor guidance says to keep configuration in the environment, not in code. This works well because the same code can then run in testing and in production, with different values.

Worked scenario: finding the EDI token and the debug default

The review in A Focused Security Review listed two findings for this lesson. F2 is the EDI token in code. F4 is the debug default. The token was already reported for rotation, but you still search properly. There may be more than one.

Search the files you track today

Bash
git grep -nIiE "(api[_-]?key|secret|token|passwd|password)[A-Za-z_]*\s*[:=]\s*['\"][^'\" ]{8,}" -- . ":!*.lock"

Likely credential assignments in tracked files. This finds candidates, not everything.

Real output from the scratch repositoryCaptured from a real run
dispatch/importers.py:6:EDI_API_TOKEN = "tw_live_EXAMPLE0000000000"
scripts/seed.env.example:2:SMTP_PASSWORD="change-me-please"

Line 6 of dispatch/importers.py is the real finding. The second line, in scripts/seed.env.example, has an obvious placeholder. It is an example file, so it is fine. Write down both and the reason. Then run two more searches from the earlier lesson.

Bash
git grep -nI "BEGIN .*PRIVATE KEY"
git ls-files | grep -iE "\.env|credentials|\.pem$|\.p12$"

Private key blocks, and files that often carry secrets.

Real output of the two commands, one after the otherCaptured from a real run
scripts/seed.env.example

No private keys. The first command printed nothing. The second printed only the example file, which holds a placeholder. Your note says: 'searched with these three commands on this date, at this commit'. That is your method, and anyone can repeat it.

The fix sequence: report, rotate, read from the environment, remove

The order matters. Many people start by deleting the line. That is the last step, not the first. A token that was in the repository must be treated as exposed. Everyone who could read the repository, every copy of it, and every tool that saw the code may have it.

  1. Report it. Tell the owner of the secret, by role. Here it is the owner of the EDI partner relationship. Do not paste the real value into the report.
  2. They rotate it. The owner asks the partner for a new token. The new one goes into the place where the workers read their environment. Only then is the old one switched off, so imports never stop.
  3. Read it from the environment. Change the code so that it asks for the value when the program starts.
  4. Remove it from the code. Commit the change, as its own small, reviewable change.
  5. Decide about the history. Do you rewrite old commits? Think about it, with the team. See below.
  6. Add a scan. Make the next secret stop at commit time. See the last part of this lesson.

Here is the change for steps 3 and 4, as a real Git diff from the scratch repository.

Real output of git diff for the fix commitCaptured from a real run
diff --git a/dispatch/importers.py b/dispatch/importers.py
index bf885b7..6905681 100644
--- a/dispatch/importers.py
+++ b/dispatch/importers.py
@@ -1,9 +1,10 @@
+import os
 import requests
 from celery import shared_task
 
 from orders.services import create_order
 
-EDI_API_TOKEN = "tw_live_EXAMPLE0000000000"
+EDI_API_TOKEN = os.environ["EDI_API_TOKEN"]
 PARTNER_URL = "https://edi.example.com/api/orders"

os.environ["EDI_API_TOKEN"] has square brackets on purpose. If the variable is missing, Python stops with an error at start-up. The program fails closed. A version with a built-in fallback, such as os.environ.get("EDI_API_TOKEN", "test"), would hide the mistake until the partner refuses the request.

Here is a small, runnable version of the idea, with a test. It is a simplified version of the service's code, so you can run it without Django.

Pythonsettings_demo.py
def debug_before(environ):
    return environ.get("DJANGO_DEBUG", "true").lower() == "true"


def debug_after(environ):
    return environ.get("DJANGO_DEBUG", "false").lower() == "true"


def edi_headers(environ):
    return {"Authorization": "Bearer " + environ["EDI_API_TOKEN"]}

Two settings functions. The debug one has a before and an after.

What each part does

  • debug_before is the Tidewell line. If DJANGO_DEBUG is missing, it uses "true", so debug is on.
  • debug_after uses "false" as the fallback. Only an explicit true turns debug on.
  • edi_headers reads the token with square brackets. A missing variable raises KeyError.
Pythontest_settings_demo.py
import pytest

from settings_demo import debug_after, debug_before, edi_headers


def test_before_a_missing_variable_turns_debug_on():
    assert debug_before({}) is True


def test_after_a_missing_variable_leaves_debug_off():
    assert debug_after({}) is False


@pytest.mark.parametrize("value, expected", [("true", True), ("True", True), ("false", False), ("", False), ("yes", False)])
def test_after_only_an_explicit_true_turns_debug_on(value, expected):
    assert debug_after({"DJANGO_DEBUG": value}) is expected


def test_token_comes_from_the_environment():
    headers = edi_headers({"EDI_API_TOKEN": "not-a-real-token"})
    assert headers == {"Authorization": "Bearer not-a-real-token"}


def test_a_missing_token_stops_the_program():
    with pytest.raises(KeyError):
        edi_headers({})

Tests that pin the new behaviour.

Bash
python -m pytest -v --no-header

Run the tests in the folder that holds both files.

Real output (timings vary between runs)Captured from a real run
============================= test session starts =============================
collecting ... collected 9 items

test_settings_demo.py::test_before_a_missing_variable_turns_debug_on PASSED [ 11%]
test_settings_demo.py::test_after_a_missing_variable_leaves_debug_off PASSED [ 22%]
test_settings_demo.py::test_after_only_an_explicit_true_turns_debug_on[true-True] PASSED [ 33%]
test_settings_demo.py::test_after_only_an_explicit_true_turns_debug_on[True-True] PASSED [ 44%]
test_settings_demo.py::test_after_only_an_explicit_true_turns_debug_on[false-False] PASSED [ 55%]
test_settings_demo.py::test_after_only_an_explicit_true_turns_debug_on[-False] PASSED [ 66%]
test_settings_demo.py::test_after_only_an_explicit_true_turns_debug_on[yes-False] PASSED [ 77%]
test_settings_demo.py::test_token_comes_from_the_environment PASSED      [ 88%]
test_settings_demo.py::test_a_missing_token_stops_the_program PASSED     [100%]

============================== 9 passed in 0.02s ==============================

Should you rewrite the history?

After the fix, the token is gone from today's files, but not from the past. Ask Git to look for it.

Bash
git grep -n "tw_live_"
git log -S "tw_live_" --oneline --all
git grep -n "tw_live_" $(git rev-list --all)

Search today's files, then the commits that added or removed the text, then every commit.

Real output of the three commands, one after the otherCaptured from a real run
(no matches)
fa6c6e4 Read the EDI token from the environment
51f1218 Add EDI importer
fc424ab94e5be0b4e48ae1457b3e135586ff89b5:dispatch/importers.py:6:EDI_API_TOKEN = "tw_live_EXAMPLE0000000000"
2bb8890d22e0035a279423df44e53d474adf4811:dispatch/importers.py:6:EDI_API_TOKEN = "tw_live_EXAMPLE0000000000"
cf0d9582d9e4a84cfa35cc0521686df3f94e13d1:dispatch/importers.py:6:EDI_API_TOKEN = "tw_live_EXAMPLE0000000000"
51f1218378766dfef03d340e814f48fb8996d0e5:dispatch/importers.py:6:EDI_API_TOKEN = "tw_live_EXAMPLE0000000000"

The first command finds nothing in the latest files. The second, called a pickaxe search, lists the commit that added the token and the one that removed it. The third shows the token inside four old commits. Anyone who clones the repository can read it there.

You can remove it from the history with a tool such as git-filter-repo (opens in a new tab). But think first.

QuestionWhat to know
Does rewriting make the old token safe?No. Copies, forks, build logs and backups may still hold it. Only rotation makes it useless.
What does it cost?Every commit after the change gets a new ID. Everyone must re-clone or reset. Open branches and pull requests break.
When is it worth doing?When the secret is very sensitive and cannot be rotated, or the repository is about to become public. Coordinate with everyone first.
What if you skip it?That is common. If the token is rotated and the old one is dead, the old commits hold a key that opens nothing.
Rotation matters more than rewriting.

GitHub's guide, Removing sensitive data from a repository (opens in a new tab), explains the steps and the limits.

Fix F4: a missing setting must give the safe result

Debug mode is a Django setting. When it is on, an error shows a long page with the code, the stack trace and settings. Django tries to hide the values of settings whose names look secret, but it cannot know every name. That page helps a developer. On a public site it helps a stranger.

Real output of git diff for the settings fixCaptured from a real run
diff --git a/tidewell/settings/production.py b/tidewell/settings/production.py
index 9444657..0e3d14c 100644
--- a/tidewell/settings/production.py
+++ b/tidewell/settings/production.py
@@ -2,6 +2,6 @@ import os
 
 from .base import *  # noqa: F401,F403
 
-DEBUG = os.environ.get("DJANGO_DEBUG", "true").lower() == "true"
+DEBUG = os.environ.get("DJANGO_DEBUG", "false").lower() == "true"
 ALLOWED_HOSTS = ["portal.example.com"]
 EMAIL_HOST = os.environ["SMTP_HOST"]

Production should be safe when nobody sets anything. Only an explicit DJANGO_DEBUG=true turns it on. Local development can set that in its own file.

Check the secret key in the same pass. In the scratch repository, tidewell/settings/base.py:3 reads SECRET_KEY = os.environ["SECRET_KEY"], which is the right pattern.

Django uses this key to sign sessions and tokens. If yours is a plain string in the code, treat it like the EDI token: report it, replace it, and read it from the environment. Replacing it can sign users out, so plan the time. Django's deployment checklist (opens in a new tab) lists more settings to check.

Catching secrets before they are committed

A fix that relies on people remembering will fail one day. So add a check that runs by itself. The usual place is a pre-commit hook: a small program that Git runs just before a commit is saved. If it fails, the commit stops. The same check should also run in your build system, in case someone skips the hook.

Real scanners are better than anything you write in ten minutes. This teaching version is short so that you can see what such a tool does. It looks for three patterns and prints the file and line. It never prints the secret itself.

Pythonscripts/check_secrets.py
import re
import sys

PATTERNS = {
    "Tidewell EDI token": re.compile(r"tw_live_[A-Za-z0-9]{8,}"),
    "private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
    "quoted secret assignment": re.compile(
        r"""(?i)(api[_-]?key|secret|token|passw(or)?d)\w*\s*[:=]\s*['"][^'" ]{8,}['"]"""
    ),
}


def scan(name, text):
    hits = []
    for number, line in enumerate(text.splitlines(), start=1):
        for label, pattern in PATTERNS.items():
            if pattern.search(line):
                hits.append((name, number, label))
    return hits


def main(paths):
    found = []
    for path in paths:
        with open(path, encoding="utf-8", errors="ignore") as handle:
            found += scan(path, handle.read())
    for name, number, label in found:
        print(f"{name}:{number}: possible secret ({label})")
    return 1 if found else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A teaching version of a secret scan. Real tools know many more patterns.

What each part does

  • PATTERNS holds three searches: the Tidewell token shape, a private key header, and a quoted value assigned to a name such as token or password.
  • scan reads text line by line and notes each line that matches a pattern.
  • main scans every file named on the command line. It prints the file, the line number and the kind. It never prints the matched text.
  • The last line returns exit code 1 when something was found. Git hooks read that code: 0 means go on, anything else means stop.
Bash
git show HEAD~2:dispatch/importers.py > old_importers.py
python scripts/check_secrets.py old_importers.py
echo "exit code: $?"

First, the old version of the importer, from before the fix.

Real outputCaptured from a real run
old_importers.py:6: possible secret (Tidewell EDI token)
old_importers.py:6: possible secret (quoted secret assignment)
exit code: 1
Bash
python scripts/check_secrets.py dispatch/importers.py
echo "exit code: $?"
python scripts/check_secrets.py $(git ls-files)
echo "exit code: $?"

Now the fixed file, and then every tracked file.

Real output of the four commands, one after the otherCaptured from a real run
exit code: 0
scripts/seed.env.example:2: possible secret (quoted secret assignment)
exit code: 1

The fixed file is clean. The scan of all files flags the placeholder in the example file. That is a false alarm, and every scanner has some. Do not switch the scan off. Instead, tell it to skip that line, or change the placeholder to something that does not look like an assignment. Real tools have an 'allow list' for this.

YAML.pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: secret-scan
        name: Scan changed files for secrets
        entry: python scripts/check_secrets.py
        language: system

A configuration excerpt for the pre-commit tool. This lesson does not run it.

The pre-commit (opens in a new tab) tool passes the names of the changed files to the script. Keep local settings in a file that Git ignores, such as .env. The guide Managing API Keys Locally shows how.

Step-by-step workflow

  1. Step 1: Search files and history, and record how

    Run your searches on the current files. Then run a pickaxe search and a history search for each secret you find. Write down the commands, the date and the commit.

    What you should see: A list of candidates, each with file, line and the commands that found it.

  2. Step 2: Judge each candidate

    Is it a real secret, a placeholder or a test value? Never copy a real value into a note, a ticket or a prompt. Note only the file and line.

    What you should see: Each candidate marked real, placeholder or unsure.

  3. Step 3: Report real secrets to their owner

    Name the owner by role. Say where the secret is, how long it has been there, and who can read the repository. Ask for rotation.

    What you should see: A report sent, with the date.

  4. Step 4: Rotate without a gap

    The owner gets a new secret. Place it in the environment first. Switch the old one off second. Check that the service still works, and watch for failures that show someone else was using the old one.

    What you should see: The service works with the new secret, and the old one is dead.

  5. Step 5: Change the code and remove the secret

    Read the value from the environment, and fail loudly if it is missing. Make this its own small commit. Fix unsafe defaults in separate commits.

    What you should see: A diff of a few lines that a reviewer can check at a glance.

  6. Step 6: Decide about history, then add a scan

    Decide with the team whether to rewrite the history, and write down the reason. Then add a scan to the commit hook and to the build.

    What you should see: A decision note, and a scan that has failed once on a test secret.

Order of the fix
  1. Report

    To the secret's owner

  2. Rotate

    New in place, old off

  3. Environment

    Read, fail if missing

  4. Remove

    Small commit

  5. History

    Decide, with the team

  6. Scan

    Hook and build

Rotation comes before cleaning up the code.

Using an AI assistant with secrets

An assistant can help you plan a rotation, write a search pattern, and review a small diff. The rule is: the real secret never goes into the prompt. A secret in a prompt has left your control. Use a placeholder such as <REDACTED> and the file name.

  • Ask for a plan, not a fix. A good answer lists who does what and in which order. Check it against the sequence above.
  • Check its search patterns. An invented pattern can miss real keys. Test it on a made-up secret first.
  • Watch for 'fixes' that hide the problem. A common one is os.environ.get("EDI_API_TOKEN", "some-default"). It replaces a loud failure with a quiet one.
  • Do not let it paste new secrets. Generated examples sometimes contain real-looking keys. Use obvious placeholders.

Conclusion and your next step

You searched the files and the history, and you can now fix an exposed secret in the right order. You moved the token to the environment, made debug fail closed, and added a scan that runs before commits. The most important point: a secret that was in the repository is replaced, not just deleted.

Your next step: fix the next two findings. Continue with Input Validation and Injection to close the SQL injection hole and check quantities at the boundary.

For more, read Configuration and Secrets and the module overview Security Review and Hardening.

Reusable prompt

Secret exposure response plan

Gets a short, ordered response plan for a credential found in code, without sharing the credential.

I found a hard-coded API token in a Python file of a service. The company and all details are fictional. The real value is not included and must not be requested.

Facts:
- File and line: dispatch/importers.py, line 6
- It is a token for a partner's order API, used by a background worker
- The repository is private, with about 20 people who can read it
- It has been in the code since an early commit, so it is in the Git history
- The token owner is the person responsible for the partner relationship

Please give me:
1. An ordered response plan with who does each step. Put rotation before code cleanup.
2. How to avoid downtime when the token is replaced.
3. How to change the code so that a missing variable causes an error at start-up.
4. Whether I should rewrite the history, with the reasons for and against.
5. Anything you cannot judge from these facts.
Mark any guess as (unverified).
Show the reusable template

Replace each {{placeholder}} with your own details.

I found a hard-coded {{secret_type}} in {{file_and_line}} of {{system_description}}. The real value is not included and must not be requested.

Facts:
{{facts}}

Please give me:
1. An ordered response plan with who does each step. Put rotation before code cleanup.
2. How to avoid downtime when the secret is replaced.
3. How to change the code so that a missing variable causes an error at start-up.
4. Whether I should rewrite the history, with the reasons for and against.
5. Anything you cannot judge from these facts.
Mark any guess as (unverified).

Expected output and limitations

A numbered plan that starts with reporting and rotation, a way to swap tokens without downtime, a code change that fails when the variable is missing, a balanced view on rewriting history, and a short list of unknowns.

Sample responseIllustrative — your output will differ
Plan
1. Report to the owner of the partner relationship today. Do not include the token in the message.
2. Owner asks the partner for a new token.
3. Put the new token in the workers' environment. Keep the old one working until the new one is confirmed.
4. Deploy the code change (below), then confirm an import runs.
5. Ask the partner to disable the old token. Watch the logs for failures from other users of it.
6. Decide on history with the team (below).
7. Add a secret scan to the commit hook and the build.

Code change
EDI_API_TOKEN = os.environ["EDI_API_TOKEN"]   # raises KeyError if missing

History
- For: removes the token from clones made later.
- Against: breaks open branches and does not remove copies elsewhere.
- Once the old token is disabled, the history holds a dead key. Many teams stop here.

Cannot judge
- Who else has used the token.
- (unverified) Whether the partner can run two tokens at once.

Limitations to keep in mind

  • The assistant does not know your partner's process. Whether two tokens can work at once is a question for the owner.
  • It may suggest a fallback value in the code. Reject it.
  • It cannot search your history. Run the searches yourself.
  • A confident plan is not a checked plan. Walk through it with the secret's owner.

Common errors and how to fix them

Deleting the secret from the code and calling it fixed

Why it happens: The latest file is clean, so the problem seems gone.

Fix: Report it for rotation first. The old value stays in the history and in every clone.

Switching off the old secret before the new one is in place

Why it happens: The steps were done in the order they came to mind.

Fix: Put the new secret in the environment and check the service. Switch the old one off afterwards.

A fallback value for a missing secret or a risky setting

Why it happens: .get(name, default) felt friendlier than an error.

Fix: Use os.environ[name] for secrets so a missing value stops the program. Use a safe default, such as debug off, for switches.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Search for secrets in your own repository

In a repository you may search, look for secrets in tracked files and history, judge each hit, and write the fix sequence you would follow. Check the production settings for unsafe defaults, and try a scan on your files.

You will need

  • A repository you may search and its commit hash.
  • The three search commands from this lesson, and a pickaxe search for any real hit.
  • The teaching scan script, or a tool such as Gitleaks if your team approves it.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Search the settings files for DEBUG, SECRET_KEY, ALLOWED_HOSTS and for any .get( with a default.
  • If you find no secrets, say how you searched. 'None found' needs a method behind it.
  • Never run a secret scan on a repository you are not allowed to read.
Show a model answer

A strong note lists three or four commands with their dates, and a table of hits with file and line only. It marks one hit as real and one as a placeholder, and says why. For the real hit it names the owner by role and lists the steps in the right order: report, rotate with the new value in place first, read from the environment, remove, decide about history, add a scan. It also names a setting with an unsafe default and the safer one. A weak note says 'no secrets found' with no commands, or suggests deleting the line and moving on.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.You find a live token in code. The repository is private. What comes first?
    Show the answer and explanation

    Answer: B. The token has been exposed to everyone who could read the repository, so it must be replaced. Deleting the line leaves the old value in the history, and rewriting the history does not reach copies that already exist. Private repositories feel safe, but they only narrow who saw it.

  2. 2.The code is DEBUG = os.environ.get("DJANGO_DEBUG", "true").lower() == "true". The variable is missing in production. What happens?
    Show the answer and explanation

    Answer: B. The second argument of get is used when the variable is missing, so the fallback turns debug on. The tempting reading is that no setting means off. The fix is a fallback of 'false', so that only an explicit 'true' switches it on.

  3. 3.A secret scan flags SMTP_PASSWORD="change-me-please" in an example file. What should you do?
    Show the answer and explanation

    Answer: B. The scan found something that looks like a secret. A person must judge it. This one is a placeholder, so it needs an allow rule or a different form. Switching the scan off loses the protection for real secrets. Rotation is for real exposed values.

Frequently asked questions

What is an environment variable?

It is a named value that the system gives to a program when the program starts. It lives outside the code. On a server it is set in the deployment settings. On your laptop it can come from a local file that is not committed.

Is it safe to commit a .env file?

No, not if it holds real values. Commit an example file with placeholders, such as .env.example, and add the real .env to .gitignore. A committed secret is in the history for good.

Do I have to rewrite Git history after a secret leaks?

Not always. Rotation is what makes the old secret useless, so do it first. Rewriting is for special cases, such as a secret that cannot be rotated. It breaks other people's copies, so agree it with the team.

Which secret scanner should I use?

Use the one your team can run in its build, such as Gitleaks, TruffleHog or the scanning built into your hosting platform. The best tool is the one that runs on every change. Test it with a made-up secret to be sure.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.