Sub topic 3
Keep Secrets and Sensitive Code Out of the Prompt
Prerequisites
This chapter assumes you can read Python and shell commands. It also assumes you have used a chat or editor assistant, and that you know what an environment variable and a configuration file are. It builds on the previous chapter, where you chose what context to share. Here you decide what to leave out.
Why this matters
When you paste code into an assistant, you send text to a service you don't control. Depending on the product, that text may be logged, kept for some period, reviewed by people, or used to improve models. The terms differ between products and between personal and business plans. You cannot tell from the chat window which terms apply to you.
Pasting a secret is hard to undo. If a key reaches a third party, you can't take it back. You can only rotate it, which means issuing a new key and revoking the old one.
The running example in this tutorial, fib with @lru_cache, contains nothing sensitive. Code from a real data-processing project often does. A module that looks harmless can hold a connection string on line 12 and a customer name in a test fixture on line 80.
What counts as sensitive
Secrets are the obvious case, but they are not the only one.
| Category | Examples | Why it matters |
|---|---|---|
| Credentials | API keys, passwords, OAuth tokens, private keys, session cookies | Anyone holding them can act as you or your service |
| Connection details | Database URLs with embedded passwords, internal hostnames, IP addresses | They map your infrastructure and often include credentials |
| Personal data | Names, emails, phone numbers, customer IDs in fixtures or logs | Sharing it may violate privacy law or your contracts |
| Proprietary logic | Pricing algorithms, fraud rules, unreleased features | It may be a trade secret or covered by an employer policy |
| Third-party code under license | Vendor SDK sources, code under NDA | Your agreement may forbid sharing it |
The first three categories can usually be fixed by editing the text. The last two cannot. You need a policy decision, not a regex.
Decide whether you may share it at all
Before you edit anything, check the rules that apply to you. Many employers approve specific assistants and forbid others. Some approve an assistant only for non-production code. Some customer contracts forbid sending any of their data to outside services.
If you are unsure, ask. A short message to a security or team lead costs less than an incident review.
Redact before you paste
Redaction means replacing sensitive values with neutral placeholders. The goal is to keep the structure of the code, because structure is what the assistant needs to explain it.
Replace values, keep structure
Compare these two versions of a configuration snippet.
# Original
DB_URL = "postgres://etl_user:[email protected]:5432/billing"
API_KEY = "sk-live-9f8e7d6c5b4a"# Safe to share
DB_URL = "postgres://<USER>:<PASSWORD>@<HOST>:5432/<DATABASE>"
API_KEY = "<API_KEY>"The assistant can still tell that the code builds a PostgreSQL URL and that the key is a string. It doesn't need the real values to explain what happens next.
Use consistent placeholders. If the same customer ID appears in three places, use <CUSTOMER_ID_1> each time. Consistent names let the assistant follow how a value flows through the code.
A better habit is to avoid secrets in code at all. If the code reads os.environ["API_KEY"], you can paste it as is, because the value lives elsewhere. Share the code that reads the environment, never the .env file.
A small redaction script
Manual editing misses things, especially in long files. The script below applies common patterns and prints the result. Save it as redact.py.
import re
import sys
PATTERNS = [
# AWS access key IDs always start with AKIA followed by 16 characters
(re.compile(r"AKIA[0-9A-Z]{16}"), "<AWS_ACCESS_KEY_ID>"),
# name = value or name: value, where the name suggests a secret
(
re.compile(
r"(?i)\b([\w-]*(?:password|passwd|secret|token|api[_-]?key)[\w-]*)"
r"(\s*[:=]\s*)"
r"""(?:'[^'\n]*'|"[^"\n]*"|[^\s'"]+)"""
),
r"\1\2<REDACTED>",
),
(re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/-]+=*"), "Bearer <TOKEN>"),
(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "<EMAIL>"),
(re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), "<IP_ADDRESS>"),
]
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()))Run it on a file and read the output before you paste it anywhere.
python redact.py < settings.pyWith this input:
DB_PASSWORD=hunter2
api_key = "sk-live-abc123"
host = "10.0.4.17"
owner = "[email protected]"
key_id = AKIAIOSFODNN7EXAMPLEthe script prints:
DB_PASSWORD=<REDACTED>
api_key = <REDACTED>
host = "<IP_ADDRESS>"
owner = "<EMAIL>"
key_id = <AWS_ACCESS_KEY_ID>This script is a safety net, not a guarantee. It has known gaps:
- It misses secrets with unusual names, such as
x = "a8f3...". - It misses multi-line values such as PEM private keys.
- It misses secrets inside URLs, like the password in a database URL.
- It produces false positives.
max_tokens = 100is redacted because the name contains "token", and a version string like1.2.3.4is treated as an IP address.
Always read the redacted text yourself. Treat the script as a second pair of eyes.
Sensitive code, not just secrets
Redaction handles values. Proprietary logic needs a different approach: share less, or share a stand-in.
Three techniques work well:
- Isolate the confusing part. If you don't understand a decorator, paste only the function that uses it. You don't need the whole module. This also improves the answer, as the previous chapter explained.
- Rewrite with generic names. Rename
compute_enterprise_discounttocompute_valueand replace business constants with plain numbers. Check that the code still shows the same pattern. - Reproduce the question in a toy example. If you don't understand how the project's caching works, ask about
fibwith@lru_cacheinstead. You learn the concept, then apply it to the real code yourself.
The third technique works best when the confusion is about a language feature or library. It works poorly when the confusion is about your project's own design. In that case the assistant needs real context, and your options are an approved internal tool or reading the code with a colleague.
Tool-based assistants read more than you paste
A chat window sends only what you type. Terminal and editor assistants can read files, search the repository, and run commands. They may send file contents, open tabs, or command output to the service without you pasting anything.
Before you use one on a real project, check these points:
- Which files can it read? Look for settings that exclude paths. Many tools support an ignore file or a deny list. Add
.env, key files, and credentials directories. - Does it include open files automatically? An editor assistant may attach the file you are viewing. If that file is
.env, its contents go along with your question. - Can it run commands? Command output such as
envorcat config.ymlbecomes part of the context. Approve commands one at a time when you work with sensitive projects. - What does it keep? Find the data retention and training settings for your account type, and set them deliberately.
If a secret leaks anyway
Mistakes happen. If a real credential went into a prompt, act in this order:
- Rotate it. Issue a new key and revoke the old one. Do this first. Deleting the chat does not guarantee the text is gone from logs.
- Check for use. Look at access logs for the old credential, covering the time since you pasted it.
- Report it. Tell your security contact, even if you think the risk is small. They may have a process, and a timely report matters more than a clean record.
- Fix the cause. Find out how the secret got into the text you copied. It might have been a hardcoded value that belongs in an environment variable.
Do not spend time debating whether the assistant provider would really misuse the key. Rotation is cheap and certain. Arguing about probabilities is neither.
A prompt template with placeholders
This template combines the habits from this chapter with the prompt structure from the spine's example. Placeholders are marked with angle brackets.
I'm reading a Python utility in a data-processing project and I don't know <the thing>.
Explain what this function does and why <the thing> is there. Note that I replaced credentials, hostnames, and customer data with placeholders such as <PASSWORD> and <HOST>; treat them as ordinary strings.
<code>
<redacted snippet here>
</code>Telling the assistant that placeholders are intentional prevents a common confusion. Otherwise it may spend its answer asking what <HOST> means or flag it as a bug.
Common errors
- Pasting a whole file "for context." You send ten secrets to explain one line. Paste the smallest snippet that shows the behavior.
- Redacting after the fact. Some people edit the text only after sending a draft. Redact first, then paste.
- Sharing stack traces and logs unchecked. Tracebacks often include file paths with usernames, request URLs with tokens in query strings, and customer data in error messages.
- Trusting a pattern list. A script that catches
AKIA...keys will not catch a secret it doesn't recognize. - Assuming a "private" mode is private. Product settings change and differ per plan. Read the actual terms for your account.
Exercises
Exercise
You want to understand an unfamiliar decorator in a 400-line module that also contains a database URL with a password. Name two ways to get a useful explanation without sending the password.
Show answer
First, paste only the decorated function and its decorator, not the whole module, so the URL never leaves your machine. Second, replace the password (and ideally the host) with placeholders such as <PASSWORD> and <HOST> and tell the assistant they are placeholders. A third valid option is to reproduce the decorator in a toy example, as with fib and @lru_cache.
Exercise
Why does the redaction script turn max_tokens = 100 into max_tokens = <REDACTED>, and what should you do about it when you share code?
Show answer
The assignment pattern matches any name containing "token", and max_tokens contains it. This is a false positive. Because the script is only a safety net, you should read its output and restore harmless values like 100 by hand if the assistant needs them to explain the code.
Exercise
You realize you pasted a live API key into an assistant an hour ago. What is the first thing you do, and why not delete the conversation instead?
Show answer
Rotate the key: create a new one and revoke the old one. Deleting the conversation does not guarantee the text is removed from provider logs or other copies, while rotation makes the leaked key useless.