Sub topic 11
Keeping Secrets and Personal Data Out
This chapter assumes you can already share files, selections, and errors with an assistant, as covered in the earlier chapters. You should also be comfortable with environment variables and basic Git. The goal here is to decide, before you send anything, whether the context contains data that must not leave your machine, and to remove or replace that data without losing the information the assistant needs.
Why this matters
Everything you put into a request is transmitted to a service you do not control. Depending on the tool and its settings, that text may be logged, stored for some period, reviewed for abuse, or used to improve models. You cannot take it back after sending it. A leaked credential is a security incident even if the assistant's answer is perfect.
Context is also easy to over-share. Two features that make assistants useful also make leaks likely:
- Attaching a whole file includes every line, including the ones you did not look at.
- Pasting an error or log includes whatever the program printed, which often contains paths, hostnames, user names, and sometimes tokens.
The earlier chapters on relevance apply here too. Data that is not relevant to the task should not be sent, and sensitive data is almost never relevant.
What counts as sensitive
| Category | Examples | Typical place it hides |
|---|---|---|
| Credentials | API keys, passwords, database URLs with passwords, private keys, session cookies | `.env` files, config files, shell history, connection strings |
| Tokens | Bearer tokens, OAuth tokens, JWTs | HTTP logs, `Authorization` headers, stack traces |
| Personal data | Names, emails, phone numbers, addresses, ID numbers | Test fixtures, database dumps, log lines, sample CSVs |
| Business-confidential data | Customer lists, pricing, unreleased features, internal hostnames | Comments, config, query results |
| Infrastructure details | Internal IPs, account IDs, bucket names | Error messages, deployment files, cloud logs |
Personal data may also be regulated. If your data falls under rules such as GDPR or HIPAA, or under a contract with a customer, sending it to a third-party service may be prohibited no matter how careful you are. Check your organization's policy first. This chapter cannot tell you what your policy allows.
Where secrets leak into context
Whole-file attachments
A file that looks harmless can contain a secret in one line.
import os
import requests
API_KEY = "sk_live_51Hxxxxxxxxxxxxxxxxxxxx" # TODO: move to env
BASE_URL = "https://api.example.com"
def fetch_orders(customer_id):
response = requests.get(
f"{BASE_URL}/orders",
params={"customer": customer_id},
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10,
)
response.raise_for_status()
return response.json()If you want help with the error handling in fetch_orders, the key is irrelevant. Share only the function, which is a selection, or replace the key before attaching the file.
Error output and logs
A stack trace can include request URLs, header values, and file paths that contain your user name.
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.example.com/orders?customer=8841&token=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiamFuZUBjb3JwLmV4YW1wbGUifQ.Xk3...
File "/home/jane.doe/work/acme-billing/orders.py", line 9, in fetch_ordersThis single output contains a token in the query string, a customer ID, and a real user name in the path. The assistant needs none of these to explain a 401 response.
Hidden and indirect sources
Check these before you attach a directory or let an assistant read your workspace:
.env,.env.local,credentials,*.pem,*.key, andid_rsafiles.- Config files such as
settings.py,application.yml, orterraform.tfvarswith inline values. - Files that are in the editor but not in
.gitignore. - Shell history and terminal scrollback, if you copy a large block of terminal output.
- Test fixtures and database dumps that were exported from production.
- Git history. A secret deleted from the current file may still appear in an older commit that you paste in a diff.
Tools that read for you
If your assistant can read files or run commands by itself, your control changes. You are no longer choosing each line to send. The assistant can open any file its permissions allow.
For these tools:
- Open the tool's documentation and find which files it reads by default, and whether it respects an ignore file.
- Configure an ignore list for secrets, if the tool supports one.
- Prefer the tool's permission prompts over blanket approval. Read the path before you allow a read.
- Keep real secrets out of the working directory when you can, for example by loading them from a secrets manager or from outside the project folder.
The ignore mechanism and its file name differ between tools. Look up the exact name for yours instead of assuming it works like .gitignore.
Redacting without losing meaning
Deleting a value outright often makes the code or error unreadable. Replace it with a placeholder that keeps the shape of the original.
Good placeholders:
- Keep the format:
sk_live_REDACTED, not an empty string. - Keep distinct values distinct:
user_Aanduser_B, so the assistant can see that two IDs differ. - Keep structure: a JWT can become
<JWT>, while a URL can keep its path and lose its query string.
Here is the earlier error after redaction:
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.example.com/orders?customer=CUSTOMER_ID&token=<JWT>
File "/home/USER/work/project/orders.py", line 9, in fetch_ordersThe assistant still sees the exception type, the status code, the failing line, and the fact that a token is passed in the query string. That last detail is likely the useful clue, because tokens in URLs are often rejected or logged.
Replacing values in code
Prefer fixing the leak in the code itself. The assistant can then see the real structure, and your next attachment is safe by default.
import os
import requests
BASE_URL = "https://api.example.com"
def fetch_orders(customer_id):
api_key = os.environ["API_KEY"]
response = requests.get(
f"{BASE_URL}/orders",
params={"customer": customer_id},
headers={"Authorization": f"Bearer {api_key}"},
timeout=10,
)
response.raise_for_status()
return response.json()This version reads the key from an environment variable at call time. It raises KeyError if the variable is missing, which fails loudly instead of sending a bad request.
Scrubbing text with a script
For long logs, manual edits miss things. A small script applies the same rules every time. This one is a starting point, not a guarantee.
import re
import sys
PATTERNS = [
(re.compile(r"eyJ[\w-]+\.[\w-]+\.[\w-]*"), "<JWT>"),
(re.compile(r"(?i)(api[_-]?key|token|secret|password)=([^&\s]+)"), r"\1=<REDACTED>"),
(re.compile(r"(?i)bearer\s+[\w.\-]+"), "Bearer <REDACTED>"),
(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "<EMAIL>"),
(re.compile(r"/home/[^/\s]+"), "/home/USER"),
(re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "<AWS_KEY_ID>"),
]
def scrub(text: str) -> str:
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
if __name__ == "__main__":
sys.stdout.write(scrub(sys.stdin.read()))Run it as python scrub.py < error.log > error.clean.log, then read the output before sending it.
Patterns only catch formats you thought of. A password in a free-text message, a name in a sentence, or a custom token format will pass through. Always read the cleaned text yourself.
A pre-send checklist
Run this check on every request, and run it more carefully as the amount of attached material grows.
- Does any line contain a key, password, token, certificate, or connection string?
- Does any line contain a real person's name, email, phone number, or ID?
- Do paths, hostnames, or URLs reveal internal systems that you would not post publicly?
- Is the data needed for the task? If not, remove it even if it looks harmless.
- Is the data allowed to leave your environment under your organization's policy?
The following diagram shows the decision.
If you already sent a secret
Treat the secret as compromised. Deleting the chat message does not guarantee deletion everywhere.
- Revoke or rotate the credential at its source. This is the step that actually fixes the problem.
- Check the provider's logs for use of the credential since you sent it.
- Look in your assistant's settings for history and data retention options, and delete the conversation if possible.
- Tell your security contact if the data was personal or belonged to a customer. Some regulations set reporting deadlines.
- Add the file or pattern to your ignore list so it does not happen again.
Common errors
- Redacting the value but leaving the hint. A line such as
# password is the dog's name plus 2024is still a leak. - Trusting a file name.
config.example.ymlsometimes contains real values that someone copied in. - Pasting a diff. Added and removed lines both appear, so a secret you just removed is still in the diff.
- Sharing screenshots. Images of terminals or dashboards can contain tokens and are harder to scrub than text.
- Over-redacting. Replacing the whole error with
<ERROR>leaves the assistant nothing to diagnose. Redact values and keep structure. - Relying on the assistant to ignore it. Telling the assistant "don't store the key" does not stop transmission. Remove the value before sending.
Fitting it into your workflow
Sensitive-data checks work best as part of how you prepare context, not as a last step. Select the narrowest context that answers the question, since that also limits exposure. Add a secret scanner to your repository or commit hooks so leaks into code are caught early. When you reproduce a bug for the assistant, build a small example with fake data instead of attaching a production record. The assistant can usually diagnose the bug from the reproduction alone.
Exercise
You want help with a 500 error. Your log excerpt contains POST /login [email protected] password=Hunter2! session=abc123def456. The assistant only needs to know which request failed and with what status. Write the version of this line that you would send, and explain what you kept and what you removed.
Show answer
Send something like POST /login user=<EMAIL> password=<REDACTED> session=<REDACTED> with the 500 status and the stack trace. You keep the HTTP method, the path, and the parameter names, because they show the shape of the request. You remove the email, the password, and the session value, because none of them is needed to diagnose a server error. If the bug depends on the user (for example, one specific account), use stable placeholders such as user_A, so the assistant can still tell accounts apart. Separately, rotate that password and session if the log is from a real system and was shared in an unprotected place.
Exercise
You attached settings.py and later notice it contained a live database password on line 14. List the steps you take, in order.
Show answer
First, rotate the database password at the database, since that is what removes the risk. Second, check the database's access logs for unexpected connections since the time you sent the file. Third, delete the conversation or adjust retention settings if your tool allows it. Fourth, notify your security contact if your policy requires it. Fifth, change settings.py to read the password from an environment variable and add any secrets file to your ignore list, so future attachments are safe.