Sub topic 9
Redact secrets and keep recordings reviewable
A recorded response is a file you commit to version control, so it holds whatever the real API call carried. This chapter covers how to keep credentials and personal data out of those files, and how to keep them small enough that a reviewer can read the diff.
This chapter assumes you have read the earlier chapters on the client seam, RecordingClient, and request matching. It also assumes you know pytest fixtures and basic regular expressions. The examples use vcrpy for HTTP recording and a small hand-written recorder for client-level recording.
What a recording can leak
A recording captures the whole exchange, not just the model's text. The table lists where sensitive data usually sits.
| Location | Typical content | Risk |
|---|---|---|
| Request headers | `authorization`, `x-api-key`, cookies | Live credentials |
| Query string | `?key=...` (some providers accept keys here) | Live credentials, and the URL is also a match key |
| Request body | Real user text, emails, names, internal documents | Personal or confidential data |
| Response headers | Organization IDs, request IDs, `set-cookie` | Account identifiers, noisy diffs |
| Response body | Echoed user text, generated content | Personal data, large files |
The request body deserves the most attention. Developers often record against real documents because they are convenient, and the prompt then ends up verbatim in the repository.
Redact at record time, not by hand
Do not edit cassettes after recording. Hand edits are forgotten, and they drift from what the code actually sends. Configure redaction once, in the recorder, so every new recording is clean.
vcrpy offers three levels of control:
filter_headersremoves a header, or replaces its value if you pass a(name, replacement)tuple.filter_query_parametersandfilter_post_data_parametersdo the same for URL and form parameters.before_record_requestandbefore_record_responseare hooks that receive the request or response and return a scrubbed one. A request hook can returnNoneto skip recording that request entirely.
The following module sets up all three. Put it in tests/vcr_config.py so every test shares it.
import os
import re
import vcr
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
DROP_RESPONSE_HEADERS = {
"set-cookie",
"openai-organization",
"request-id",
"x-request-id",
}
def scrub_text(text: str) -> str:
return EMAIL.sub("[email protected]", text)
def scrub_request(request):
if request.body:
body = request.body
if isinstance(body, bytes):
body = body.decode("utf-8")
request.body = scrub_text(body)
return request
def scrub_response(response):
headers = response.get("headers", {})
for name in list(headers):
if name.lower() in DROP_RESPONSE_HEADERS:
del headers[name]
return response
def record_mode() -> str:
# "once": replay if the cassette exists, record if it does not.
# "none": never touch the network, fail on any unrecorded request.
return "once" if os.environ.get("RECORD_CASSETTES") == "1" else "none"
my_vcr = vcr.VCR(
cassette_library_dir="tests/cassettes",
record_mode=record_mode(),
filter_headers=[("authorization", "REDACTED"), ("x-api-key", "REDACTED")],
filter_query_parameters=[("key", "REDACTED")],
before_record_request=scrub_request,
before_record_response=scrub_response,
match_on=["method", "uri", "body"],
)Three details matter here.
- Default to
none. CI and ordinary local runs should never reach the network. Recording is an explicit act, switched on with an environment variable. - Replace instead of delete for credentials. A placeholder such as
REDACTEDshows a reviewer that the header was sent and then scrubbed. - Redaction and matching interact. vcrpy runs
before_record_requeston the live request before comparing it with the cassette during replay. The scrubbed request must therefore still be deterministic. If you redact with a random token, replay will never match. Use fixed replacements like[email protected].
Scrubbing the body changes what is stored, not what is sent. Because matching compares scrubbed bodies on both sides, a prompt containing [email protected] at record time still matches a replay that contains the same address.
Give the SDK a dummy key during replay
Most SDKs refuse to build a client without a key. In replay, the key's value is irrelevant because the network is never touched, so set a fake one in a fixture.
import pytest
@pytest.fixture(autouse=True)
def dummy_api_key(monkeypatch):
if os.environ.get("RECORD_CASSETTES") != "1":
monkeypatch.setenv("OPENAI_API_KEY", "test-key-not-real")Add import os at the top of the file. When recording, the fixture steps aside and the real key from your shell is used. The filter_headers rule then strips it before the file is written.
Redact in a client-level recorder
The RecordingClient from the earlier chapter stores only a hash of each prompt, so the prompt text is not in the file. It stores the reply in full, though, and reviewers cannot tell which prompt a hash belongs to. A reviewable variant stores a scrubbed copy of the prompt next to the reply:
import hashlib
import json
import os
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def scrub(text: str) -> str:
return EMAIL.sub("[email protected]", text)
class ReviewableRecordingClient:
def __init__(self, path, real_client=None):
self.path = path
self.real_client = real_client
self.entries = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
self.entries = json.load(f)
def complete(self, prompt: str) -> str:
key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
if key not in self.entries:
if self.real_client is None:
raise LookupError(
"No recorded reply for this prompt. Re-record with a real client."
)
reply = self.real_client.complete(prompt)
self.entries[key] = {
"prompt_preview": scrub(prompt)[:200],
"reply": scrub(reply),
}
with open(self.path, "w", encoding="utf-8") as f:
json.dump(self.entries, f, indent=2, sort_keys=True)
return self.entries[key]["reply"]The key is computed from the raw prompt, so lookups stay exact. Only the stored text is scrubbed. The 200-character preview keeps the file small and tells a reviewer what each entry is for.
One consequence: the scrubbed reply is what tests see on replay. If your code parses an email out of the reply, the test now sees [email protected]. Write assertions against the scrubbed values, or use synthetic inputs that contain no real data in the first place. Synthetic inputs are the stronger option, because nothing sensitive is ever sent.
Add a scan as a safety net
Scrub rules cover the leaks you thought of. A scan catches the ones you did not. Add a test that fails if any committed cassette contains something shaped like a credential.
import pathlib
import re
SECRET_PATTERNS = [
re.compile(r"sk-[A-Za-z0-9_-]{20,}"),
re.compile(r"Bearer\s+[A-Za-z0-9._-]{10,}"),
re.compile(r"AKIA[0-9A-Z]{16}"),
]
def test_cassettes_contain_no_secrets():
for path in pathlib.Path("tests/cassettes").rglob("*.yaml"):
text = path.read_text(encoding="utf-8")
for pattern in SECRET_PATTERNS:
assert not pattern.search(text), f"{path} matches {pattern.pattern}"The placeholder Bearer REDACTED is shorter than ten characters, so it does not trip the second pattern. Extend the list with the key formats your providers use. Also consider a dedicated secret scanner in pre-commit or CI, since it will know more formats than a hand-written list.
Keep recordings reviewable
A cassette nobody can read is a cassette nobody reviews, and an unreviewed cassette is where leaks and wrong assumptions hide. These habits keep files readable:
- One cassette per test. A shared cassette makes every change touch many tests, and a failing test points to a file that mostly belongs to other tests.
- Record short inputs. Use the smallest invoice, document, or conversation that exercises the behavior. Set a low
max_tokenswhen recording so replies stay short. - Use stable formatting. In the client-level recorder,
indent=2andsort_keys=Truemake re-recording produce line-level diffs rather than one rewritten line. - Remove noise. Dropping request IDs and timestamps from response headers, as the hook above does, means a re-record changes only the lines that actually changed.
- Name cassettes after behavior.
summarize_empty_input.yamltells a reviewer what to expect.test3.yamldoes not. - Treat a re-record as a code change. A diff in a cassette means the API's behavior, or your prompt, changed. Read it the way you would read a change to an expected-output fixture.
A short review checklist
When a pull request touches a cassette, check:
- No header holds a real value. Look for anything other than
REDACTED. - No request or response body contains names, emails, or internal text.
- The prompt in the recording matches what the code under test is meant to send.
- The file is small enough to read. If it is not, shrink the input and record again.
Common errors
- Redaction applied only to headers. The most common leak is a real document in the request body. Always open a fresh cassette and read it once.
- Random replacement values. Replacing a field with a random token breaks matching on replay. Use constants.
- Matching on a header you redacted. If
match_onincludesheaders, every request matches only if the redacted values agree. This usually works, but it adds fragility for no benefit. - Recording with
new_episodesby habit. This mode appends any unmatched request to the file, so cassettes grow silently and stale entries stay. Preferonceand delete files deliberately. - Committing before scanning. Run the scan test locally before the first commit of a new cassette, not after.
Exercise
You record a cassette for a test and filter_headers removes the authorization header. A reviewer still finds a customer's email address in the file. Name the file location where it most likely sits, and give two changes that prevent it.
Show answer
It most likely sits in the request body, which holds the prompt, or in the response body if the model echoed the prompt. Header filtering does not touch bodies. One change is to add a before_record_request hook (and a response hook if needed) that scrubs email patterns with a fixed replacement such as [email protected]. The other is to use synthetic test inputs that contain no real data, so nothing needs scrubbing. Adding a secret-scan test that fails on email-shaped strings also catches regressions.
Exercise
Why is it a problem if before_record_request replaces an email with a random string each time it runs, even though the cassette itself looks clean?
Show answer
During replay, vcrpy scrubs the live request with the same hook before matching it against the cassette. A random replacement produces a different body each run, so the body never equals the recorded one and replay fails to find a match. Replacements must be deterministic constants.