Sub topic 9
Redact Secrets and Keep Recordings Reviewable
This chapter assumes you can write pytest tests, read Python classes, and have used an LLM API. It also assumes you know how a recording replays saved replies, which the previous chapters covered. Here you will keep secrets out of recordings and keep the files small enough for a reviewer to read.
Why recordings are a risk
A recording is a file you commit to version control. It holds a copy of real traffic, so it can hold things you never meant to share:
- API keys in
authorizationorx-api-keyheaders. - Customer text in prompts, such as names, emails, or invoice details.
- Account identifiers in response headers, such as organization or request IDs.
Once a secret is committed, it stays in the Git history even if you delete the file later. You would have to rotate the key. Redact before you save, not after.
Redact before writing to disk
Redaction should happen at the moment of recording. If the raw data is never written, it cannot leak.
The RecordingClient from the earlier chapter stores only the model's text reply, keyed by a hash of the prompt. It never stores headers, so API keys cannot end up in it. Prompts are the remaining risk, because they are hashed but your reply text may still echo private data.
Vcrpy records full HTTP exchanges, so headers are a real concern there. Use filter_headers to remove them, and filter_post_data_parameters or a before_record_request hook for body content.
import re
import vcr
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
def scrub_request(request):
if request.body:
text = request.body.decode("utf-8") if isinstance(request.body, bytes) else request.body
request.body = EMAIL.sub("[email protected]", text)
return request
def scrub_response(response):
for name in ("openai-organization", "set-cookie", "request-id"):
response["headers"].pop(name, None)
response["headers"].pop(name.title(), None)
return response
my_vcr = vcr.VCR(
cassette_library_dir="tests/cassettes",
record_mode="none",
filter_headers=["authorization", "x-api-key"],
before_record_request=scrub_request,
before_record_response=scrub_response,
match_on=["method", "uri", "body"],
)Redaction changes the request body that gets saved. At replay time, vcrpy applies before_record_request to the live request before matching, so the scrubbed body still matches. This works because the same function runs on both sides.
Keep recordings small
A reviewer will read the diff. Large recordings hide changes. Three habits help:
- One cassette per test. A shared cassette changes whenever any test changes, so diffs mix unrelated edits.
- Short prompts in tests. Use a two-line invoice, not a real ten-page one. Smaller input means a smaller recording and a faster review.
- Stable formatting. The
RecordingClientwrites withindent=2, sort_keys=True. Sorted keys mean re-recording one prompt only changes the lines for that entry.
You can also check that a recording is safe with a test that scans the committed files:
import pathlib
import re
SECRET_PATTERNS = [
re.compile(r"sk-[A-Za-z0-9_-]{20,}"),
re.compile(r"(?i)bearer\s+[A-Za-z0-9._-]{20,}"),
]
def test_no_secrets_in_recordings():
for path in pathlib.Path("tests/cassettes").glob("*"):
text = path.read_text(encoding="utf-8")
for pattern in SECRET_PATTERNS:
assert not pattern.search(text), f"possible secret in {path}"This test fails the build if someone records with a new header you forgot to filter.
A review checklist
When you review a recording diff, check these items:
| Check | What to look for |
|---|---|
| Headers | No credentials, cookies, or account IDs |
| Prompts | No real customer data |
| Size | The file is small, and only expected entries changed |
| Replay | Tests pass offline with `record_mode="none"` |
Exercise
A teammate re-records a cassette and the pull request diff shows 400 changed lines, though only one prompt changed. Name two likely causes and one fix for each.
Show answer
First, the cassette is shared by many tests, so unrelated entries were rewritten. Fix it by using one cassette per test. Second, the writer does not sort keys or fix formatting, so entries are reordered or reindented. Fix it by writing with stable settings such as sort_keys=True and a fixed indent. A non-deterministic scrubber (for example, one that inserts timestamps) is another valid cause, fixed by making the scrubber deterministic.