Developer & Technical Security 10 min read

What to Do If an API Key or Secret Is Exposed

Accidentally committing a secret to Git, exposing a token in CI/CD logs, or leaking a credential in a screenshot requires immediate, structured action. Here is a defensive response framework for revoking, rotating, and remediating exposed application secrets.

The Defensive Response Framework

This is an editorial response framework designed to prioritize harm reduction and system recovery, not a formal regulatory or incident-response standard. When an application credential, API key, token, webhook secret, or database password is leaked, follow these core phases in sequence:

1. Assume Exposure

Treat the credential as potentially compromised the moment it appears in an insecure channel.

2. Revoke or Rotate

Invalidate or regenerate the credential and verify the old secret is no longer usable.

3. Update Dependencies

Deploy replacement secrets to legitimate production runtimes, CI/CD, and scheduled workloads.

4. Find Spread & Review

Identify caches, clones, logs, and activity records for unauthorized requests.

Do Not Rely on Deleting the Secret Alone

The most common mistake after discovering an exposed credential is to immediately delete the file, push a quick git commit that removes the line, or delete a chat message, assuming the problem is solved. If a credential may have been exposed, revoke or rotate it where possible rather than relying only on deleting the visible copy.

Once a credential has traveled over an insecure network, appeared on an external monitor, or landed in a shared repository, you must assume that automated scanners, web crawlers, log aggregators, or unintended recipients may have already recorded it. Deleting the visible text removes the evidence from view, but the secret itself remains functional until the issuing service explicitly invalidates it.

Revoke or Rotate / Regenerate First

Your primary defensive priority is terminating the validity of the compromised secret. Understanding the core technical approaches helps you plan the fastest route to recovery:

Revoke

Revocation immediately deactivates the key at the provider level, causing any request using that key to fail instantly. Revocation is the most direct way to stop unauthorized use if the compromised credential is high-privilege, if active abuse is suspected, or if the workload can tolerate temporary downtime while replacements are configured.

Rotate / Regenerate

Rotation involves generating or regenerating a replacement credential, deploying it across legitimate dependent workloads, and verifying that the old credential is deactivated and no longer usable. In environments or providers that support concurrent active keys, a temporary overlap period is one workload-specific pattern to transition services smoothly; where dual keys are not supported, direct revocation followed by immediate redeployment of the regenerated key is standard.

Update Legitimate Dependent Systems

Before or immediately following revocation, catalog all services and workflows that depend on the credential to prevent unintended outages. Common systems that require credential updates include:

  • Production Application Runtimes: Web servers, backend API instances, container clusters, and background workers.
  • CI/CD Automation: Build pipelines, automated deployment runners, test runners, and container registries.
  • Scheduled Jobs & Lambdas: Cron tasks, serverless functions, database migration scripts, and backup utilities.
  • Third-Party Webhooks & Partners: External SaaS integrations, payment processors, and partner API endpoints.

Git Repository Exposure: History, Public vs. Private

Committing a secret to a Git repository is one of the most common exposure channels. Deleting a later line or making a subsequent commit that removes the secret merely updates the repository’s working tree; it does not necessarily remove the secret from Git history, reflogs, or existing clones.

Official GitHub documentation on removing sensitive data emphasizes that once a commit containing a sensitive credential has been pushed to a remote server, you should consider it compromised. While history rewriting can reduce residual exposure in future clones, history cleanup does not restore trust in an exposed credential and does not replace revocation or rotation, because anyone who fetched or cloned the repository while the secret was present may retain an intact copy.

Credentials Committed to Private Repositories

A real credential committed to a private repository should still be treated as potentially exposed. Consider who and what had repository access, including users, CI/CD systems, integrations, clones, and artifacts. Revocation or rotation is generally safer than relying on repository privacy or deleting the commit alone. For preventative storage patterns, see our guide on how to store API keys and secrets safely in development.

Exposure in Logs, Error Messages, and CI/CD Pipelines

Secrets frequently leak through verbose logging statements, unhandled exception traces, curl commands with verbose flags, or debug scripts in CI/CD pipelines.

