Sub topic 11
Keep Secrets and Private Data Out of Prompts
This chapter assumes you can read Python, run commands in a terminal, and know what an environment variable is. You should also have used a chat-based or editor-integrated assistant. Earlier chapters showed that the prompt is the assistant's only view of your task. This chapter covers the other side of that fact: everything in the prompt leaves your machine.
A prompt is a disclosure
When you send a prompt, its text goes to a service you don't control. Depending on the provider, your plan, and your organization's settings, that text may be logged, kept in chat history, visible to teammates in a shared workspace, or retained for a set period. Policies differ between providers and between plans, so read the one that applies to you instead of assuming. The safe working assumption is that anything in a prompt can be seen by someone you did not intend.
Editor-integrated assistants add a second route. They can send open files, selected text, terminal output, and other repository context without you pasting anything. An .env file open in a tab may be part of the context for your next question.
What counts as sensitive
| Category | Examples | Safe substitute |
|---|---|---|
| Credentials | API keys, passwords, session cookies, private keys, tokens in headers | `<API_KEY>`, or the name of an environment variable |
| Connection details | Database URLs with passwords, internal hostnames, private IP addresses | `db.example.com`, `192.0.2.10` |
| Personal data | Names, emails, phone numbers, addresses, customer records | Invented records with the same shape |
| Business-confidential material | Proprietary algorithms, unreleased product code, contract terms | A reduced example that shows the problem but not the logic |
| Regulated data | Health, payment, or government ID data | Never paste. Use fully synthetic data. |
Some of this may be allowed by your employer's rules and some may not. If you are unsure, treat it as not allowed and ask.
Share the shape, not the value
The assistant needs structure, types, error messages, and expected behavior. It almost never needs the real values. To debug a refused database connection, it must know that the URL has a user, a password, a host, and a port. It does not need your actual password.
Here is a prompt that leaks, followed by a version that doesn't.
Leaky prompt:
My app fails with this error. Here is the config.
DATABASE_URL=postgres://app:[email protected]:5432/orders
Stripe key: sk_live_51Hxyz...
Customer [email protected] gets a 500 on checkout.
Safer prompt:
Task: find why my Python 3.11 app fails to connect to PostgreSQL 15.
Context: the URL has the form postgres://<USER>:<PASSWORD>@<HOST>:5432/orders.
The error is: connection refused on <HOST>:5432. The app runs in Docker; the database runs on the host machine.
Constraints: no new dependencies. Do not ask me to paste credentials.
Output format: a short list of likely causes, most likely first.The safer prompt is also a better prompt. It names versions, states the constraint, and removes noise.
Techniques
Use consistent placeholders
Replace each sensitive value with a descriptive label in angle brackets, such as <DB_PASSWORD> or <CUSTOMER_EMAIL>. If the same value appears twice and the relationship matters, give it the same label both times, or use numbered labels like <USER_1> and <USER_2>. The assistant can then still reason that two rows belong to the same person.
Use synthetic data that keeps the shape
When the bug depends on data, build fake records with the same structure and the same edge cases. Reserved example values are safe by design:
example.com,example.org, andexample.netare reserved domain names.192.0.2.0/24,198.51.100.0/24, and203.0.113.0/24are reserved for documentation, so they never point at a real host.
A record with an empty middle name, a very long surname, and a non-ASCII character exercises the same code paths as a real customer row.
Cut to a minimal reproducible example
Reduce the problem to the smallest snippet that still fails. A 15-line function exposes far less than a 900-line module, and the assistant answers it more precisely. This is the same habit as writing a good bug report, and it also tends to reveal the bug.
Make code read secrets from the environment
Code that never contains a secret is safe to paste. Load secrets at runtime and name them in the prompt without giving their values.
import os
def get_payment_key() -> str:
key = os.environ.get("PAYMENT_API_KEY")
if not key:
raise RuntimeError("PAYMENT_API_KEY is not set")
return keyIn a prompt you can then write "the key comes from the PAYMENT_API_KEY environment variable". When the assistant returns code, check that it keeps that pattern. Assistants sometimes inline a placeholder such as "sk-test-123" into the code. Replace it with an environment lookup before the code gets near a commit.
Redact logs and errors automatically
Logs are the most common accidental leak, because they mix timestamps, hostnames, tokens, and user data. A small script run before you paste reduces the risk. This one reads standard input and writes redacted text to standard output.
import re
import sys
PATTERNS = [
# Credentials inside URLs must run before the email pattern.
(re.compile(r"(\w+://)([^:/\s]+):([^@/\s]+)@"), r"\1<USER>:<PASSWORD>@"),
(re.compile(r"AKIA[0-9A-Z]{16}"), "<AWS_ACCESS_KEY_ID>"),
(re.compile(r"(?i)bearer\s+[a-z0-9._\-]+"), "Bearer <TOKEN>"),
(
re.compile(r"(?i)(password|passwd|secret|api[_-]?key|token)(\s*[=:]\s*)\S+"),
r"\1\2<REDACTED>",
),
(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "<EMAIL>"),
(re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), "<IP_ADDRESS>"),
]
def redact(text: str) -> str:
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 and run python redact.py < app.log. For this input:
2026-11-27 10:02:11 ERROR connect failed url=postgres://app:[email protected]:5432/orders
2026-11-27 10:02:12 WARN retry for [email protected] api_key=sk_live_51Hxyz
2026-11-27 10:02:13 INFO Authorization: Bearer eyJhbGciOi.abc.defthe output is:
2026-11-27 10:02:11 ERROR connect failed url=postgres://<USER>:<PASSWORD>@<IP_ADDRESS>:5432/orders
2026-11-27 10:02:12 WARN retry for <EMAIL> api_key=<REDACTED>
2026-11-27 10:02:13 INFO Authorization: Bearer <TOKEN>The order of the patterns matters. If the email pattern ran first, it would match [email protected]-style text inside the URL and leave the user name behind. Put the most specific patterns first.
Exclude files and scan for secrets
Prevent the leak at the source as well:
- Many assistants and editor integrations support an ignore file or an exclusion setting that keeps chosen paths out of the context they collect. The name and syntax vary by tool, so check its documentation. Exclude
.env, key files, and data exports. - Keep secrets out of version control with a
.gitignoreentry for env files. - Run a secret scanner such as gitleaks or detect-secrets as a pre-commit hook. It catches keys in code you are about to commit, and the same patterns are useful for checking text before you paste it.
Where redaction fails
Automated redaction is a safety net and does not replace reading what you send. Common gaps:
- Unknown formats. A regex catches patterns it knows. A token in a custom format passes through untouched.
- Over-redaction. Replacing every number or every identifier can remove the clue the assistant needs. Redact values, and keep the structure.
- Hidden places. Stack traces contain file paths with usernames. Git remotes can contain tokens (
https://<token>@github.com/...). HTTP dumps includeCookieandAuthorizationheaders. Notebook outputs and test fixtures often hold real rows. Screenshots show everything on screen. - Combinations. A job title, a city, and a date may identify one person even when no name is present. For personal data, prefer fully synthetic records over partial masking.
- Comments and commit messages. People paste passwords into comments "temporarily".
Read the final text once, top to bottom, before you send it. This takes seconds, and it is the check that catches what the script missed.
A short pre-send checklist
- Does the text contain any credential, token, key, or connection string with a password? Replace it with a placeholder.
- Does it contain real names, emails, phone numbers, or customer rows? Swap in synthetic data.
- Is any of the code proprietary beyond what the question needs? Reduce it to a minimal example.
- Do the files your editor assistant can see include
.envfiles, key files, or data exports? Exclude them. - Does your organization have a policy on which assistants and plans may receive which data? Follow it.
- Will the code that comes back read secrets from the environment, not from literals?
Exercise
A teammate pastes this into an assistant: requests.get("https://api.internal.acme.test/v2/users", headers={"Authorization": "Bearer eyJhbGciOi.abc.def"}), plus the error "403 Forbidden for user [email protected]". Rewrite the pasted text so it is safe to send and still lets the assistant diagnose the 403.
Show answer
Replace the token with a placeholder, use a reserved example domain for the host, and replace the email with a placeholder or synthetic value. For example: requests.get("https://api.example.com/v2/users", headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"}) with the error "403 Forbidden for user <USER_EMAIL>". The assistant can still reason about the endpoint, the Bearer scheme, and the 403 status. It can suggest causes such as missing scopes, an expired token, or a wrong audience. The real token should also be rotated if it was ever sent, because the original text already contained it.
Exercise
In the redact.py script, why must the URL-credentials pattern come before the email pattern? What would the output look like for postgres://app:[email protected]/orders if the order were reversed?
Show answer
The email pattern matches [email protected] as if it were an email address. With the email pattern first, the text becomes postgres://app:<EMAIL>/orders. The user name app stays in the output. The URL pattern then no longer sees an @ to match, so the result is partly redacted and structurally broken. Running the URL pattern first gives postgres://<USER>:<PASSWORD>@db.example.com/orders. Specific patterns should run before general ones.
Exercise
Name two sources of sensitive data that an editor-integrated assistant may send even though you never pasted them, and one control for each.
Show answer
One source is an open or indexed .env file, controlled by excluding it through the assistant's ignore or exclusion setting and keeping secrets out of the repository. Another source is terminal output or logs in the context, controlled by redacting logs before sharing them or keeping the terminal out of the context. Other valid answers are data exports in the workspace (exclude the directory) and notebooks with saved outputs (clear the outputs).