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 and 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_idandproject_idwith 1-minute, 1-hour or 1-day buckets.1 Anthropic's usage report groups byapi_key_idandworkspace_idand 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
# 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:
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 NoneRun 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
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.
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 null2 |
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.
- 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.
- CI and deploy logs. A build step that prints environment variables is a common source. Check runs shortly before the first misuse.
- 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.
- Developer machines and shared hosts.
.envfiles, shell history, notebooks and screenshots. - Third-party tools that were handed the key: coding agents, IDE assistants, evaluation services, hosted consoles. See AI coding agents and secrets for how those leak.
- People changes. Offboarding, contractor access and role changes near the window.
- 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?.
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 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
