Sub topic 6
Redacting What You Paste and What Tools Echo Back
This chapter assumes you can use Git and a command line, have used an AI coding assistant or chat tool, and know what an environment variable is. Earlier chapters covered what counts as a secret and how to keep files out of AI context. Ignore files only protect files. They do nothing for text you copy by hand, and they do nothing for output a tool produces while it works. This chapter covers those two gaps.
Two directions of leakage
Secrets reach an AI tool in two ways.
- Outbound paste. You copy a stack trace, a log excerpt, a
curlcommand, or a config snippet into a prompt. Anything in that text goes to the provider. - Echo back. An agent or assistant runs a command such as
env,cat config.yaml, ordocker inspect. The command output becomes part of the conversation context. The secret travels to the provider even though you never typed it.
The second case is easy to miss. You approved "run the test suite", and the test runner printed a database URL with a password in it during a failed connection.
Where secrets hide in pasted text
Before you can redact, you need to know where to look. Common places:
- Stack traces and error messages. Connection errors often include the full connection string.
- HTTP debugging output.
curl -vand request logs showAuthorizationheaders and cookies. - Environment dumps.
env,printenv,docker inspect, and CI job logs list every variable. - Config files and infrastructure state. Kubernetes manifests, Terraform state, and
.npmrcfiles can hold tokens inline. - URLs. Credentials can appear as
https://user:token@host/pathor as query parameters such as?api_key=.... - Personal data. Customer emails, names, and IDs in logs are sensitive even when they are not credentials.
A best-effort redaction helper
A small script can replace well-known credential shapes before you paste. The helper below uses regular expressions (patterns that match text by shape) for three cases: AWS access key IDs, bearer tokens in HTTP headers, and password=, secret=, token=, or api_key= style assignments.
import re
PATTERNS = [
(re.compile(r"AKIA[0-9A-Z]{16}"), "[REDACTED_AWS_KEY_ID]"),
(re.compile(r"(?i)(authorization:\s*bearer\s+)[^\s]+"), r"\1[REDACTED]"),
(re.compile(r"(?i)((?:password|secret|token|api[_-]?key)\s*[=:]\s*)\S+"), r"\1[REDACTED]"),
]
def redact(text: str) -> str:
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
print(redact("password=hunter2 Authorization: Bearer abc123"))Running it prints:
password=[REDACTED] Authorization: Bearer [REDACTED]Each rule keeps the label and removes the value. The second and third rules use a capture group, written (...), and the replacement \1 puts that group back. The reader of the redacted text, and the AI, can still see that a password was present, which keeps the log useful for debugging.
What this helper misses
Treat it as a seatbelt, not a guarantee. It does not catch:
- Secrets with no recognizable prefix or label, such as a bare 40-character hex string on its own line.
- Credentials inside URLs, such as
postgres://app:s3cret@db:5432/prod. - Values split across lines, such as PEM private keys, which span many lines.
- Names, emails, and other personal data.
- Secrets that appear after a label the patterns do not know, for example
client_secret_value: .... The wordsecretfollowed by_valuebreaks the match because the pattern expects=or:right after the keyword.
You can extend the list, but each new pattern also risks false positives. A broad rule may blank out harmless text and make the log useless. Pick patterns for the credential types your team actually uses.
Using the helper from the command line
A filter is more useful when it sits in a pipe. Save the helper as redact.py and replace the final print line with a stdin loop:
import re
import sys
PATTERNS = [
(re.compile(r"AKIA[0-9A-Z]{16}"), "[REDACTED_AWS_KEY_ID]"),
(re.compile(r"(?i)(authorization:\s*bearer\s+)[^\s]+"), r"\1[REDACTED]"),
(re.compile(r"(?i)((?:password|secret|token|api[_-]?key)\s*[=:]\s*)\S+"), r"\1[REDACTED]"),
(re.compile(r"(?i)(\w+://[^:/\s]+:)[^@\s]+(@)"), r"\1[REDACTED]\2"),
]
def redact(text: str) -> str:
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
if __name__ == "__main__":
for line in sys.stdin:
sys.stdout.write(redact(line))The fourth pattern handles URL credentials. Now you can filter any output before pasting:
python redact.py < app.log > app.redacted.logRead app.redacted.log yourself before you paste it. A redaction tool narrows what you have to check. It does not replace checking.
Prefer reducing the output over cleaning it
Redaction is a cleanup step. A better habit is to produce less sensitive output in the first place.
- Select, don't dump. Run
grep ERROR app.log | tail -n 20instead of pasting the whole log. - List names, not values. Use
env | cut -d= -f1to show which variables are set without printing their contents. - Use dedicated checks.
git diff --statshows what changed without showing the content.aws sts get-caller-identityshows which identity is active without exposing keys. - Replace real values with fakes. When asking for help with a config shape, write
DB_PASSWORD=example-not-realyourself. - Minimize the reproduction. A small failing example rarely needs real credentials or real customer data.
# Names only: shows which variables exist, never their values
env | cut -d= -f1 | sortControlling what tools echo back
When an agent runs commands, you control the echo path through approvals and the commands you allow. A few practical rules:
- Do not auto-approve commands that print secrets.
env,printenv,cat .env,cat ~/.aws/credentials, anddocker inspectshould always need a manual decision, or be denied. - Check what a command prints before you approve it.
npm testis usually safe. A script you have not read may log its configuration at startup. - Prefer commands with narrow output. Ask the agent to run
git status --shortrather than a command that prints full configuration. - Keep secrets out of the shell environment where an agent runs. If the variable is not set in that session,
envcannot reveal it. Load credentials only into the process that needs them. - Review the transcript. After a session, scan what the agent displayed. If a secret appeared there, it was also sent to the provider, so treat it as exposed and follow the leak procedure in a later chapter.
Programs that mask their own output
Some tools hide secrets on their own. CI systems often mask registered secret values in job logs. Some CLIs show only the last four characters of a token. Do not rely on this. Masking usually matches exact values, so a transformed value, such as a Base64-encoded or URL-encoded copy of a secret, is not masked.
A short workflow
Before you paste anything into an AI tool:
- Ask whether the AI needs this text at all. Cut it to the smallest useful excerpt.
- Run the excerpt through your redaction filter.
- Read the result once, looking for URLs with credentials, long random strings, private keys, and personal data.
- Replace anything left with an obvious placeholder.
- If you find a real secret in text you already sent, do not just delete the message. Deleting it from the chat window does not remove it from provider logs. Treat the secret as leaked and rotate it.
Common errors
| Mistake | Why it fails | Better approach |
|---|---|---|
| Redacting only the password line | The same secret also appears in a URL or a header further down | Search the whole excerpt for the secret's value before pasting |
| Trusting a regex filter completely | Unlabeled or multi-line secrets pass through | Read the output, and prefer sending less text |
| Pasting `env` output "for context" | It lists every secret in the session | Print variable names only |
| Auto-approving all shell commands | One approved command can print a credential file | Require approval for commands that read config or credentials |
| Replacing a secret with a placeholder that looks real | The AI may treat it as live, or you may confuse it with a real value | Use clear markers such as `[REDACTED]` or `example-not-real` |
| Deleting a chat message after pasting a secret | The provider may already have stored the text | Rotate the credential |
Exercise
A teammate pastes this into an AI chat to debug a connection failure: OperationalError: could not connect to postgres://app:[email protected]:5432/orders. They then run the redaction helper from this chapter (the first version, with three patterns) and paste its output instead. Will the password be removed? What would you change, and what else should you do before pasting?
Show answer
No. The first version has no pattern for credentials inside a URL. The password|secret|token|api_key rule needs a keyword followed by = or :, and the text s3cret here sits after a colon inside a URL, with no such keyword before it. The password would pass through unchanged. Add a URL-credentials pattern, such as (?i)(\w+://[^:/\s]+:)[^@\s]+(@) replaced with \1[REDACTED]\2, as in the stdin version of the helper. Then read the output to confirm the password is gone, and consider trimming the excerpt to the error line only. If the original text was already sent, rotate the database password.
Exercise
An agent asks permission to run env | grep -i key to find out why an SDK cannot authenticate. Why might you decline, and what could you offer instead?
Show answer
The command prints the full values of every variable whose name contains "key", and the agent sends that output to the provider. Instead, run env | cut -d= -f1 | grep -i key yourself to list only the variable names, or check aws sts get-caller-identity to see which identity is active. Then tell the agent which variable names are set or missing.