Skip to main content
Security guideReviewed

Exposed API keys: where secrets leak, how to check your own site, and what to fix first

API keys and other secrets leak into source files, git history, the JavaScript every visitor downloads, log files, and environment files or .git folders a web server hands out.

This guide shows how to confirm a leak on your own property, why the old key is revoked or rotated before anything is cleaned, and how to prove it no longer works. It comes with a fixture repository you can run on your own computer, taking four planted canary keys from detection through to proof.

Canary fixture repository and leak response sequence

An illustration you can run on your own computer: a local git repository with four canary keys planted in current source, history, a client bundle and a log, a local key service that can revoke and replace them, and one script for each step from detection to proof, with a regression test. Every output below was copied from one recorded run of these files on Node.js 26.0.0, git 2.53.0 and git filter-repo 2.47.0.

How to use it

The canaries use a format invented for this page.

secrets-exposure.txt

Introduction40 lines

CANARY FIXTURE REPOSITORY AND LEAK RESPONSE SEQUENCE ILLUSTRATION ONLY. The shop app, its keys, the key service and every result below were written for this page and run on one computer. Nothing here is a client's code or a client's result. Every API key in the lab is either a canary in a format invented for this lab, "lab-canary-" followed by a label, a hyphen and 16 hexadecimal characters, or a key the lab's own key service makes up while it runs, "lab-key-" followed by a name, a version and 32 hexadecimal characters. No provider issues keys in either format. The key service's admin token is random, made when the service starts and never printed. Run the lab on your own computer, and use what it teaches only on systems you own or are authorised in writing to test. WHAT IT NEEDS Node.js, git and git filter-repo. The scripts import only node:assert/strict, node:child_process, node:crypto, node:fs, node:fs/promises, node:http, node:os, node:path, node:test, node:timers/promises and node:url, and call the global fetch() function, so the lab installs nothing from npm. git filter-repo is a separate tool you install yourself; GitHub's documentation gives Homebrew as one way. The run below was recorded on macOS with Node.js 26.0.0, git 2.53.0 and git filter-repo 2.47.0, the only versions and the only system it was run on. GitHub's documentation says the --sensitive-data-removal option needs git filter-repo 2.47 or later. Timings, timestamps, process ids and the new keys differ from run to run. The commit ids did not: three complete runs on this computer produced the same ones. WHAT IT DOES NOT DO Every server in the lab listens on 127.0.0.1, on a port the system picks, and no port is printed. Nothing calls a real provider, and no real key is created, used or revoked. The fixture is a new git repository that make-fixture.mjs creates inside the lab folder. Every git command names it with -C, and the script stops if git resolves to any other repository. The scripts set an invented author, Fixture Developer at fixture.invalid, and point GIT_CONFIG_GLOBAL and GIT_CONFIG_SYSTEM at /dev/null, so the fixture's commits use neither your git settings nor your name and email address. The search in search.mjs looks for this lab's canary format and for exact values it is given. It is not a general secret scanner, and it would pass straight over a real key in any other format. THE FOUR CANARIES name value planted in orders lab-canary-orders-3f9a61c0d27e4b85 current source: config/credentials.json mailer lab-canary-mailer-8c2d04e7b61f3a95 history only: .env, committed then deleted search lab-canary-search-51e7c9a0f2d84b36 client bundle: dist/client.js payments lab-canary-payments-a04f7d2c9e81b653 application log: logs/app.log The key service starts with all four active, the way a provider still accepts a key that nobody revoked. THE SEQUENCE, AND THE SOURCE BEHIND EACH STEP Set-up Scripts: node service.mjs start, then node make-fixture.mjs. They build the leaky repository, its bundle and its log. Source: git's documentation of GIT_AUTHOR_NAME, GIT_AUTHOR_DATE, GIT_COMMITTER_DATE and GIT_CONFIG_GLOBAL, for the fixed author, dates and settings. Step 1, detect Script: detect.mjs. It searches the working tree; every commit (git rev-list --all, then git grep over each commit's tree); every object git holds, reachable or not (git cat-file --batch-all-objects); the bundle; and the log. Then it requests five paths from a server whose web root is the project folder. Sources: git's grep, rev-list and cat-file documentation; the latest edition of OWASP WSTG-CONF-04 for .env and .git/. Step 2, contain Script: contain.mjs. It revokes every key the search found, before anything is cleaned. Sources: GitHub, Removing sensitive data from a repository; OWASP Secrets Management Cheat Sheet, section 9.2. Step 3, rotate Script: rotate.mjs. It issues replacements into the host environment, deletes the key file, changes the app to read every key from the environment, and rebuilds the bundle without the secret. Sources: Supabase, Rotate a leaked or compromised API key; GitHub's advice to use environment variables or a secret management service. Step 4, clean up Script: clean.mjs. It removes .env and config/credentials.json from every commit with git filter-repo, then redacts the revoked keys in the log and keeps every line. Sources: GitHub's procedure and git filter-repo's documentation; OWASP Secrets Management Cheat Sheet, section 9.2, on removing secrets from logs while keeping log integrity. Step 5, prove Script: prove.mjs. Old keys refused, new keys accepted, refused attempts recorded, the first changed commit gone, every search empty, sensitive paths not served. Sources: git filter-repo's documentation for the git cat-file -t check; OWASP Secrets Management Cheat Sheet, section 8.3, on logging attempts to use a revoked secret. Regression test Script: leak.test.mjs. It fails on the leaky fixture and passes on the cleaned one. Source: Node.js test runner documentation, which says a failing test sets the exit code to 1.

