FortWatch.ai

Leaked API Key or Cloud Credential? What to Do in the First Hour

FortWatch

FortWatch Team

• 23 min read

Leaked API Key or Cloud Credential? What to Do in the First Hour

After Okta's October 2023 breach, Cloudflare rotated the credentials it believed were exposed. It left one service token and three service-account credentials alone, believing them unused. In its post of 1 February 2024 it wrote: "This was incorrect and was how the threat actor first got into our systems." A leaked key works for whoever holds it until you revoke it at the issuer, and its permissions decide what they can do.

A key leaks through a public commit, a .env file your web server hands to anyone who asks, a ticket someone pasted it into, or a vendor that has just told you it was breached. How it got out changes little about the first hour of incident response. This post is that hour, step by step, for AWS, GitHub, Google Cloud, Azure, Stripe, Slack and the AI model APIs. In the middle of one? Go straight to Step 1.

What to do when an API key leaks: revoke, scope, hunt, close, replace

Revoke the key and every session minted from it at the issuer. Scope the damage from the provider's own logs, starting at the moment of exposure. Hunt for anything the key created. Close the leak path. Then ship a narrower replacement and prove the old key fails. One exception: if the leak path is still live (a file still served, a ticket still open), close it right after the revoke, or the replacement leaks the same way.

Treat every exposure as a compromise, and rate it by what the key can do, never by whether anyone probably saw it. Speed matters: in the EleKtra-Leak campaign, Unit 42 reported on 30 October 2023 that exposed AWS keys were used "within five minutes of their initial exposure on GitHub".

Read what the key can do before you rate it. For an AWS user key, aws iam list-attached-user-policies --user-name <user> lists its managed policies and aws iam list-user-policies --user-name <user> its inline ones; AWS's recovery playbook for an exposed access key uses the first. Many admins get their power from a group, so also run aws iam list-groups-for-user --user-name <user>, then list-attached-group-policies and list-group-policies for each group. A permissions boundary or an SCP can only narrow this: "No permissions are granted by an SCP." A Stripe sk_ secret key is unrestricted; an rk_ restricted key has only the permissions you gave it. An Azure storage account key gives "full access to the storage account data and the ability to generate SAS tokens." An admin-level AWS key is full compromise of the AWS account, and in an Organization's management account a way into the member accounts too. An owner-level Google Cloud service account key, a storage account key or an sk_live_ key is full compromise of that project, storage account or Stripe account.

Deactivate first, replace second

AWS's routine rotation creates the new key first and deactivates the old one last, which is right when nobody hostile holds it. AWS's recovery playbook for an exposed key starts with deactivation: "Start here. This step contains the damage." Our advice: in a leak, deactivate first and accept the outage. A deactivated key can be reactivated in one command; an hour of someone else's access to your account cannot be undone. The playbook's urgency table allows no delay for an admin key, for activity you don't recognise or for a key that reaches PII, financial or health data, and at most 4, 12 or 24 hours for narrower keys. Stripe's key best practices are shorter: "rotate it immediately even if you aren't sure anyone saw it."

Step 1: revoke the key and the sessions it minted

Disable or revoke the key at the provider that issued it, then end the sessions and tokens it already minted, in the same sitting. Several credentials leave something behind that outlives the revoke:

CredentialWhat survives the revokeWhere to look next
AWS IAM access keySTS session credentials minted with it (GetSessionToken, up to 36 hours; 1 hour from a root key), and any second key or service-specific credential the attacker addedCloudTrail, by the AKIA key ID and each ASIA ID it minted
GitHub personal access tokenDeploy keys die with the token; GitHub documents nothing else as deleted. Pushes, tags, releases, packages, workflow edits, webhooks, collaborators, SSH keys and runners stay.Each repository it reached; security log, public_key and oauth_access
Google Cloud service account keyAccess tokens already issued (1 hour by default), and tokens for any service account it could impersonateCloud Audit Logs, by serviceAccountKeyName
Azure storage account keyChanges made with the key: containers set to public access, deleted or overwritten blobs. Every SAS signed with the key dies with it.StorageBlobLogs, if a diagnostic setting existed
Stripe secret or restricted keyCharges, refunds, payouts, connected accounts and webhook endpoints it madeView request logs on the key; Developers > Webhooks
OpenAI, Anthropic, Gemini keysUsage already billed; the stored files it could readThe provider's usage page; the files stored in the project or workspace
Slack tokenMessages and files it read or posted; a user token has that user's accessteam.accessLogs (paid plans, logins only); the app's install and OAuth settings

