Sub topic 4
Keep secrets and private data out of prompts
This chapter assumes you can read a traceback and paste code and errors into an AI assistant. It also assumes you know what an environment variable is, can use git, and have already reproduced a failure. The earlier chapters on gathering context and reproducing failures cover that groundwork. Here you learn what to remove from that context before it leaves your machine.
Why a prompt is a data transfer
A prompt is not a private note to yourself. When you send it, the text travels to a service you do not control. Depending on the provider and your plan, it may be logged, retained for some period, reviewed for abuse, or used to improve models. Chat history may also be visible to teammates on a shared workspace. You can't reliably take a prompt back once you send it.
A debugging prompt carries more risk than most. Good debugging context means real code, real error output, and real configuration. Those are the places where secrets are most likely to appear.
The rule for this chapter is simple. Send the assistant the structure of the problem, not the private values inside it.
What counts as sensitive
Credentials are the obvious case, but they are not the only one.
| Category | Examples | Where it hides while debugging |
|---|---|---|
| Credentials | API keys, passwords, access tokens, private keys, session cookies | `.env` files, connection strings, request headers in logs |
| Personal data | Names, emails, phone numbers, addresses, health or payment details | Rows printed in a failing query, test fixtures copied from production |
| Internal infrastructure | Hostnames, IP addresses, internal URLs, account IDs | Tracebacks, connection errors, cloud resource names |
| Proprietary material | Unreleased business logic, licensed code, customer contracts | Whole files pasted "for context" |
| Identity of the machine | Usernames, home directory paths | File paths in stack frames, such as `/home/jsmith/...` |
Some of these carry legal or contractual obligations. Customer data, health data, and code under an NDA may be forbidden from leaving your organization at all. Check your employer's policy on approved assistants before you worry about regexes. If the policy says a class of data cannot go to an external tool, redaction does not change that.
Where secrets leak during debugging
Most leaks are accidents of copying too much. These are the usual sources:
- Connection errors. Many database and HTTP libraries include the full URL in the exception, such as
postgres://app:[email protected]:5432/orders. The password is inside the error message. - Environment dumps. Running
env,printenv, or printingos.environto "show the environment" exposes every variable, including unrelated ones. - Verbose logs. Debug-level logs often include request headers, so an
Authorization: Bearer ...line can sit in the middle of a log you paste. - Config and dotfiles.
.env,settings.py,config.yaml,~/.aws/credentials, and Terraform state files often hold secrets in plain text. - Failing test data. A fixture dumped from production can contain real customer rows.
- Editor and agent context. Some assistants read open tabs or the whole workspace on their own. You may never paste a secret, yet the tool sends it anyway. The chapter on letting the assistant run commands covers that case in more detail.
Pasting the full traceback is still the right move, as an earlier chapter explained. You just need a step between copying and sending.
A decision flow before you send
Redact with placeholders, not deletion
Deleting a line makes the context confusing. A placeholder keeps the structure the assistant needs and removes only the value.
Before:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "10.0.4.17", port 5432 failed: FATAL: password authentication failed for user "app"
DATABASE_URL=postgres://app:[email protected]:5432/ordersAfter:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "<DB_HOST>", port 5432 failed: FATAL: password authentication failed for user "<DB_USER>"
DATABASE_URL=postgres://<DB_USER>:<DB_PASSWORD>@<DB_HOST>:5432/ordersThe assistant can still see that this is a PostgreSQL authentication failure, that the URL has the right shape, and that the port is the default. It can't see the credentials.
Automate the first pass
Manual redaction misses things when you are tired or in a hurry. A small script can handle common patterns before you read the text yourself. The script below reads text from standard input and writes a redacted version to standard output.
import re
import sys
PATTERNS = [
# AWS access key IDs
(re.compile(r"AKIA[0-9A-Z]{16}"), "<AWS_ACCESS_KEY_ID>"),
# Bearer tokens in Authorization headers
(
re.compile(r"(?i)(authorization:\s*bearer\s+)[A-Za-z0-9._~+/=-]+"),
r"\1<TOKEN>",
),
# user:password@ inside URLs
(
re.compile(r"\b([a-z][a-z0-9+.-]*://)([^/\s:@]+):([^/\s@]+)@"),
r"\1<USER>:<PASSWORD>@",
),
# name = value pairs where the name looks secret
(
re.compile(
r"(?i)\b([\w-]*(?:api[_-]?key|secret|token|password|passwd)[\w-]*)"
r"(\s*[=:]\s*)(\"[^\"]*\"|'[^']*'|\S+)"
),
r"\1\2<REDACTED>",
),
# Email addresses
(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "<EMAIL>"),
# IPv4 addresses
(re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), "<IP>"),
]
def redact(text):
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
if __name__ == "__main__":
sys.stdout.write(redact(sys.stdin.read()))Save it as redact.py. Given this input:
psycopg2.OperationalError: connection to server at "10.0.4.17" failed
DATABASE_URL=postgres://app:[email protected]:5432/orders
Authorization: Bearer eyJhbGciOi.abc.def
api_key = "sk-live-12345"
contact: [email protected]Run python redact.py < error.log and you get:
psycopg2.OperationalError: connection to server at "<IP>" failed
DATABASE_URL=postgres://<USER>:<PASSWORD>@db.internal:5432/orders
Authorization: Bearer <TOKEN>
api_key = <REDACTED>
contact: <EMAIL>The order of the patterns matters. The URL pattern runs before the email pattern. Otherwise [email protected] would be read as an email address and the password would be partly exposed.
Reduce what you have to redact
The best defense is to include less in the first place.
- Send a minimal example. The earlier chapter on shrinking a failure applies here too. A twelve-line reproduction with invented data has almost nothing to leak. Replace real records with fake ones such as
"Alice Example"and[email protected]. - Send excerpts, not whole files. Include the failing function, its callers, and the traceback. You rarely need an entire config file.
- Keep secrets out of code. Read them from environment variables or a secrets manager, so the file you paste holds only a variable name like
os.environ["API_KEY"]. - Exclude secret files from the assistant. If your editor or agent tool supports an ignore file or a deny list for paths, add
.env, key files, and credential directories. Check your tool's documentation for the exact mechanism. - Scan before you commit or share. A quick search finds common mistakes:
grep -rEn "AKIA[0-9A-Z]{16}|BEGIN [A-Z ]*PRIVATE KEY" . --exclude-dir=.gitWhen the bug depends on a value's shape, describe the shape instead of the value. For example, write "a 36-character UUID" or "a JWT with three dot-separated parts". If a bug depends on the exact value, such as a specific malformed record, replace it with a fake value that triggers the same failure. That also gives you a better regression test later.
If a secret was already sent
Assume it is compromised, even if you delete the message. You can't confirm what was stored or who can read it.
- Revoke or rotate the credential at its source, such as the cloud console or API dashboard. Do this first.
- Check the provider's access logs for use you don't recognize.
- Replace the old value everywhere it was used, and confirm the application still starts.
- Tell whoever owns security for the project, if you work in a team. Many organizations have a defined incident process.
- If you also committed the secret to git, rotating is still required. Rewriting history does not undo exposure that already happened.
Putting it together in a prompt
Here is the debugging prompt from the earlier chapter, now with sensitive values replaced:
I am running Python 3.12 with SQLAlchemy 2.0 and PostgreSQL 16.
Expected: the app connects to the database on startup.
Actual: OperationalError, password authentication failed (output below).
Values are replaced with placeholders: <DB_HOST>, <DB_USER>, <DB_PASSWORD>.
<paste the redacted connection code and traceback>
What are the most likely causes? Explain your reasoning from the error first, then suggest the smallest check I can run.The prompt says outright that placeholders were used. That stops the assistant from "fixing" the placeholders as if they were bugs, for example by telling you that <DB_PASSWORD> is not a valid password.
Exercise
The traceback you want to paste contains requests.exceptions.HTTPError: 401 for url: https://api.example.com/v1/items?api_key=abc123xyz. What do you send, and what do you do beyond editing the text?
Show answer
Replace the key with a placeholder, giving https://api.example.com/v1/items?api_key=<API_KEY>. The 401 status and the URL shape are what the assistant needs, and the real key is not. Also check whether you logged or committed that URL anywhere. If the real key was ever sent to an assistant or stored in a shared log, rotate it. A key in a query string is also a design problem: secrets in URLs end up in logs, so move it to a request header read from an environment variable.
Exercise
Your redaction script turns [email protected] into <EMAIL> when the URL pattern is moved after the email pattern. Why does that happen, and why is it a problem?
Show answer
The email pattern matches any run of word characters followed by @ and a dotted domain, and [email protected] fits that shape. The result is that the password text is treated as an email's local part. Depending on the surrounding characters, part of the URL can be mangled or the password can be left partly visible. Running the URL pattern first removes the user:password@ section before the email pattern sees it. In general, put more specific patterns before general ones.