What counts as an exposed secret, and what does not

An exposed API key is a credential that has reached a place where more people or systems can read it than ever needed to: a public repository, the JavaScript every visitor downloads, a log file, or a file the web server hands to anyone who asks for it.

The same goes for every other secret an application holds. OWASP's Secrets Management Cheat Sheet lists the more common types of secret worth detecting, among them API keys, connection strings, credentials, passwords, private keys, session tokens and application configuration files.

Not every key in a browser is a leak. Some providers design a key to be public, put the protection somewhere else, and say so in their own documentation. Stripe says its publishable key can go in front-end code or applications you distribute, and that it cannot perform sensitive operations such as creating charges or reading account data.

Supabase lists its publishable key as safe to expose online and says it only reaches what Row Level Security allows. Firebase says that if an app's setup follows its guidelines, API keys restricted to Firebase services do not need to be treated as secrets and are safe to include in code or configuration files.

It also says the security of Realtime Database, Cloud Firestore and Cloud Storage data is enforced by Firebase Security Rules, and protection of covered APIs by Firebase App Check, not by keeping the API key secret.

The same pages draw the other line just as plainly. Stripe says only publishable keys are safe to expose outside your application's back end, and that you are responsible for protecting the others, restricted keys included. Supabase says a secret key bypasses every Row Level Security policy and must never be put in a browser, a shipped application or source control.

So the question for any key you find is not whether it looks secret. It is what the key's own provider says about exposing it, and what the key can do in someone else's hands.

A key that is meant to be public still deserves the limits its provider offers: Firebase, for one, calls it critical to apply appropriate API restrictions to every API key in a project.

Two neighbouring guides take the questions on either side of this one. Session tokens are secrets too, but how they are issued, rotated and ended belongs to the session management guide. Personal and business data that a page or API hands to the wrong person is the subject of the sensitive data exposure guide. This page stays with credentials: the keys, tokens and passwords an application uses to reach other systems.

Five places keys leak, and why each copy is hard to take back

A leaked key is a copy, and changing the original does nothing to the copy.

Four of the places below match the four canaries in the fixture on this page. The fifth, the web server, is checked by the same fixture with a small local server.

Source and configuration files

The plainest leak is a key typed into a configuration file, a settings module, a test fixture or a seed script, then committed. 1 min read

Repository history

Deleting the line, or the whole file, adds a new commit. 1 min read

The JavaScript sent to browsers

A browser can only run a script it can read, so a key inside a client bundle is public from the moment the bundle is deployed. 1 min read

Logs

A log keeps a copy of whatever the code wrote to it, for as long as the log is kept. 1 min read

Environment files and .git folders the web server hands out

If the folder a site is served from is the project folder rather than only the build output, anything in it may be requested by path: an environment file, a configuration file, or the .git folder that holds the repository's history. 1 min read

How to confirm a leak on your own property

Run these checks only on repositories, builds, logs and domains you own or are authorised in writing to test.