Exposed AWS access key: deactivate it and end its sessions

Check whose key it is first. aws sts get-caller-identity, run with the leaked key, returns its ARN. An ARN ending in :root (AWS's identifier formats) is a root key, and the next three paragraphs do not apply to it; the root branch follows them. For an IAM user's key:

aws iam update-access-key --access-key-id AKIA... --status Inactive --user-name <user>

A deactivated key "cannot be used for programmatic access to AWS". Keep it until the investigation ends: an inactive key can be reactivated if you deactivated the wrong one. Write the key ID down; it is your search handle in CloudTrail. In the same sitting, run aws iam list-access-keys --user-name <user> and deactivate any key you did not create: a user can hold two access keys, and the deny below does not touch long-term keys. Also run aws iam list-service-specific-credentials --user-name <user> and aws iam get-login-profile --user-name <user> for a console password you did not set.

Deactivation does not end minted sessions: temporary credentials "are valid until they expire", up to 129,600 seconds (36 hours). Attach this inline deny to the IAM user, with the current UTC time:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {"DateLessThan": {"aws:TokenIssueTime": "<now, ISO 8601 UTC>"}}
  }]
}

aws:TokenIssueTime "is only present in the context of AWS requests that are signed with temporary security credentials", so the user's new long-term key keeps working. For each role the key could assume, use IAM > Roles > the role > Revoke active sessions.

