Skip to content

Security and governanceGuide

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

Revoking a leaked AI API key ends the spending but not the investigation. This guide covers the second phase: dating the leak from provider usage and key metadata, matching it to the system that exposed it, and sizing what the exposure cost.

By INFRO Editorial

Published

9 min read

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

In short

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 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_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
Shell
# 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:

first_anomaly.py
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

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 keyGateway log for the same keyWhat it suggests
More tokens than the gateway sentNormal traffic presentThe provider key itself leaked and is used directly
Tokens, none from the gatewayAbsentA provider key outside your gateway, or a workload going direct
Normal tokensForeign countries or a volume jump on a gateway keyThe gateway key leaked; the provider key may be intact
Spend on a null key idn/aConsole 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.

  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 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?.

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

Questions readers ask

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.

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.

  • Incident mode and report

    Available with a plan

    A guided response to a leaked gateway key, a breached host, a leaked provider key or a taken-over account that ends in a report: the timeline, the requests by model, time and estimated provider cost, the countries each key was used from, and the actions taken, as JSON, CSV or a page to print.

  • Usage and cost per request

    Available with a plan

    Every request records its model, latency, token or unit counts, and estimated provider cost, queryable by project and key.

    Read the documentation for Usage and cost per request
  • Request traces and payload logs

    Available with a plan

    Per-request timing detail, with prompt and completion logging off by default and a retention window you choose.

    Read the documentation for Request traces and payload logs
  • Usage, request and FOCUS exports

    Available with a plan

    GET /v1/usage and GET /v1/requests on any gateway key, the request log and usage series as CSV, plus a FOCUS v1.4 Cost and Usage dataset as JSON or CSV, so AI spend lands in your FinOps platform beside the rest of your cloud cost.

    Read the documentation for Usage, request and FOCUS exports
  • 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.

  • Retired and turned-off key signals

    Available with a plan

    A signal when a revoked, rotated-out, expired or turned-off gateway key is presented again, with the country and time.

  • 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.

  • Audit log

    Available with a plan

    Member, key, and policy changes recorded with actor and timestamp, viewable in the console.

    Read the documentation for Audit log

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.Leaked OpenAI API key? What to do in the first hour (opens in a new tab) — INFRO. Accessed Nov 30, 2026.
  2. 2.Usage and Cost API (legacy), Claude Platform Docs (opens in a new tab) — Anthropic. Accessed Nov 30, 2026.
  3. 3.Request traces, Observability (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  4. 4.Detect AI API usage that bypassed your gateway (opens in a new tab) — INFRO. Accessed Nov 30, 2026.
  5. 5.Security signals, Security (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  6. 6.Incidents, Security (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  7. 7.Exports and OpenTelemetry (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  8. 8.OWASP Top 10 for Large Language Model Applications (opens in a new tab) — OWASP Foundation. Accessed Nov 30, 2026.

About this article

Read on 2026-11-30: INFRO's security, signals, incidents, exports and traces docs, two INFRO guides that summarise OpenAI's usage and key endpoints, Anthropic's Usage and Cost API page and OWASP's LLM Top 10 project page. Provider-side log retention periods and OpenAI-side audit log field details were not confirmed in what was read, so they are left out.

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.