Skip to content

Security and governanceMethodology

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

Unsecured AI keys rarely sit where the checklist says to look. This is a find-it method for security and platform engineers: six places to sweep, what each scanner class catches and misses, and how to triage a hit.

By INFRO Editorial

Published

11 min read

A grid of dark glass cards with small bar charts, a few of them lit amber, on a dark ground

In short

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 and know what to do when a key leaks (how to find where a leaked key 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 models1; 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 manager2, and keep them out of source control, client-side code and prompts3.

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 Untracked2. 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 endpoint3. 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 unaffected2. 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 Anthropic4. 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 Protection5. 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 you5. 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 protection5. 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 TruffleHog5. A pattern scan to start with, as an illustration:

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 all6. 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 not3.

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 provider7, and OpenAI documents project service accounts with workload identity federation so a workload can authenticate without storing a long-lived key8. 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:

Shell
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 anywhere2.

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 header7, 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 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, and revoke the key. Anthropic's guidance is to keep keys out of client-side code3. 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 classCatchesMisses
Provider-pattern matcher on filesKnown key prefixes in plain text, fast, low noiseUnknown or prefix-less formats, split or encoded strings
Git-history scannerKeys committed then deleted, across branchesAnything not in Git: images, logs, notebooks outside the repo, chat
Entropy or generic detectorUnlabelled high-randomness strings, formats nobody wrote a rule forMany false positives (hashes, IDs); still misses encoded strings
Live validationTells you whether a found key still worksDoes not find anything; sending a key to a provider to test it needs a controlled place and your approval
Host-side scanning with partner reportingPublic repositories and public npm packages, with provider revocation for partner formatsPrivate repositories (alert only), other Git hosts, images, logs, chat5
Provider-side key list and usageWhich keys exist, last use, expiry, usage you did not expectWhere the copy sits
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 checks5.
  2. Revoke at the provider. Create a replacement, update the workload, verify, then revoke the old key; this is the rotation order OpenAI documents8. 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 revocation9. 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 muted10. 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 instead11, 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 readers ask

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.

From the team that builds it

Where this shows up in INFRO

INFRO is a control plane in front of the provider accounts you already hold. The capabilities below are the parts of it this article touches, each with the documentation that defines its behaviour.

  • Tripwire keys

    Available with a plan

    A decoy gateway key to plant where your secrets live. It serves nothing and answers like an unknown key; when it is presented, every member is told the country and time.

  • Security screen

    Available with a plan

    One console screen for credential safety: posture checks, the most your gateway keys can spend in the next 24 hours under the limits in force, one feed of leak, provider-credential, spend, network-refusal and access-change signals, and an inventory of every credential that can spend money or change configuration, with a CSV export. On every plan.

  • Usage outside INFRO, on every plan

    Available with a plan

    With a usage credential (an OpenAI or Anthropic admin key that INFRO only reads with), INFRO compares your provider's own usage by key with what it served and flags a key whose usage did not go through INFRO. OpenAI and Anthropic, checked every six hours, on every plan.

  • Guardrails

    Available with a plan

    Pattern-based checks on chat completion prompts and responses: block, redact or flag email addresses, phone numbers, card numbers, IBANs, US Social Security numbers, IP addresses, API keys and your own terms, plus optional classifier checks on your own connection to a decision model's provider. Detection can miss things. Included on every plan.

    Read the documentation for Guardrails
  • Provider connections

    Available with a plan

    Connect provider accounts you already hold. Each credential is encrypted when saved, scoped to your organization and never shown again; applications use INFRO gateway keys instead.

    Read the documentation for Provider connections
  • Key leak signals

    Available with a plan

    INFRO emails you when a gateway key is used from six or more countries in a day or at twenty times its usual daily volume. Nothing is blocked.

INFRO accounts are self-serve. Provider usage is billed to you by your providers; INFRO charges a software subscription and takes 0% of model spend. See plans.

Sources

Numbered in order of first citation. Each was opened and checked against the claim on the date shown.

  1. 1.OWASP Top 10 for Large Language Model Applications (opens in a new tab) — OWASP Foundation. Accessed Dec 1, 2026.
  2. 2.Production best practices (opens in a new tab) — OpenAI. Accessed Dec 1, 2026.
  3. 3.Developer API keys (opens in a new tab) — Anthropic. Accessed Dec 1, 2026.
  4. 4.Credential inventory (opens in a new tab) — INFRO docs. Accessed Dec 1, 2026.
  5. 5.AI API keys leaked on GitHub: what secret scanning catches (opens in a new tab) — INFRO. Accessed Dec 1, 2026.
  6. 6.Secrets Management Cheat Sheet (opens in a new tab) — OWASP Cheat Sheet Series. Accessed Dec 1, 2026.
  7. 7.API overview (opens in a new tab) — Anthropic. Accessed Dec 1, 2026.
  8. 8.API keys and service accounts (opens in a new tab) — OpenAI. Accessed Dec 1, 2026.
  9. 9.AI API key security checklist: 48 controls to verify (opens in a new tab) — INFRO. Accessed Dec 1, 2026.
  10. 10.Tripwire keys (opens in a new tab) — INFRO docs. Accessed Dec 1, 2026.
  11. 11.INFRO documentation overview (opens in a new tab) — INFRO docs. Accessed Dec 1, 2026.

About this article

Read on 2026-12-01: OpenAI's production best-practices and API-keys guides, Anthropic's API overview and Developer API keys pages, the OWASP LLM Top 10 project page and the OWASP Secrets Management cheat sheet contents, and INFRO's docs and earlier posts. Scanner products' own documentation was not read, so scanner behaviour is described by class and not as vendor claims; provider key prefixes in code are illustrative and unconfirmed.

Last checked against its sources on . The next review is due by . No separate named reviewer is recorded for this article.

How articles are written, sourced and corrected is set out in the editorial standards.