Application & Error Logs

When an application prints a secret during an exception or prints request payloads to standard out, rotate the credential at the issuing service. Identify where logs are forwarded (cloud aggregators, monitoring dashboards, APM tools, third-party log providers) and use log redaction or retention settings where supported. Recognize that log deletion mechanisms rarely purge cold-storage backups immediately.

CI/CD Build Logs & Artifacts

Build runners may output environment dumps or print executed shell commands. Rotate the credential, update the pipeline secret store, and inspect build output permissions. While platform secret masking helps redact known secret strings from pipeline stdout, it is an imperfect defense-in-depth measure that fails if the secret is base64-encoded, fragmented, or transformed.

Frontend and Client-Side Bundles

Any code, configuration, or environment variable delivered to a web browser, iOS app, or Android package is publicly readable. If a privileged server-side secret (such as a database connection string, an administrative API key, or a private signing secret) is bundled into frontend JavaScript, shipping a new build does not make the old key safe. The old bundle may be cached by intermediate proxies, CDNs, archive bots, and browser caches.

Rotate the privileged credential immediately and re-architect the application so that privileged API operations occur on an authenticated backend server. Distinguish privileged server keys from intentional public client identifiers (such as public analytics tracking IDs or restricted map tile keys) that are designed to be client-accessible and defended via domain whitelisting.

Screenshots, Chat Channels, Tickets, and Container Images

Screenshots, Chat & Support Tickets

When a secret is captured in a screen share, posted to a Slack or Discord channel, or included in an external support ticket, assess who has access to the channel or ticket queue. While editing or deleting the message reduces ongoing visibility, it cannot remove the credential from email notifications, local device notifications, or user caches. Rotate the credential where active privileges exist.

Container Images & Build Layers

Baking a credential into a Dockerfile or container image layer embeds the secret in the image manifest. Overwriting or deleting the file in a subsequent build step does not purge it from earlier layers. Rotate the credential, rebuild the image using runtime secret injection or multi-stage build secrets, and delete affected tags from private or public container registries.

Review Activity and Evaluate Privilege Scope

Once revocation or rotation is underway, inspect the activity history associated with the exposed credential. Most major cloud platforms and SaaS providers offer audit logs, API usage dashboards, or access history:

  • Inspect Usage Metrics: Check request counts, geographic origin of IP addresses, unexpected user-agent headers, and anomalous spikes in API calls.
  • Audit State Changes: Check for unauthorized IAM role modifications, newly generated secondary API keys, newly invited user accounts, or changes to billing and compute instances.
  • Understand Logging Limits: Log availability varies widely by provider, and absence of suspicious logs does not conclusively prove a credential was never accessed. Treat the credential itself as compromised regardless of log findings.
  • Determine Scope: Evaluate the exact permissions of the key. A strictly read-only key with granular resource limits represents a narrower blast radius than a write-privileged database password or account-wide administrative token.

Related Credentials and Short-Lived Tokens

Examine whether additional credentials were exposed in the same context. If an entire .env file or configuration directory was leaked, every secret in that file must be evaluated and rotated. Similarly, assess whether passwords or signing secrets were reused across other staging, test, or production environments. Avoid indiscriminate mass-rotation across unrelated infrastructure, but thoroughly rotate all secrets that shared the exposure boundary.

If the leaked secret is a short-lived session token (such as an OAuth access token or temporary STS token), check its configured time-to-live. While the token may expire automatically within minutes or hours, review whether it allowed the bearer to generate secondary persistent credentials, deploy background tasks, or establish persistent sessions before expiring.

Secret Scanning and Preventing Recurrence

Secret scanning tools (such as pre-commit hooks, CI/CD pipeline actions, and repository security scanners) can detect supported secret patterns and known provider token formats. However, detection is not exhaustive. Scanners rely on defined regular expressions and specific partner signatures; they cannot detect every arbitrary password, custom token, or unconventional string. A clean scan does not prove that no secrets exist.

To prevent future credential exposures, adopt defense-in-depth practices:

