If OpenAI's Codex wrote an API key into your code and committed it, rotate the key first, then purge it from history and move it to an environment variable. Codex works from a task and produces running code, and an inline key is often the quickest route to that, so an exposed secret is a normal outcome to guard against, not a surprise.
Why it's a problem
A key in committed source is exposed to anyone with the repo and is scraped from public GitHub within minutes. Any key that touches money or a database is a live liability for as long as it stays valid, which is why rotating it comes before any code cleanup.
How to fix it, in order
- 1Rotate the key first. Revoke and regenerate it at the provider before anything else.
- 2Check the provider's logs. Look for activity you did not create and treat anything unexplained as an incident.
- 3Purge it from git history. Use git filter-repo or BFG and force-push, remembering forks and caches can retain the old commit.
- 4Move it to an environment variable. Read the new key from the environment and confirm the .env is gitignored.
Why Codex does this
Codex generates code to satisfy a task, and when an integration needs a credential the literal value inline is the completion that runs. It does not distinguish a value that should be a secret from ordinary configuration, so it will place the key wherever the code needs it.
Stop it happening again
Add a rule to AGENTS.md telling Codex to read secrets from environment variables and never inline them. Keep a committed .env.example with empty values and a gitignored .env. Install a gitleaks pre-commit hook so an inline key fails the commit.
The quick fix
- Rotate the key first.
- Check provider logs for unauthorized use.
- Purge from git history; move the key to an environment variable.
- Add a secrets rule to AGENTS.md and install a gitleaks pre-commit hook.
Common questions
How does the AGENTS.md file restrict Codex behavior?
Codex reads AGENTS.md as project-level instructions. A rule like 'always read secrets from environment variables' is applied in subsequent sessions and code generations.
Can Codex be used with a .env file safely?
Yes, if the .env is gitignored. Codex can reference environment variables at runtime. The risk is when it writes the literal value inline in the generated code rather than referencing the variable.
Is the fix process the same for any AI tool that exposes a key?
Yes. The core sequence is always: rotate first, check for unauthorized use, purge from history, move to an environment variable, and add a future guard.