A root key. No IAM policy reaches it: "You cannot change the permissions for an AWS account root user", nor for GetSessionToken or GetFederationToken credentials created as root (same AWS page). Sign in as root, delete the root access key under Security credentials, change the root password and turn on root MFA. Sessions the key minted last at most one hour (GetSessionToken reference). In a member account of an AWS Organization, an SCP with the same aws:TokenIssueTime deny does apply: an SCP restricts "the member account's root user" (AWS's SCP guide). Then open an AWS Support case.

If AWS has attached AWSCompromisedKeyQuarantineV2, V3 or V4, leave it. The V4 policy's description says "Do NOT remove this policy" and points to the support case. V4 denies cloudtrail:LookupEvents and iam:UpdateAccessKey, so act as a different principal.

Leaked GitHub personal access token: delete it

Settings > Developer settings > Personal access tokens > Fine-grained tokens or Tokens (classic) > Delete. A deploy key the token created is deleted with it. GitHub automatically revokes a valid token pushed to a public repository or gist, not one in a private repo, a ticket or a vendor's hands. Found someone else's token? POST https://api.github.com/credentials/revoke takes up to 1,000 tokens per request, sent without authentication.

Compromised Google Cloud service account key: disable the key and the account

gcloud iam service-accounts keys disable KEY_ID \
  --iam-account=SA@PROJECT.iam.gserviceaccount.com --project=PROJECT

"The Google Cloud console can't disable keys", and disabling one does not revoke tokens already issued. Google's compromised-credentials guide: disable the service account or apply an IAM deny policy, wait "at least 60 minutes", then replace and delete the key. Tokens last one hour by default, but for service accounts your organization allows it, tokens created through the REST API can last up to 12 hours; there, the disabled service account or the deny policy is what protects you, not the wait. Google auto-disables publicly exposed keys by default, but that page also says: "Google Cloud doesn't guarantee that it will detect exposed keys."

Leaked Azure storage account key or SAS: renew both keys

az storage account keys renew --resource-group <rg> --account-name <acct> --key primary
az storage account keys renew --resource-group <rg> --account-name <acct> --key secondary

Renew both unless you can prove which leaked. Regenerating a key "revokes shared access signatures (SAS) that are generated based on that key" (Microsoft's key-management guide). If the leaked item is itself a user delegation SAS, run az storage account revoke-delegation-keys, which may take a short time to apply. A service SAS on a stored access policy dies when you change the policy (Microsoft's SAS overview). Our bucket post covers how long a SAS URL stays valid.

Compromised Stripe secret key: rotate with expiration Now

On the API keys page: overflow menu (⋯) > Rotate key, set Expiration to Now ("the old key is deleted"), then Rotate API key. Any later expiration keeps the leaked key working for up to 7 days. Rotate the webhook signing secret too, under Webhooks, if it sat in the same file.

Leaked OpenAI, Anthropic or Gemini API key: delete it

Spend is the visible risk, but a key also reads what you stored with the provider. OpenAI's Files API returns "the contents of the specified file"; at Anthropic, "Any API key with access to a workspace can access any files uploaded to that workspace." OpenAI: delete the key and contact Support; on the replacement, set a monthly limit with hard enforcement, because "Spend alerts alone don't stop API traffic." Anthropic: Claude Console > API keys > ⋯ > Delete API key. Gemini: Google documents a replace-first order. Our advice: if the key has no spending cap, delete it first anyway, since you can restore a deleted API key within 30 days, and restrict the replacement to the Generative Language API: "API restrictions specify which APIs can be called using the API key." Then scope each key as in Step 2.

Leaked Slack token: revoke it with auth.revoke

auth.revoke revokes the token that calls it; test=1 is a dry run. A user token (xoxp-) carries "the same access a user has to a workspace", so count every channel and file that person sees as read. A leaked incoming-webhook URL is not an API token, though its URL "contains a secret": remove that webhook in the app's settings and add a new one.

Step 2: scope the damage from the provider's own logs

Search the provider's audit log for the key's ID from when it first became visible (the commit, the day the file went public, the vendor's breach date), not from when you found it. Where a log never records an action, empty means unrecorded, not innocent: record each blind spot in the incident notes.

AWS: search CloudTrail for the key ID

Two cheap signals come first: GuardDuty findings, if it was on, and Cost Explorer grouped by Region and service from the exposure date, which AWS's unauthorized-activity guide lists; compute you never launched shows up there as cost. aws iam get-access-key-last-used gives the last-used date, service and Region. Then list what the key did in every Region:

for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
  aws cloudtrail lookup-events --region $r \
    --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIA... \
    --start-time <exposure>
done

In the results, find GetSessionToken, GetFederationToken and AssumeRole events, the three calls the recovery playbook searches for. Take the new access key ID in each event's response and run the same loop for it. These IDs start with ASIA, the prefix of temporary access key IDs, and every call made with the session is logged under that ID, not the AKIA one.

Event history keeps 90 days of management events per Region, and lookup-events allows 2 requests per second, so the loop is slow. IAM events land in us-east-1. The blind spot: event history "does not show data events", so S3 object reads appear only if a trail with data events was already recording. If the exposure is older than 90 days, query the trail's S3 logs (with Athena) or a CloudTrail Lake event data store, if one existed. If none did, those days cannot be reconstructed.

Google Cloud: filter the audit logs on the key name

In Logs Explorer, filter on the full key name (Google's service-account log examples):

protoPayload.authenticationInfo.serviceAccountKeyName="//iam.googleapis.com/projects/PROJECT_ID/serviceAccounts/SA_EMAIL/keys/KEY_ID"

App Engine and Compute Engine don't log the key name, so also search principalEmail for the service account. If the account could impersonate others, also filter on protoPayload.authenticationInfo.serviceAccountDelegationInfo.firstPartyPrincipal.principalEmail set to the leaked account, as Google's compromised-credentials guide says. Every service account it acted as is compromised too: disable it the same way. The blind spot: Data Access audit logs are disabled by default for every service except some BigQuery services, so Cloud Storage reads appear only if you had turned them on.

GitHub: search the security log and the audit log

A personal security log covers 90 days. For an organization, hash the token without putting it in your shell history:

read -rs T; printf %s "$T" | openssl dgst -sha256 -binary | base64; unset T

Then search the audit log for hashed_token:"VALUE", where your plan's audit log offers it. Clones and pushes appear only in an exported audit log.

Azure Storage: read StorageBlobLogs, if they exist

"Resource logs aren't collected and stored until you create a diagnostic setting" (Microsoft's Blob Storage monitoring guide). Without one before the leak, the reads cannot be reconstructed.

Stripe, Slack and the model APIs

Stripe: the key's ⋯ > View request logs. OpenAI and Anthropic: the usage pages, read from the exposure time; then list the files stored in the project or workspace and count them as read. At Anthropic, check every Workspace and any other Console organization for the same key, and contact Support if suspicious activity continues. Slack: team.accessLogs shows logins on paid plans, not the API calls a bot token made.

If the key reached personal data in the EU, GDPR Article 33(1) requires notifying the supervisory authority "without undue delay and, where feasible, not later than 72 hours after having become aware of it", unless the breach is unlikely to put people at risk. Stored files a model-API key could read count here too. Check whichever breach-notice rules cover your data and sector.

Step 3: hunt for backdoors the key created

Look for anything the key could have created that outlives it: users, keys, roles, SSH and deploy keys, workflows, webhooks, instances, buckets, and money that moved. Count every secret the key could read as leaked too.

On AWS, the AWSCompromisedKeyQuarantineV4 policy is AWS's own list of what an attacker does with a key. It denies, among others, launching instances, creating IAM users, keys, login profiles and roles, attaching and writing policies, lambda:CreateFunction, s3:PutBucketPolicy, ses:Send*, secretsmanager:GetSecretValue, ssm:GetParameter*, bedrock:InvokeModel and cloudtrail:StopLogging. Search the IAM calls by event name in us-east-1:

for e in CreateUser CreateAccessKey UpdateAccessKey CreateLoginProfile UpdateLoginProfile \
  AttachUserPolicy PutUserPolicy AddUserToGroup AttachGroupPolicy PutGroupPolicy \
  PutUserPermissionsBoundary CreateRole UpdateAssumeRolePolicy AttachRolePolicy \
  PutRolePolicy CreatePolicyVersion SetDefaultPolicyVersion \
  CreateServiceSpecificCredential ResetServiceSpecificCredential \
  CreateOpenIDConnectProvider CreateSAMLProvider; do
  aws cloudtrail lookup-events --region us-east-1 --start-time <exposure> \
    --lookup-attributes AttributeKey=EventName,AttributeValue=$e
done

Search RunInstances, RequestSpotInstances, ImportKeyPair, AuthorizeSecurityGroupIngress, CreateFunction, StopLogging, DeleteTrail, UpdateTrail, PutEventSelectors, GetSecretValue and GetParameter in every Region, and check the SES sending statistics (aws ses get-send-statistics) for mail you did not send. Look for destruction or ransom too: DeleteBucket, PutBucketVersioning, PutLifecycleConfiguration and ScheduleKeyDeletion, all on V4's list. S3 object deletes and overwrites are data events and need a trail. V4 lists more, ECS and SageMaker jobs among them. Treat any new access key ID as a new search handle.

If the key could read Secrets Manager, Parameter Store, Lambda configuration or a bucket of config files, treat every secret stored there as leaked and run these steps on each.

  • Google Cloud: "Check if new service account keys, new user accounts, or project-level SSH keys were created during the incident" (Google's compromised-credentials guide), plus VMs, buckets and Service Account Token Creator grants you didn't make, in this project and for every service account the leaked one impersonated.
  • GitHub: pushes and workflow changes on every repository the token reached (look hardest at .github/workflows), new or moved tags and releases, published package versions, changed branch protection or rulesets, new self-hosted runners, webhooks, collaborators and deploy keys, plus public_key and oauth_access entries in the security log. Each of these can reach the people who install your code. If the token could change workflow files, rotate every Actions secret in those repositories. A changed workflow can send its secrets anywhere, and you cannot prove it didn't.
  • Stripe: "unexpected charges, refunds, or connected accounts" (Stripe's compromised-keys page), payouts you didn't authorize, and webhook endpoints under Developers > Webhooks. A secret key can create webhook endpoints through the API: delete any you did not make.
  • Azure: "It's not possible to audit the generation of SAS tokens" (Microsoft's SAS overview), which is why Step 1 renewed both keys. Check each container's public access level too.

Some of this damage shows from the outside. A storage key can make a bucket public, and FortWatch's cloud check finds publicly listable S3, GCS and Azure Blob storage named from your domain or added as an asset (cloud exposure). It does not see IAM users, instances or Lambda.

Step 4: close the leak path

Once the key is dead, remove it from where it leaked. That is hygiene, not containment: the revoke in Step 1 is what protects you.

Why rewriting git history doesn't un-leak a key

GitHub's guide to removing sensitive data opens with "as a first step you need to revoke and/or rotate that secret." "You cannot remove sensitive data from other users' clones of your repository," forks keep the commit, and cached views by SHA and pull requests that reference it survive. For the same reason, making the repo private does not recall copies already made. If you rewrite anyway, GitHub recommends git-filter-repo with --sensitive-data-removal, and cached views go through GitHub Support. Google's service-account key best practices agree: "It's not sufficient to only delete the key from the source code repository."

The other leak paths

  • A file served from your own site. The server rule and the curl test are in our post on a public .env file. FortWatch's sensitive-files scanner checks 129 paths, from .env and .git/config to .aws/credentials and terraform.tfstate, and counts a finding only when the file comes back with matching content, so the next scan shows whether the path is closed.
  • A ticket or chat paste. Delete the message.
  • A vendor-held key. Issue a new one scoped to its one job.

Step 5: ship the replacement and prove the old key is dead

Put a narrower key everywhere the old one lived, then check that the old one fails. AWS's recovery playbook lists config files, environment variables, CI/CD secrets, ~/.aws/credentials, containers and third-party integrations.

  • AWS: make one call with the old key, for example aws sts get-caller-identity, and expect an authentication error instead of your account ID. aws iam list-access-keys --user-name <user> should show the key as Inactive. get-access-key-last-used belongs before a deactivation, as in AWS's rotation procedure: an inactive key cannot authenticate, so it records nothing new.
  • Google Cloud: gcloud iam service-accounts keys list --iam-account=SA@PROJECT.iam.gserviceaccount.com shows True under DISABLED for the old key (Google's key-listing docs).
  • Stripe: send one request with the old key and expect an authentication error.

Then watch the error logs of every app and job that held the old key for a day. A missed copy shows up there as authentication errors: give that system the new key.

When the leak is your vendor's

When a vendor that holds your credentials is breached, run the same five steps on every credential it held, and start the clock at its breach date, not at the email that told you.

Radware's November 2026 breach shows the pattern. BleepingComputer reported on 24 November 2026, citing Radware's root-cause report, that on 19 November 2026 an unauthorized party accessed "an internal-only Cloud WAF management API that was reachable from the Public Internet without requiring authentication". For some customers that put their log-export credentials within reach: AWS S3 access keys, Azure Blob keys or SAS tokens, and SFTP credentials. Per the report, Radware "strongly" advised affected customers to rotate them and review storage access logs since at least 19 November. Radware had made no public statement when BleepingComputer published. For SFTP, change the vendor account's password or remove its key, then read the server's authentication log from the breach date.

"Review access logs" assumes logs exist. S3 object reads are data events, not logged by default, and Azure Blob logs need a diagnostic setting (both in Step 2). Switch both on now for every bucket or storage account a vendor writes to.

Rotate every credential the vendor held, including the ones you believe are unused: that is Cloudflare's lesson from the top of this post. Leaked keys rarely die on their own: GitGuardian reported on 17 March 2026 (a vendor figure) that more than 64% of secrets confirmed valid in 2022 were still valid in January 2026.

Prevention: fewer long-lived keys, push protection, an inventory

Fewer long-lived keys. AWS says to "use temporary security credentials (such as IAM roles) instead of creating long-term credentials like access keys" (AWS's access-key guide); for Azure Storage, Microsoft's key-management guide recommends Entra ID with managed identities. For pipelines, see replacing CI secrets with OIDC.

Push protection. Push protection for users is on by default and stops your pushes of supported secrets to public repositories. Push protection for a repository is off by default (GitHub's push-protection docs): public repositories have it without a paid product, while private and internal organization repositories need GitHub Secret Protection (GitHub's Advanced Security overview). Turn it on everywhere your plan allows.

An inventory. One key per vendor and per system, scoped to its job: a dispute tool gets a Stripe restricted key with "read-only access to dispute-related resources". Rotate on a schedule as a drill: "Periodic rotation confirms that you know where each key is used and that your team can replace a key on short notice" (Stripe's key best practices).

Frequently asked questions

What should I do first if an API key is leaked?

Revoke or deactivate it at the issuer, then end every session minted from it (Step 1). Speed matters: Unit 42 reported on 30 October 2023 that the EleKtra-Leak campaign used AWS keys within five minutes of their exposure on GitHub. Investigation comes after.

Does deleting the commit remove a leaked secret from GitHub?

No. GitHub's guide says a history rewrite cannot reach other people's clones or forks, and cached views by commit SHA or pull requests that reference it need GitHub Support. Making the repo private cannot recall copies already made either. Revoke first.

Should I deactivate the old AWS key or create the new one first?

Deactivate first. AWS's playbook for an exposed key starts there: "Start here. This step contains the damage." A deactivated key can be reactivated. Creating the new key first is AWS's planned-rotation order; in a leak, we contain first.

Can a leaked key still be used after I revoke it?

Yes, through what it minted: AWS GetSessionToken credentials for up to 36 hours (one hour from a root key), Google access tokens for one hour by default, and a SAS signed with a leaked Azure storage key until it expires or the key is regenerated. A second key the attacker created keeps working on its own. End them all in Step 1.

What if a vendor that holds my keys is breached?

Treat each credential it held, SFTP logins included, as leaked from the vendor's breach date, not from the day it told you, and run the same steps on every one. Then give the vendor a narrower key.

What do I do with this?

Do these in order, in the first hour.

  1. Write down the exposure time and read the key's scope, group policies included, and every secret and stored file it could read.
  2. Revoke it at the issuer and end its sessions:
    • AWS: deactivate it and any key you did not create, attach the aws:TokenIssueTime deny, revoke role sessions, keep any quarantine policy. A root key: delete it as root, change the password, turn on MFA.
    • Google Cloud: disable the key and the service account, wait at least 60 minutes.
    • Azure: renew both account keys; revoke the user delegation keys only if a user delegation SAS leaked.
    • Stripe: Rotate key, Expiration: Now.
    • GitHub: delete the token.
    • Model APIs: delete the key, set a hard monthly limit on its replacement.
    • Slack: auth.revoke with the leaked token; a webhook URL gets removed and replaced.
    Close a live leak path right after.
  3. Pull the provider's logs from the exposure time, in every region or location the provider has, including the ASIA session IDs an AWS key minted, and write down what was never logged.
  4. Hunt for what the key created or destroyed: users, access keys, roles, policies, SSH or deploy keys, workflow changes, tags, releases, packages, runners, webhooks, instances, buckets, deleted data, refunds and payouts. Rotate every secret it could read and every Actions secret a workflow-capable token could reach.
  5. Clean up the leak path. A history rewrite is hygiene only.
  6. Ship a narrower replacement everywhere, confirm the old key fails, and watch your apps' error logs for a day for missed copies.

Then start the inventory, one row per secret, vendors included:

SecretWhere it livesWho holds itScopeOwnerLast rotatedRevoke command
AWS key for WAF log exportWAF vendor's log-export settingsWAF vendorWrite-only, one bucketOps leadYYYY-MM-DDaws iam update-access-key --access-key-id AKIA… --status Inactive --user-name waf-log-export

Most of this hour happens in your providers' consoles. The part an external attack surface scan watches is your own websites: the sensitive-files scanner checks that none of them serves a credential file, and alerts send each new critical finding to Slack or email when a scan finishes.

Share this post

Ready to secure your stack?

Secure your entire stack today

Start scanning in under 5 minutes. No credit card required. 7-day free trial included.