Each one looks at your own property from the inside or requests your own hostnames, and none of it involves looking for anyone else's keys.

  • Start with an inventory. List each key the application uses: the provider, what the key can reach, where it is configured, who can rotate it, and whether the provider documents it as safe to expose. A search only finds what it is told to look for. The fixture's search is an example: it matches the lab's own canary format and would pass straight over a real key in any other format.
  • Search the working tree and every commit. git grep searches tracked files, and given a list of commits it searches the blobs in each commit's tree; git rev-list --all lists the commits reachable from every ref and from HEAD. Search for a distinctive part of each key rather than pasting the full value into a command, where it would stay in your shell history.
  • If the repository is on GitHub, read its secret scanning alerts. GitHub says secret scanning covers the entire Git history on all branches for known secret types. It runs automatically for free on public repositories, and private and internal repositories owned by an organisation need GitHub Secret Protection enabled on GitHub Team or the one other plan GitHub's page names for those repositories. A private repository owned by a personal account is in neither group; GitHub's page covers user-owned repositories only under the managed-user and self-hosted server offerings it names. Custom patterns, which are regular expressions you define, cover formats the defaults do not.
  • Search what you deploy, not only what you commit. The files your deploy step uploads are what visitors receive, so search the built JavaScript, and any source maps, for each key. The JavaScript bundle secret scanner in the related guides is a browser-based tool for that pass; treat what it reports as leads for a person to confirm.
  • Search the logs where they end up: on the server, in whatever collects or forwards them, and in your CI run logs.
  • Request the sensitive paths on your own hostnames, staging included. From a private browser window, or with a command-line HTTP client, request /.env, /.git/HEAD and /.git/config. A correctly configured server answers with an error, such as 404 or 403, and none of the file's content. Read the body as well as the status code: the latest WSTG-CONF-04 says to confirm a response actually returns the file's content, not a custom 404 or an access-denied page, and notes that custom "not found" pages returning 200 are a common false positive. In the fixture, the first line of the real HEAD file is ref: refs/heads/main.
  • For each key you confirm, look it up in the provider's dashboard: whether it is still active and, where the provider shows it, when it was last used. Test whether a key works only if the key is yours.

The first hour: revoke or rotate before you clean anything

Once a key is confirmed exposed, the instinct is to delete it from wherever it was found.

That removes one copy and leaves the key working. GitHub's documentation on removing sensitive data sets the order: when the data is a secret, the first step is to revoke and/or rotate it. Once it is revoked or rotated it can no longer be used for access, and GitHub says that may be enough on its own. git filter-repo's documentation also says to revoke and rotate the credential first, and GitHub's secret scanning page adds that removing a secret from Git history is time-intensive and often unnecessary once the credential has been revoked.

OWASP's Secrets Management Cheat Sheet breaks containment into four steps, in this order: revocation, immediate for keys that were exposed; rotation, so a new secret can be created and put in place quickly; deletion of the revoked or rotated secret from the exposed system, code and logs included; and logging, so whoever handles the incident knows who had access, when the key was used and when it was last rotated.

Supabase adds two conditions in its guide to rotating a leaked key. Fix the root cause before you rotate anything, or the new key can leak the same way. And if someone is actively using the leaked key, retire it right away, even though components that still use it stop working until it is replaced.

The fixture takes that path: contain.mjs revokes all four keys first, and the deployed app's next two calls fail with 401 until rotate.mjs fixes the code and puts the replacements in place.

  • Write down what you found before you change it: where each copy was, since when, and who could read that place. The cleanup removes the evidence.
  • Look in the provider's dashboard and logs for any use of each key that you do not recognise.
  • Stop the source, so a replacement cannot leak the same way: take the served file away, switch off the debug line, or remove the public prefix.
  • Revoke each exposed key, or rotate it with the shortest overlap your deployment allows. Revoke at once if there is any sign someone else is using it.
  • If someone else has used a key, or it could reach customers' personal information, bring in an incident response specialist. Clever Ops does not provide incident response or monitoring.
  • If personal information may have been reached, get advice early. The OAIC explains that under the Notifiable Data Breaches scheme, an organisation or agency covered by the Privacy Act 1988 must notify affected individuals and the OAIC when a data breach is likely to result in serious harm to a person whose personal information is involved.
  • If you hold cyber insurance, read what the policy says about telling the insurer before you engage anyone.

Rotating a key without an outage, and when to accept one

Rotation is two changes that have to meet: the provider starts accepting a new key, and every component that used the old key moves to it.