Centralized Secret StoresUse dedicated cloud secret managers (such as AWS Secrets Manager, HashiCorp Vault, or Google Secret Manager) to avoid storing credentials in static configuration files.
Workload IdentityAdopt short-lived IAM roles, workload identity federation, or instance profiles where supported to eliminate long-lived static API keys.
Granular ScopingIssue API keys with the minimum required privileges (least privilege) and restrict keys by IP address or HTTP referrer where available.
Strict Git Ignore RulesMaintain robust .gitignore configurations and use sample templates (like .env.example) with placeholder values.

Specialized Workflows: SSH Keys and Account Handoffs

Different credential types follow specific revocation patterns:

Response Priorities by Exposure Location

Exposure LocationFirst PriorityImportant Limitation
Git commit (public or private repository)Revoke or rotate credential at issuing provider; update authorized workloadsRewriting Git history does not invalidate the secret or recall existing clones
CI/CD build logsRotate credential; update pipeline secrets; remove verbose echo commandsLog aggregators and build archives may retain plaintext copies indefinitely
Frontend / client bundleRotate privileged secret; move logic to backend authenticated APIDeploying a new frontend bundle leaves the exposed secret active on the server
Screenshot / chat / ticketRotate credential; delete message to limit further visibilityMessage deletion cannot retract email alerts or recipient screenshots
Container image / layerRotate secret; rebuild image using build secrets; delete affected tagsImage deletion from a registry does not remove previously pulled layers from nodes

Incident Checklist: If an API Key or Secret Was Exposed

What specific credential was exposed (API key, webhook secret, database password, token)?
Is the credential currently active in production, staging, or development?
Can you revoke or rotate it immediately in the provider console or CLI?
What authorized workloads, services, and scheduled jobs depend on this credential?
Exactly where was the secret exposed (Git commit, CI/CD log, error trace, screenshot, client bundle)?
Who had access to that location (public repository, internal team, build system, external vendor)?
Are residual copies present in commit history, log aggregators, artifacts, or chat notifications?
What permissions and scope did the credential have (read-only, write, billing, full admin)?
Is there an audit log or API access history available to review for unauthorized activity?
Were other credentials or sensitive files exposed in the same file, commit, or screenshot?
Have authorized dependent applications and CI/CD pipelines been updated with the replacement?
Have you fixed the root cause to prevent future exposure (pre-commit hooks, secret stores, ignored files)?

Authoritative Security Sources

OWASP (Open Worldwide Application Security Project)Secrets Management Cheat Sheet

Supports the principle that exposed secrets must be revoked or rotated immediately, that deleting a committed secret does not remove it from history or clones, and that credentials must be scoped and separated by environment.

Warns that once a commit containing a sensitive credential has been pushed, you should consider it compromised; deleting the commit or rewriting Git history does not revoke the credential, and anyone with access may have already cloned or copied it.

GitHub SecurityAbout secret scanning

Explains that secret scanning can detect supported secret patterns and partner token types in repositories, but detection is not exhaustive and a clean scan does not prove no secrets exist. Provider notification and automatic remediation vary by partner and repository configuration.

Where Paste & Purge Fits

Paste & Purge has a very narrow, specific role in developer credential workflows. It can help transmit an authorized temporary text secret (such as handing off a replacement API token or initial temporary credential to a colleague) through a zero-knowledge encrypted link with a configured expiration and view limit, preventing the secret from lingering indefinitely in persistent chat or email history.

Paste & Purge does not revoke leaked credentials, rotate API keys, invalidate tokens, scan repositories, remove Git history, inspect server logs, investigate security incidents, manage IAM policies, or determine whether an exposed secret was exploited. Using a burn-after-reading link reduces ongoing storage persistence, but it does not prevent an authorized recipient from copying, saving, or screenshotting decrypted text; it does not prove a secret was not exposed elsewhere; it cannot revoke an underlying API key or token; and while the server record is purged after viewing or expiration, it cannot permanently erase copies stored outside the service. If an active credential was exposed, you must revoke or rotate it directly within the issuing provider or service.

Frequently Asked Questions