# An AI API key leaked: how to find where it came from

URL: https://infro.io/blog/an-ai-api-key-leaked-how-to-find-where-it-came-from
Author: INFRO Editorial (https://infro.io/blog/editorial)
Publisher: INFRO
Published: 2026-11-30
Last modified: 2026-11-30
Last reviewed: 2026-11-30 (next review due 2027-02-28)
Topic: Security and governance
Format: Guide

> After you revoke a leaked OpenAI or other provider key, date the leak from the first out-of-pattern hour in per-key provider usage, match that hour to events in candidate systems, and size spend from tokens at your own rates. Gateway traces show which traffic was yours and which was not.

Key takeaways:
- Revocation stops new spend; the source and the exposure window come from per-key usage history, so export it before anything ages out.
- Date the leak from the first hour a key's usage left its pattern, then widen the window backwards to the earliest moment the key could have been exposed.
- Match that first anomalous hour to events in candidate systems: commits, CI logs, deploys, tool onboarding, laptop and offboarding changes.
- Compare provider usage per key with gateway traces: tokens the provider saw and the gateway did not are the attacker's, or a bypass.
- Size spend from provider usage at your own contract rates, then confirm against the provider's cost report and invoice.

## What the first hour leaves unanswered

The key is revoked and spending has stopped. Three questions remain, and a revocation checklist does not answer any of them. When did a copy of the key first leave your control? Which system let it out? How much did it cost?

They matter for different reasons. The window decides which logs you have to review and what you tell the provider. The source decides what else is exposed, because a repository, a CI log or a vendor tool that leaked one key usually held others. The spend decides what you dispute. The immediate steps are in [Leaked OpenAI API key? What to do in the first hour](https://infro.io/blog/leaked-openai-api-key) and [Leaked Anthropic API key?](https://infro.io/blog/leaked-anthropic-api-key). This guide starts after them.

The method has four steps: preserve the evidence, date the leak, find the system, size the spend. Each step uses a different source, and the sources disagree in useful ways.

## Preserve evidence before it ages

Do this before any analysis. Some of your evidence expires on a schedule you do not control.

- **Provider usage for the key, by hour.** Export it now, grouped by key id. INFRO's guide to OpenAI's organization usage endpoint describes grouping by `api_key_id` and `project_id` with 1-minute, 1-hour or 1-day buckets.[1] Anthropic's usage report groups by `api_key_id` and `workspace_id` and also takes 1m, 1h and 1d buckets.[2]
- **Key metadata.** Record the key id, name, project or workspace, creator, creation time, last-used time and permissions. A deleted key may not be listable later.
- **Provider audit log.** OpenAI's Audit Logs API records the lifecycle of keys, users, service accounts and projects, but audit logging has to be enabled before events are recorded.[1] If it was off during the exposure, you cannot reconstruct it. Turn it on now.
- **Gateway request log.** Your gateway's history is limited by plan.[3] Export what covers the window before it rolls off.
- **Source-side logs.** Repository history, CI run logs, secret manager access logs and shell history on shared hosts all have their own retention. Snapshot them.

Work from copies, in UTC. OpenAI's usage dashboard reports in UTC,[1] so convert your own logs to match before comparing anything.

## Date the leak from the key's usage

The goal is two timestamps. The **first misuse** is the earliest hour the key did something your systems did not. The **earliest exposure** is the earliest moment a copy could have existed. The leak window runs from earliest exposure to revocation. First misuse is only the upper bound on when exposure began.

### Find the first out-of-pattern hour

Pull the key's usage at hourly resolution for at least 30 days, longer if the key is old. Then look for what changed, not just what is large:

- a model your code never calls
- hours when your own workload is idle
- a step in volume with no deploy to explain it
- a different project or service tier than the key's usual one

```bash
# OpenAI: hourly tokens for one key (admin credential required)
curl -s "https://api.openai.com/v1/organization/usage/completions?start_time=$START&bucket_width=1h&group_by=api_key_id&group_by=model&api_key_ids=$KEY_ID" \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY"

# Anthropic: hourly tokens for one key (Admin API credential required)
curl -s -G "https://api.anthropic.com/v1/organizations/usage_report/messages" \
  --data-urlencode "starting_at=$START_ISO" --data-urlencode "bucket_width=1h" \
  --data-urlencode "group_by[]=api_key_id" --data-urlencode "group_by[]=model" \
  --data-urlencode "api_key_ids[]=$KEY_ID" \
  -H "anthropic-version: 2023-06-01" -H "x-api-key: $ANTHROPIC_ADMIN_KEY"
```

Both calls need an admin credential; Anthropic states that workspace API keys do not work for these endpoints.[2] Anthropic also documents a newer Usage and Cost Analytics API and calls this one legacy but supported, so check which you should build on.[2] Page through results with the cursor the response returns.[4]

Then find the first hour mechanically rather than by eye:

```python
import statistics

def first_anomalous_hour(rows, baseline_days=14, k=5):
    """rows: list of (iso_hour, tokens, model), oldest first, UTC."""
    known_models = {m for _, _, m in rows[: baseline_days * 24]}
    hourly = [t for _, t, _ in rows[: baseline_days * 24]]
    cap = statistics.median(hourly) * k or 1
    for hour, tokens, model in rows[baseline_days * 24:]:
        if model not in known_models or tokens > cap:
            return hour, model, tokens
    return None
```

Run it with a few values of `k` and baseline lengths. If the answer moves by a day, the window is uncertain and you should say so in the report instead of picking a convenient hour.

### Bound the window from the other side

Use key metadata. A key created on a given day cannot have leaked before it. A key with no usage at all in a stretch and then a burst suggests it sat unused in someone's possession. Keys created before 20 December 2023 did not have usage tracking on by default, and OpenAI shows their earlier usage as "Untracked",[1] so an old key may have an unreadable early history. Anthropic's key list has no last-used field; the usage report grouped by key is how you learn when a key was last used.[4]

> **Example: Illustrative window**
> A key created 3 March. Usage is flat and daytime-only until a Tuesday, when hourly tokens jump 40-fold between 02:00 and 05:00 UTC on a model the service never calls. The first misuse is that Tuesday 02:00. The key was also pasted into a repository on 19 March. The earliest exposure is therefore the 19 March commit, and the leak window is 19 March to revocation, not Tuesday to revocation. These dates and figures are made up for illustration.

## Use gateway traces to separate your traffic from theirs

Once you have the provider's view, subtract your own. If requests normally pass through a gateway, its log holds every call that went through it, with the model, connection, outcome, tokens and estimated cost.[3] The provider holds everything, including calls that never touched the gateway. Compare them per key and per UTC day, as in [Detect AI API usage that bypassed your gateway](https://infro.io/blog/detect-gateway-bypass-provider-usage).

The difference tells you which key leaked:

| Provider usage on the key | Gateway log for the same key | What it suggests |
| --- | --- | --- |
| More tokens than the gateway sent | Normal traffic present | The provider key itself leaked and is used directly |
| Tokens, none from the gateway | Absent | A provider key outside your gateway, or a workload going direct |
| Normal tokens | Foreign countries or a volume jump on a gateway key | The gateway key leaked; the provider key may be intact |
| Spend on a null key id | n/a | Console or playground use; Anthropic reports it with `api_key_id` null[2] |

Gateway key leaks leave other traces. INFRO's leak detector fires when a gateway key is used from six or more countries in a UTC day, or when a day reaches twenty times its median over the previous seven with at least 500 requests, and it flags a revoked or rotated-out key being presented again as the strongest evidence that a copy exists.[5] Those timestamps are another independent clock for the first misuse. Per-key country counts are kept for 30 days,[6] so pull them early.

## Find the exposing system

You now have a time and a profile. Treat the first misuse as the end of a search and work backwards through candidate systems, each with its own clock.

1. **Source control.** Search history for the key's prefix and last characters, not the full secret. Include forks, deleted branches and pull request diffs. Compare commit times with the earliest exposure.
2. **CI and deploy logs.** A build step that prints environment variables is a common source. Check runs shortly before the first misuse.
3. **Application and error logs.** A request dump or stack trace that includes headers can store the key where many people can read it. Check log aggregators and their access lists.
4. **Developer machines and shared hosts.** `.env` files, shell history, notebooks and screenshots.
5. **Third-party tools** that were handed the key: coding agents, IDE assistants, evaluation services, hosted consoles. See [AI coding agents and secrets](https://infro.io/blog/ai-coding-agents-secrets-exposure) for how those leak.
6. **People changes.** Offboarding, contractor access and role changes near the window.
7. **Front-end and mobile builds.** A key shipped in a bundle is public from the release date.

Use the attacker's usage as a fingerprint to rank candidates. A key leaked from a public repository tends to be picked up and used within a short time, so the first misuse sits near the commit. A key leaked through a vendor's breach may show a long gap, because the first misuse follows the breach rather than your own change. Long gaps between a plausible exposure and first misuse are normal; do not dismiss a candidate for that reason alone.

If one system holds several keys, review every key it held, not only the one you noticed. Also check whether a provider admin key was in reach, since it can create new keys that your revoked one will not explain. Your provider audit log is where those show up.[1]

## Size the spend

Provider usage gives you tokens per hour, per model, per key. Spend is tokens times the rates your contract carries, so use your negotiated rates where you have them and list rates only as a fallback. Include cached input, cache writes, output and service tier, which are billed differently. Then reconcile with the provider's own cost report and invoice, since the invoice is what you pay and an estimate from tokens is not.

Three cautions apply:

- Estimates from request logs are not an invoice. A gateway's request log is operational evidence, not billing.[3]
- Unpriced traffic exists. A model or tier with no rate configured should be reported as unpriced, not as zero.
- The window for the dispute is the leak window, but the spend that counts is what was made with the key and not by you. Subtract your own legitimate traffic using the gateway log from the previous section.

Keep one table per key: hour, model, tokens by type, rate applied, amount. It is the evidence a provider's support team will ask for. For the refund question, see [Stolen AI API key charges: can you get a refund?](https://infro.io/blog/ai-api-key-theft-bill-refund).

## Evidence your gateway can hand over

If your traffic goes through INFRO, its incident flows for a leaked gateway key or a leaked provider key end in a report with the timeline, requests by model, time and estimated provider cost, and countries per key. The report covers seven days before opening by default, up to 90 days, lists up to 10,000 requests, and holds metadata only, never prompts or responses.[6] With a usage credential, INFRO also flags a connected key whose provider-reported usage did not go through it, checked every six hours.[5] Request records can be exported as CSV or through the API.[7] INFRO does not revoke keys at your provider.[6]

## Write down what you do not know

A good report states the window as a range, names the evidence behind each end, and lists what could not be checked, such as an audit log that was off or a key with untracked early usage. OWASP's LLM Top 10 project includes unbounded consumption among the risks to plan for, and this incident is a practical case of it.[8] Finish with the structural fixes: one key per workload with an owner, expiry dates, spend limits and network restrictions, and a recorded key id for each key. [A postmortem template for AI credentials](https://infro.io/blog/ai-credential-incident-postmortem-template) gives a structure for the write-up.

- [ ] Per-key provider usage exported at hourly resolution, in UTC
- [ ] Key metadata recorded before it disappears
- [ ] Provider audit log enabled, and reviewed for new keys and members
- [ ] First misuse found by a repeatable method, not by eye
- [ ] Window stated as earliest exposure to revocation
- [ ] Gateway log subtracted from provider usage per key and day
- [ ] Each candidate system checked against its own clock
- [ ] Every key that system held reviewed and rotated
- [ ] Spend computed at your contract rates and reconciled with the provider's report
- [ ] Unknowns written into the report

## Questions

### Does revoking an OpenAI key delete its usage history?

Do not assume either way. Export the per-key usage and cost data right after revoking, before you rely on it. If the key is gone from the key list, you need its key id, which you should have recorded in your inventory or can read from usage rows grouped by key.

### Can I tell which person leaked the key?

Usually not from provider logs, which carry key ids and projects rather than people. You can narrow it to a system and a time, then use that system's own history, such as commit authors, CI run owners or tool onboarding records. Treat it as a process failure first.

### What if the provider shows usage but my gateway shows none?

Then the traffic did not pass through your gateway. That points to a leaked provider key used directly, or to a workload that bypasses the gateway. It is the case where the gateway's own logs cannot size the spend and the provider's usage report has to.

### Is the leak window the same as the time of the first bad request?

No. The first bad request is the latest the key could have been exposed. The exposure window runs from the earliest moment a copy could have existed, such as the commit or the log write, to revocation.

## Sources

1. Leaked OpenAI API key? What to do in the first hour — INFRO. https://infro.io/blog/leaked-openai-api-key (accessed 2026-11-30)
2. Usage and Cost API (legacy), Claude Platform Docs — Anthropic. https://platform.claude.com/docs/en/manage-claude/usage-cost-api (accessed 2026-11-30)
3. Request traces, Observability — INFRO Docs. https://infro.io/docs/observability/traces (accessed 2026-11-30)
4. Detect AI API usage that bypassed your gateway — INFRO. https://infro.io/blog/detect-gateway-bypass-provider-usage (accessed 2026-11-30)
5. Security signals, Security — INFRO Docs. https://infro.io/docs/security/signals (accessed 2026-11-30)
6. Incidents, Security — INFRO Docs. https://infro.io/docs/security/incidents (accessed 2026-11-30)
7. Exports and OpenTelemetry — INFRO Docs. https://infro.io/docs/observability/exports (accessed 2026-11-30)
8. OWASP Top 10 for Large Language Model Applications — OWASP Foundation. https://owasp.org/projects/top-10-for-large-language-model-applications (accessed 2026-11-30)