If the old key dies first, whatever still uses it fails, as the fixture's app did between steps 2 and 3. Some providers support an overlap, in which both keys work for a while, so the move can happen without a gap.

Stripe's documentation describes one. Rotating a key generates a replacement that is ready to use immediately, and the dashboard asks for an expiration date for the old key: choosing Now deletes the old key, and choosing a time displays the time remaining until it expires.

Stripe says that when you rotate a key in the Dashboard, both the old and new keys work for up to 7 days. To avoid downtime, it suggests, if possible, using the new key from a small subset of servers or services first and watching server logs for errors, and checking the old key's request logs so it is expired only after its request volume has been at zero for a few hours or days.

Supabase's guide follows the same shape for a leaked secret key: create a new secret key, replace the compromised key everywhere the application uses it, confirm every component uses the new one, then delete the old key, which cannot be undone. Unless someone is actively using the leaked key, it says to wait until every component has moved before retiring it.

For an exposed key, an overlap is also a window in which the exposed key still works. Keep it as short as the deployment allows, and skip it when there is any sign of use you do not recognise. Restarting the application on a new key is not the same as killing the old one.

In its section on automating secrets management, where it discusses dynamic secrets, OWASP's cheat sheet notes that restarting the application does not itself revoke stolen credentials, which remain usable until the backing service expires or revokes them.

Two habits make the next rotation smaller. Supabase recommends a separate secret key for each backend component, so a leak from one component means rotating only that key. OWASP recommends rotating secrets regularly, so a stolen credential works only for a short time, and ASVS 5.0 requirement 13.3.4, at Level 3, asks for secrets to be configured to expire and be rotated based on the application's documentation.

Cleaning up history, bundles, logs and served files

Cleanup comes after the key is dead.

It limits what the old copies reveal; it does not take the key back. Anyone who cloned the repository, forked it or copied a log before the cleanup still has the key, which is why the revocation in the first hour matters more than anything in this section.

Rewriting history, and what it cannot undo

GitHub's procedure uses git filter-repo, in a version with the --sensitive-data-removal flag (2.47 or later), run in a clone of the repository. 2 min read

Bundles and builds

Rebuild without the value and redeploy, then deal with the builds that came before it. 1 min read

Redacting logs

OWASP's cheat sheet says secrets in logs must have a process for removing the secret while maintaining log integrity. 1 min read

Closing the served paths

Deploy only the build output, so the web root never contains .git, .env or configuration files in the first place. 1 min read

Proving the old key is dead

Proof has two halves: the old key no longer works, and no copy of it, or of its replacement, is left where you looked.

Only the provider can answer the first. For a real key, that means calling the provider's API from your own computer with the old credential and seeing it refused. Stripe, for example, says a request that includes an expired key gets an authentication error.

Use a read-only request, and only with keys that are yours: a key you found that belongs to someone else is reported to its owner, not tried.

Then look at what the provider recorded after the key was revoked. OWASP's cheat sheet lists being revocable, including the logging of attempts to use a revoked secret, among the properties a secret should have. The fixture's key service records each refused attempt by key name, never by value, and its record shows six: the deployed app's own two calls after revocation, then the four made by the proof step. An attempt on a dead key may come from a component of your own that nobody moved.

The second half is the searches again, with the new keys added, plus the served paths. After a history rewrite, git filter-repo's documentation gives a check for a clone that was cleaned up rather than cloned again: git cat-file -t on each first changed commit must end in a fatal error.

In the fixture every one of these passes, with the clone check run on the rewritten fixture itself. The regression test then holds the result in place. It fails while any canary is left in any of the five places and passes once they are clean.

The Node.js test runner sets the exit code to 1 when a test fails, so a pipeline step that treats a non-zero exit code as a failure fails with it.

Stopping the next leak

