# Unsecured API keys: where AI keys sit exposed and how to sweep

URL: https://infro.io/blog/unsecured-api-keys-where-ai-keys-sit-exposed-and-how-to-sweep
Author: INFRO Editorial (https://infro.io/blog/editorial)
Publisher: INFRO
Published: 2026-12-01
Last modified: 2026-12-01
Last reviewed: 2026-12-01 (next review due 2027-03-01)
Topic: Security and governance
Format: Methodology

> Unsecured AI API keys sit in six places scanners treat unevenly: repository history, CI logs, container image layers, notebook outputs, chat and ticket text, and browser bundles. Sweep each with a scanner suited to it, start from the provider's own key list, and treat every hit as compromised until revoked.

Key takeaways:
- Sweep six surfaces, not one: repository history, CI logs, image layers, notebook outputs, chat and ticket text, and shipped browser bundles.
- Start from the provider's own list of keys and their last use, so you know what you are hunting for and which hits are live.
- Host-side secret scanning covers public repositories and npm; every other surface needs your own scanner run on a schedule.
- Each scanner class has a blind spot: patterns miss unknown formats, entropy checks are noisy, and history scanners never see images or logs.
- Treat every hit as compromised: revoke at the provider first, then clean the copy, then find the other copies.
- Plant a decoy key in the places you could not scan, so a leak there announces itself.

## What the sweep is for

Most guidance on unsecured API keys tells you where keys should live. This post is the other half: a method for finding the ones that do not. It assumes you have already read the [AI API key security checklist](https://infro.io/blog/ai-api-key-security-checklist) and know what to do when a key leaks ([how to find where a leaked key came from](https://infro.io/blog/an-ai-api-key-leaked-how-to-find-where-it-came-from)). The question here is how to find plaintext keys before someone else does.

An AI provider key is worth more to an attacker than most secrets because it spends money and reaches data as soon as it works. OWASP's GenAI Security Project, which maintains the Top 10 for LLM applications, covers the application-level risks around models[1]; the sweep below covers the credential layer under them. The provider's own guidance is consistent: keep keys out of code and public repositories and supply them through environment variables or a secret manager[2], and keep them out of source control, client-side code and prompts[3].

The method has four steps: build the list of keys that should exist, sweep six surfaces, triage each hit, and plant decoys where you could not look. Order matters. Sweeping without the list tells you a string looks like a key, not whether it is live.

## Step 0: build the list from the provider side

Before scanning, pull each provider's list of keys and their last use. That gives you the set of live credentials, which you then match against hits.

- **OpenAI.** Project keys and service-account keys are listed in the dashboard and through the Admin APIs. Keys created before 20 December 2023 did not have usage tracking on by default, and their earlier usage shows as `Untracked`[2]. Those are the keys least visible to you, so list them first.
- **Anthropic.** The Admin API reports each key's `expires_at` on its List API Keys endpoint[3]. A key with expiration "Never" is a candidate for the sweep, because nothing will retire it if it leaks.
- **Policy limits.** OpenAI's key-governance settings, such as restricting key types or a maximum lifetime, apply only to new key creation; existing keys are unaffected[2]. Turning on a policy does not clean up what already exists.

If you use INFRO, the Security screen's credential inventory lists provider keys outside INFRO, meaning keys your provider lists that no connection holds, with the provider's redacted form of each. It needs a usage credential, which is available for OpenAI and Anthropic[4]. Without one the list says "not checked", never "none"[4]. Whatever tool you use, keep the same distinction: an empty result and an unchecked result are different.

Record each key's owner, environment and last use. A hit later that matches a key with no recent use is a lower-priority revoke; one that matches a key used this hour is an incident.

## Surface 1: repositories and their history

Start with Git because it is where most scanners work best. Scan the full history on every branch, not just the working tree: a key committed and deleted in the next commit is still in the history, and anyone with a clone has it.

GitHub's own scanning covers the whole history on all branches plus issues, pull requests, discussions, wikis and secret gists, but only on public repositories for free; private and internal repositories need GitHub Secret Protection[5]. Partner alerts, where GitHub tells the provider, apply to public repositories and public npm packages. A match in a private repository raises an alert for admins and the committer and is not sent to the provider, so nothing is revoked for you[5]. INFRO's earlier guide also reports, as read on 2026-10-21, that GitHub's table lists the Gemini API key format with neither partner reporting nor push protection[5]. Re-check that table before relying on any row.

So run your own scanner over every repository you own, on every host, including GitLab, Bitbucket and self-hosted Git. Two widely used open-source scanners are Gitleaks and TruffleHog[5]. A pattern scan to start with, as an illustration:

> **Example: Illustrative starter patterns**
> These regular expressions are examples, not a maintained rule set. Confirm each provider's current key format before trusting them, and prefer your scanner's maintained rules.
> 
> ```bash
> rg -n -uu --hidden \
>   -e 'sk-[A-Za-z0-9_-]{20,}' \
>   -e 'sk-ant-[A-Za-z0-9_-]{20,}' \
>   -e 'AIza[0-9A-Za-z_-]{35}' \
>   -e 'sk_infro_[A-Za-z0-9_-]{20,}' \
>   --glob '!node_modules' .
> ```

What this misses: keys split across lines or built from string concatenation, keys base64-encoded in config, and any format with no fixed prefix. Also look at forks and archived repositories; they are scanned only if you list them.

## Surface 2: CI logs and pipeline configuration

A CI system is where keys are most often handled in plaintext, and the log is the second copy. Check three things.

1. **Log content.** Download recent build logs and scan them like any text. Masking in CI systems typically works by matching the exact registered secret value, so a key that is transformed, truncated or printed by a tool in a different form (for example in a debug dump of environment variables, or in a command echoed with `set -x`) is not masked. Verbose debug mode on a failing job is the usual cause.
2. **Pipeline files.** Scan workflow and pipeline definitions for literals, and for `echo` or `env` calls that print the environment. OWASP's secrets cheat sheet has a section on where a secret should live in CI/CD: in the CI tooling, in a secrets management system, or not touched by CI at all[6]. The last is the strongest option.
3. **Stored variables.** List every CI variable that holds a provider key and compare it to your Step 0 list. A key stored as a CI variable by a person who has since left is common, and for Anthropic a personal key stops working when its owner leaves the organization, while a service-account key does not[3].

Where the CI platform can authenticate with an identity provider, remove the stored key altogether. Anthropic documents Workload Identity Federation for CI and for servers with an identity provider[7], and OpenAI documents project service accounts with workload identity federation so a workload can authenticate without storing a long-lived key[8]. A key that does not exist cannot be found in a log.

## Surface 3: container image layers

Images are the surface teams forget, because a `COPY .env` or a build argument ships the key inside a layer even if a later step deletes the file. Deleting a file in a later layer hides it from the running container, not from anyone who pulls the image and unpacks the layers. An image in a registry is also not a repository, so repository-level secret scanning does not look at it.

Check both the layers and the image metadata, since `ENV` and `ARG` values live in the image config:

```bash
IMAGE=registry.example.com/team/app:latest
mkdir -p /tmp/img && docker save "$IMAGE" | tar -x -C /tmp/img
docker history --no-trunc "$IMAGE" | rg -i 'key|token|secret'
for f in /tmp/img/blobs/sha256/* /tmp/img/*/layer.tar; do
  [ -f "$f" ] || continue
  d="/tmp/img/x/$(basename "$(dirname "$f")")-$(basename "$f")"
  mkdir -p "$d" && tar -xf "$f" -C "$d" 2>/dev/null
done
rg -n -uu -e 'sk-[A-Za-z0-9_-]{20,}' -e 'sk-ant-[A-Za-z0-9_-]{20,}' /tmp/img
```

Scan every tag you still keep, not only `latest`; an old tag from a debugging session is the likely hit. Include base images your team built and pushed. A scanner that unpacks layers does this for you, but confirm that it reads the config blob and not only the file layers. After a fix, the rebuilt image does not remove the old tag: delete or expire the old tags, and revoke the key regardless.

## Surface 4: notebooks

A notebook stores its outputs inside the file. A cell that printed `os.environ` or a failed authentication call that echoed a request header leaves the key in the saved output, which may be committed, synced to a shared drive or exported to a hosted notebook service, none of which sees a Git diff of the source cell.

Scan `.ipynb` files as raw JSON with the same patterns, since the output text is plain strings inside it, and also scan exported HTML and PDF copies. Check the places notebooks accumulate: shared drives, a data-science repository, hosted notebook workspaces and teaching material. For hosted services, the scan has to run through the service's export or API, because the files are outside Git.

Two fixes are worth making once you have the hits. Strip outputs before commit with a pre-commit hook such as `nbstripout`, and load keys in a notebook from the environment or a secret manager rather than pasting them into a cell. OpenAI's guidance on exposing keys through environment variables or a secret manager applies here as anywhere[2].

## Surface 5: chat tools, tickets and agent transcripts

Keys get pasted into chat to unblock someone, into tickets as part of a reproduction, and into coding-agent transcripts when an agent reads a `.env` file. These copies are not in any repository and are usually searchable by a large group.

Sweep them through the export or search interface of each tool:

- Chat workspace: use the admin export or the search API for the key patterns, including direct messages where your retention and legal rules allow it.
- Ticket and wiki systems: search titles, comments and attachments. Attachments such as HAR files and log bundles are where request headers hide.
- Request headers: search for the header forms providers use. Anthropic's API takes the key as a Bearer token in `Authorization`, or in the legacy `x-api-key` header[7], so search for `x-api-key:` and `Authorization: Bearer` followed by a long token in pasted `curl` commands.
- Coding-agent logs and session exports: see [AI coding agents and secrets](https://infro.io/blog/ai-coding-agents-secrets-exposure) for how those copies arise.

You cannot delete a chat message and call it fixed: the key was readable, and may have been copied. Revoke it, then delete the message. If you run prompts through a gateway, a guardrail that blocks or redacts API-key patterns in prompts can stop the key reaching the provider, with the caveat that pattern detection can miss things.

## Surface 6: browser bundles and mobile binaries

A key in client code is public by construction. Scan what you actually ship, not the source: the built JavaScript, the source maps, the HTML, and unpacked mobile packages. A key can arrive in a bundle through a build variable your framework exposes to the client, so check each variable name that is inlined at build time, and check `.map` files, which can carry source strings that minified output does not make obvious.

Crawl your production and staging sites, download every script and map, and run the patterns over them. Do the same for each mobile build you still distribute, since old versions stay installed. Old deploys cached on a CDN or archived by an artifact store are worth including.

If a provider key is in a bundle, the fix is architectural, not a scan result: move the call to your server, as set out in [AI API keys in frontend and mobile apps](https://infro.io/blog/ai-api-keys-frontend-mobile-apps), and revoke the key. Anthropic's guidance is to keep keys out of client-side code[3]. A key with expiry set to hours would at least limit the window, but only a server-side call removes the exposure.

## What each scanner class catches and misses

No single tool covers all six surfaces. Pick the class that fits the surface, and know its blind spot.

| Scanner class | Catches | Misses |
| --- | --- | --- |
| Provider-pattern matcher on files | Known key prefixes in plain text, fast, low noise | Unknown or prefix-less formats, split or encoded strings |
| Git-history scanner | Keys committed then deleted, across branches | Anything not in Git: images, logs, notebooks outside the repo, chat |
| Entropy or generic detector | Unlabelled high-randomness strings, formats nobody wrote a rule for | Many false positives (hashes, IDs); still misses encoded strings |
| Live validation | Tells you whether a found key still works | Does not find anything; sending a key to a provider to test it needs a controlled place and your approval |
| Host-side scanning with partner reporting | Public repositories and public npm packages, with provider revocation for partner formats | Private repositories (alert only), other Git hosts, images, logs, chat[5] |
| Provider-side key list and usage | Which keys exist, last use, expiry, usage you did not expect | Where the copy sits |

Table: Scanner classes against what they find and what they leave.

The last row is why Step 0 comes first. A scan finds strings; the provider's list tells you which strings matter. A key that your provider lists as used from an address you do not recognise is a priority whatever the scanner said.

## Triage a hit

Every hit follows the same path. Do not spend time debating whether a key was seen by anyone.

1. **Match it to the list.** Is it live, whose is it, which environment, when last used? A validity check from the scanner can answer the first question; GitHub's table, for instance, shows which formats have validity checks[5].
2. **Revoke at the provider.** Create a replacement, update the workload, verify, then revoke the old key; this is the rotation order OpenAI documents[8]. If the key is plainly abused, revoke first and accept the outage.
3. **Review usage from the earliest exposure**, not from the time you found it. The commit date or message date bounds when the key became readable.
4. **Remove the copy and find its siblings.** A key in a notebook was probably also pasted in chat. Re-run the other surfaces with the same key string.
5. **Fix the cause**: the build step, the missing hook, or the workflow that put a human in the path.

Remember what only the provider can stop. Gateway budgets and monitoring govern traffic that passes through them; a provider key used directly meets only the key's scope, the provider's spend limit and revocation[9]. So set a provider-side spend limit on every key found, even if you revoke it.

## Plant decoys where you could not look

You will not be able to scan everything: a departed contractor's laptop, a vendor's support tool, a backup. For those, plant a decoy that tells you when the place leaks.

INFRO's tripwire keys are decoy gateway keys that serve nothing. They have the format of a real gateway key, answer like an unknown key, and when one is presented every member is told, with the country and time. The alert is critical and cannot be muted[10]. You plant one where a real key would sit, under a plausible name, and never use it. INFRO connects provider accounts you already hold and applications use INFRO gateway keys instead[11], so the sweep's goal is also to replace raw provider keys with gateway keys that can be limited, rotated and turned off. A tripwire does not replace the sweep; it covers the surfaces you could not reach.

Schedule the sweep to repeat. Keys come back: a new notebook, a new image tag, a new paste. Re-run the cheap surfaces on every change, the heavy ones on a calendar, and treat a hit on a previously clean surface as a process failure to fix.

## Questions

### What counts as an unsecured API key?

Any working provider credential stored where someone without a need to use it can read it: plaintext in a repository or its history, a CI log, an image layer, a notebook output, a chat message, a ticket, or a file shipped to browsers. Storage in a secrets manager with access control and audit is the opposite case.

### Is one scanner enough for the sweep?

No. A scanner that reads Git history will not open container layers or notebook outputs unless you point it there, and a pattern matcher will not recognise a key format it has no rule for. Run one scanner per surface and compare the results against the provider's own key list.

### Should I revoke a key found in a private repository?

Yes, if it is live. Host-side partner reporting only reaches providers for public repositories, so nothing will revoke it for you, and a private copy still sits in clones, caches and backups. Revoke at the provider first, then remove the copy.

### How often should the sweep run?

Run the cheap surfaces, repositories and CI configuration, on every change, and the heavy ones, image layers, notebook stores, chat history and bundles, on a schedule you can keep, such as weekly, plus once in full before any audit.

## Sources

1. OWASP Top 10 for Large Language Model Applications — OWASP Foundation. https://owasp.org/projects/top-10-for-large-language-model-applications (accessed 2026-12-01)
2. Production best practices — OpenAI. https://developers.openai.com/api/docs/guides/production-best-practices.md (accessed 2026-12-01)
3. Developer API keys — Anthropic. https://platform.claude.com/docs/en/manage-claude/api-keys (accessed 2026-12-01)
4. Credential inventory — INFRO docs. https://infro.io/docs/security/credentials (accessed 2026-12-01)
5. AI API keys leaked on GitHub: what secret scanning catches — INFRO. https://infro.io/blog/ai-api-keys-github-secret-scanning (accessed 2026-12-01)
6. Secrets Management Cheat Sheet — OWASP Cheat Sheet Series. https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html (accessed 2026-12-01)
7. API overview — Anthropic. https://platform.claude.com/docs/en/api/overview (accessed 2026-12-01)
8. API keys and service accounts — OpenAI. https://developers.openai.com/api/docs/guides/api-keys.md (accessed 2026-12-01)
9. AI API key security checklist: 48 controls to verify — INFRO. https://infro.io/blog/ai-api-key-security-checklist (accessed 2026-12-01)
10. Tripwire keys — INFRO docs. https://infro.io/docs/security/tripwires (accessed 2026-12-01)
11. INFRO documentation overview — INFRO docs. https://infro.io/docs (accessed 2026-12-01)
