← All fixes

Fix it

GitHub Copilot suggested a hardcoded API key — how to fix it

High severityCWE-798 (Use of Hard-coded Credentials)

GitHub Copilot autocompletes code from patterns in its training data, and those patterns include hardcoded credentials, so it will confidently suggest a key inline. If you accepted one and pushed it, rotate the key first, then clean up and turn on the guards below. Research found repos with Copilot active leak secrets at a meaningfully higher rate than average.

Why it's a problem

A committed key is exposed to anyone with the repo and is scraped from public GitHub within minutes. Copilot compounds the risk because it suggests the pattern so smoothly that it feels reviewed when it was not, and it has even been shown to reproduce real-looking secrets when asked to replace redacted ones.

How to fix it, in order

  1. 1Rotate the key first. Revoke and regenerate it at the provider. This is the only step that invalidates the copy that was already scraped.
  2. 2Check for unauthorized use. Review the provider's logs and billing for activity you did not create.
  3. 3Purge it from git history. Remove it with git filter-repo or BFG and force-push, knowing forks and caches may retain the old commit, which is why rotation came first.
  4. 4Move it to an environment variable. Read the new key from process.env or import.meta.env and confirm the .env file is gitignored.

Why GitHub does this

Copilot predicts the next tokens that best match the surrounding code. When that code is setting up an API client, the highest-probability completion is often a literal key, because that is what appears in the code it learned from. It is not evaluating whether the value should be a secret; it is completing a pattern.

Stop it happening again

Turn on GitHub secret scanning with push protection so a recognized key is blocked at push. Add a rule to .github/copilot-instructions.md telling Copilot to always read secrets from environment variables. And install a gitleaks pre-commit hook, since Copilot will keep suggesting inline keys and the hook is what actually stops them.

The quick fix

  • Rotate the key first.
  • Check provider logs for unauthorized use.
  • Purge from git history; move the key to an environment variable.
  • Enable GitHub push protection and add a secrets rule to copilot-instructions.md.

Want to know if this pattern is already in a repo you shipped? Scan a public repo free, no account needed.

Scan a repo →

Related: the full prevention setup

GitHub Copilot Hardcoded an API Key — How to Fix It: Prbl