Each leak in the fixture had a small, specific cause, and each has a small, specific guard.

  • Keep keys out of code. GitHub advises against hardcoding secrets and suggests environment variables or a secret management service that injects them at runtime. Stripe suggests your hosting platform's secrets vault and, where you cannot use one, environment variables. Fail loudly when a key is missing, as the fixed fixture app does, rather than falling back to a value in the code.
  • Ignore environment files before the first commit. Next.js says its default create-next-app template adds all .env files to .gitignore and that you almost never want to commit them. Vite says .env.*.local files can contain sensitive variables and that you should add *.local to .gitignore. An ignore rule added later does not remove a file that is already tracked.
  • Check before the push. GitHub's push protection blocks pushes that contain secrets before they reach the repository. Push protection for users is on by default and stops you pushing secrets to public repositories on GitHub.com; push protection for repositories needs GitHub Secret Protection and is off until someone enables it. Once push protection for repositories is enabled, GitHub says you can customise it by defining custom patterns, regular expressions you define to detect secrets specific to, for example, your repository or organisation, and you can choose to enable push protection for each pattern. That is one way a format of your own, such as a canary, could be blocked at the push. A pre-commit hook, which GitHub and OWASP both suggest, checks for a secret before it is committed at all.
  • Give the public prefix only to values the provider calls safe to expose. NEXT_PUBLIC_ and VITE_ mean every visitor gets a copy.
  • Log a hash, never the key, and keep request dumps out of production. CWE-532's mitigations include removing debug log files before deploying to production.
  • Deploy the build output, not the repository, so nothing under .git or in an environment file sits in the web root.
  • Plant canaries of your own: a unique, harmless value in the places a real key would sit, searched for on every build. A canary that turns up somewhere new shows a copy escaping before a real key does.
  • Keep pipeline secrets narrow. How a pipeline hands secrets to its jobs, and what a compromised job can read, is covered in the CI/CD security guide.
  • Watch for a dead key being presented. Alerting on events like that, and keeping secrets out of logs by design, belong with the security logging and monitoring guide.

Where a Clever Ops check fits

Clever Ops does not monitor repositories, logs or sites and does not respond to incidents.

If someone else has used one of your keys, start with the provider and an incident response specialist. What Clever Ops offers sits on either side of an incident: a check before one, and a check after the keys are rotated.

Each report records what was checked and on which dates. It is not monitoring, and a key committed the day after the report is outside what it can speak to. If Clever Ops built or hosts the site, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

  • The website security check reads the page source and JavaScript your site sends to every browser for keys and secrets, and looks for configuration files and other leftovers at paths the web server will serve. A key it finds is recognised by its format, not tried.
  • A secure code review looks for keys in source files, test fixtures, seed scripts, configuration, build output and the history of the branches in scope, and reports each one with what it can reach and a note to rotate it.
  • The vibe-coded app security check searches the JavaScript an AI-built app sends to browsers and, if you share it, the exported code and its history, for secret and service keys.

Frequently asked questions

No. Some keys are designed to be public, and the provider's documentation says so: Stripe's publishable key can go in front-end code, and Supabase lists its publishable key as safe to expose online. A secret, server-side or restricted key in the same place is a leak. Check what the provider says about that exact key type, then restrict even the public ones as far as the provider allows.

No. The commits before the deletion still hold it, and so does every clone and fork made from them. Revoke or rotate the key at the provider first. GitHub's documentation says that once a secret is revoked or rotated it can no longer be used for access, and that this may be all you need. Rewriting history comes after that, if at all.

Only after the key is revoked, and only if what remains exposed is worth the disruption. GitHub lists the side effects, including changed commit hashes, lost diffs on closed pull requests and the risk that an old clone pushes the data straight back. If you go ahead, GitHub's documentation uses git filter-repo with the --sensitive-data-removal flag, run in a clone of the repository.

Request /.env, /.git/HEAD and /.git/config on each of your own hostnames from a private browser window. A correctly configured server returns an error and none of the file's content. Read the body as well as the status, because a custom not-found page can answer 200. If any of them returns the real file, treat every key it holds as exposed, and deploy only your build output from then on.

Where the provider supports it, run old and new keys side by side: create the new key, move every component to it, watch the old key's requests fall to zero, then expire it. Stripe lets you choose when the old key expires when you rotate, and Supabase's guide has you replace the key everywhere before deleting the old one. If there is any sign someone else is using the exposed key, revoke it at once and accept the short outage.

Call the provider's API with the old key from your own computer, using a read-only request, and confirm it is refused. Check the provider's logs for any use after you revoked it. Then search the repository history, the build output and the logs again, adding the new key to the search so you know it has not leaked the same way.

No. Clever Ops does not provide incident response or monitoring, so start with the provider and an incident response specialist. Once the keys are rotated, a website security check or a secure code review can look for keys the browser can read, files the server hands out and secrets in your code, and the report records what was checked.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.