Keeping Test Secrets Out of Version Control and Agent Context
Almost every test automation engineer has done it at some point. You're moving fast, you need an API key to get one test passing, and you paste it into a config file or a fixture. You commit, you push, and that credential now lives in your Git history, even if you delete the file in the next commit. The fallout ranges from an awkward security review to a rotation scramble at the worst possible moment.
Coding agents add a few new paths. An agent in your editor can read your .env file, run a command that prints environment variables, paste a failing request (headers and all) into a pull request description, or helpfully "fix" a 401 by writing the token it found into a fixture. None of that is malicious. It's the agent doing what you asked with whatever it can see, which is why the rules have to be structural rather than "be careful".
In this article I'll walk through why test credentials end up in Git, the injection pattern I use in Python suites, the guardrails that catch mistakes before they reach the remote, and how I set things up so agents can run tests without ever handling a real secret directly.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Why test credentials end up in Git
The root cause is almost always convenience under pressure. There's no established way to inject a credential, so the path of least resistance is a hardcoded string. Once it's in a commit, git rm doesn't help: the value still exists in the commit that introduced it. Tools like git filter-repo can rewrite history, but that's disruptive on a shared repository, and once a secret has been pushed you should treat it as exposed and rotate it anyway. Rewriting history is cleanup, not a fix.
The second common cause is a .env file committed before anyone added it to .gitignore. The third is secrets inside test data: a realistic request payload with a real token pasted in "to make it work", committed with the rest of the fixtures. Test data rarely gets the same scrutiny as application code, which is exactly why it's a good hiding place. The same boundary applies to personal data, which I cover in generating test data with AI without leaking real data.
Prevention is far cheaper than remediation. Everything below is about stopping the value reaching a commit, a log or a prompt in the first place.
Inject secrets through the environment
For a Python suite, the pattern I use is environment variables, loaded locally from a .env file that is never committed.
Ignore first. Add the ignore rules and commit them before the file exists:
# .gitignore
.env
.env.local
.env.*.local
Commit a contract, not values. A .env.example documents every variable the suite needs, with placeholders:
# .env.example (committed)
API_BASE_URL=https://staging.example.com
API_KEY=replace_me
Load in one place and fail clearly. Tests never read the environment directly; a fixture does:
# conftest.py
import os
import pytest
from dotenv import load_dotenv
load_dotenv() # reads .env if present; does not override variables already set
@pytest.fixture(scope="session")
def api_key():
key = os.getenv("API_KEY")
if not key:
pytest.exit("API_KEY is not set. Copy .env.example to .env and fill it in.")
return key
A clear stop beats a cryptic 401 three tests later, for you and for an agent reading the output. In CI, the same variables come from your platform's encrypted secrets, never from plaintext in the workflow file. load_dotenv() is harmless there because no .env exists and the variables are already set. If you need rotation or audit logs, a secrets manager populates the same environment variables at runtime; the suite doesn't change. For the token side of this, see testing OAuth-protected APIs without hardcoding tokens.
Guardrails that catch mistakes before the remote
Discipline handles the intentional cases. Tooling handles the accidental ones.
A pre-commit secrets scanner. The pre-commit framework runs a scanner on every commit. detect-secrets and gitleaks are both solid; a minimal detect-secrets setup:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/Yelp/detect-secrets
rev: v1.4.0
hooks:
- id: detect-secrets
args: ["--baseline", ".secrets.baseline"]
Create the baseline once with detect-secrets scan > .secrets.baseline, run pre-commit install after cloning, and a staged string that looks like a key blocks the commit. The baseline lets you acknowledge known placeholders without switching the scanner off. Pin rev to the current release when you set it up.
Server-side scanning. On GitHub, secret scanning and push protection catch known credential formats at push time, a safety net for anything that slipped past local hooks. Hooks can be skipped; a server-side check can't be skipped by accident, so keep both.
A setup checklist. Before the first commit on a new test project: .env variants ignored, tool token files and credential caches ignored, .env.example committed with placeholders. It takes minutes.
Running agents without handing them secrets
The pre-commit hook still matters when an agent writes the commit, but it only covers Git. Agents also write to terminals, logs, pull request descriptions and chat. The approach I use:
- Test-only, low-privilege credentials. The keys in a developer or agent environment should only reach a test tenant or sandbox, with the narrowest scope that lets the suite run. If one leaks, the damage is small and rotation is routine.
- Redact in one place. Your HTTP client's logging is where tokens escape, because failure output prints requests. Mask
Authorizationand key headers in the client wrapper so neither people nor agents ever see them in test output. - No secrets in agent configuration. Instruction files and committed MCP server configs are code. Reference environment variables there, never values.
- Tell the agent the rules. In
.github/copilot-instructions.mdor your agent's equivalent file:
## Secrets
- Never read, print or summarise .env or any credential file.
- Never run env, printenv or similar commands that dump the environment.
- A 401 or 403 means a missing or expired credential. Report it; never write a token into code or fixtures.
- Do not paste request headers into PR descriptions or comments.
Instructions guide; they don't enforce. The scanner, push protection and low-privilege keys are what hold when guidance is ignored. I also check agent-written pull requests for new string literals in fixtures and config, which is where a "helpful" fix would hide a token.
A small redaction helper is worth having in the client wrapper:
SENSITIVE = {"authorization", "x-api-key", "cookie"}
def safe_headers(headers):
return {k: ("***" if k.lower() in SENSITIVE else v) for k, v in headers.items()}
Make it structural
Keeping secrets out of version control is a design decision, not a one-off cleanup. Build the injection pattern in early, enforce it with scanners on both sides of the push, give agents scoped credentials and clear rules, and you'll rarely face a rotation you could have avoided. For how this fits the rest of a developer workflow, see developer workflows for testers with VS Code and GitHub. My API testing courses set up a suite this way from the first commit.