Secrets in Public Code Repositories: Find, Rotate, Clean Up
Skip to content

Secrets in Public Code Repositories

Secrets in public code repositories are passwords, API keys, tokens, private keys and connection strings that have been committed to code anyone on the internet can read.

On this page

The same repositories also carry customer records, internal hostnames and source code that were never meant to leave the organization. Most of these leaks sit outside the organization’s own accounts, in repositories owned by staff, contractors and vendors.

This guide covers how secrets reach public code, which kinds matter most, how to find and validate them, why rotation comes before cleanup, and how to prevent the next one.

How Secrets Reach Public Code

A secret usually reaches a public repository through ordinary work. A developer pushes a script to a personal account to keep a copy, or a test configuration goes up with real values in it. The repositories that cause trouble mostly belong to accounts the organization does not manage.

  • Staff personal accounts: Engineers and analysts keep side projects and backups on personal accounts, and company configuration files travel with them.
  • Vendor and contractor accounts: Agencies, integrators and freelancers publish client work by mistake, or build a portfolio from projects that still hold client credentials.
  • Former staff: Code written during employment stays on the personal account after the person leaves, along with any keys it holds.
  • Collaboration surfaces: Issues, pull request comments, wikis and build logs collect pasted error messages and tokens.

The US Federal Trade Commission has set out where this leads in two enforcement cases. In the first, the FTC described an access key with full administrative privileges that an engineer posted publicly on GitHub, which an intruder used in 2014 to take personal data about more than 100,000 people. In the second, the FTC’s complaint said an employee posted the company’s cloud credentials to a personal public repository in 2018, and the company’s servers were used to mine cryptocurrency until the company learned of it and changed the credentials.

The second case adds a lesson about personal accounts. Staff reached the company’s repositories through personal GitHub accounts, and an executive given access for a one-day event in 2018 kept it. In 2020 an attacker signed in to his account with credentials from an unrelated breach, found cloud and database credentials in a repository, and copied a user table of more than 2.5 million records.

AI Coding Assistants

AI coding assistants have widened the group of people who publish code. An operations analyst can now build a working internal tool in an afternoon and push it to a personal repository to share it.

Generated code tends to take the shortest path to working. A database password goes into a settings file and a sample export of real records into the project folder, and a person new to software has little reason to know the published folder carries both.

  • Credentials in generated code: Keys pasted into a prompt to make a script run end up written into the files the assistant produces.
  • Real data as test data: Spreadsheets and exports used to check the tool’s output are committed along with the code.
  • Publishing by new users: People who have never used Git create a public repository because it is the default, or because a tutorial told them to.
  • Agents that commit: Coding agents can create commits and repositories directly, so a secret may reach a public repository without a person reviewing the change.

GitHub Docs state that push protection also applies to interactions with the GitHub MCP server for public repositories, which covers agents that write through it. The wider answer is policy and monitoring, because many of these tools live on personal accounts the organization never sees.

History, Forks and Gists

Deleting a file from a repository removes it from the latest version and leaves it in the commit history. Anyone who clones the repository, or opens the old commit in a browser, can still read it.

Copies spread beyond the original repository as well. GitHub Docs state that commits pushed to any repository in a fork network can be accessible from other repositories in that network, and that this applies even after a fork is deleted. When a public repository is deleted, an active public fork becomes the new upstream, and when a public repository is made private, its public forks stay public in a separate network.

  • Commit history: Every earlier commit that held the secret keeps it, whatever a later commit deletes.
  • Forks: A fork made before the cleanup keeps its own copy of the history, owned by someone else.
  • Cached views and pull request references: GitHub Docs note that rewritten commits may remain reachable by their hashes in cached views and through pull requests that reference them.
  • Gists: GitHub Docs state that secret gists aren’t private, since anyone with the URL can view one, and public gists appear in Discover and in search.
  • Clones: Anyone who cloned the repository while the secret was there holds a full copy that no platform can reach.

Exposure therefore starts at the first push, and a secret public for an hour is treated as known.

Types of Exposed Secrets

Secrets differ in what they open and in who can rotate them. A cloud key with broad permissions is more urgent than a key for a test service with no data behind it.

Many platforms issue keys in a recognizable format, which makes them easier to find. GitHub Docs list a prefix for each GitHub token type, such as ghp_ for a classic personal access token.

Secret type Typical place in code What it can open Who rotates it
Cloud access keys Deployment scripts, infrastructure templates, CI settings Storage, compute and identity settings in the cloud account, up to full control Cloud administrator
Database connection strings Application settings files, backup scripts Read and write access to the data in that database Database owner
SaaS and payment API keys Integration code, sample projects Customer, billing or messaging data held by the provider Owner of the provider account
Source code platform tokens Build files, scripts that call the platform Private repositories, packages and pipelines The token’s owner, or an organization owner
Mail and SMTP credentials Notification code, contact forms Sending mail as the organization’s domain Mail administrator
Private keys and certificates Key files committed by mistake, container builds Server identity, signed sessions and encrypted traffic Certificate and key owner
Token signing secrets Application configuration Forged sessions for any user of the application Application owner
User passwords Test scripts, comments, sample configuration The account, and any other account where the password is reused The user, with the identity team

User passwords have a reach beyond the repository. A password found in code may also be in use on other services, and a sign-in check should follow, as our guide to infostealer response explains for credentials stolen by malware.

Data and Code Beyond Keys

A public repository can expose the organization without holding a single credential. Customer and staff records arrive as spreadsheets, database dumps and exports used for testing, and they raise a privacy question in place of a rotation task.

Code itself also tells an attacker a lot. Internal hostnames, network ranges, API routes and the names of internal projects show where the systems are and how they talk to each other.

  • Personal data: Customer lists, staff records and exports committed as test data can trigger notification duties under privacy law.
  • Internal hostnames and addresses: Names of servers, admin portals and staging systems give an attacker targets that may be missing from public DNS.
  • Proprietary source code: Application code shows how authentication and input handling work, which makes vulnerabilities easier to find.
  • Infrastructure definitions: Templates and configuration files describe the network, its firewall rules and the services exposed to the internet.

These findings go to different owners than a leaked key. Personal data goes to the privacy officer for an assessment, and hostnames and infrastructure details go to the team that runs the attack surface program.

Finding Leaks in Public Code

Finding leaks starts with the search terms. Domains, hostnames, internal project names, email formats and key formats tie a stranger’s repository to the organization.

Built-in search covers less than it appears to. GitHub Docs state that code search only supports the default branch and excludes files over 350 KiB, so older commits need the repository cloned and its full history scanned.

  • Organization accounts: Every repository, branch and commit in the organization’s own GitHub and GitLab groups is scanned, archived projects included.
  • Staff and vendor accounts: Public repositories owned by known developers and suppliers are searched for the organization’s terms.
  • History and forks: Each matching repository is scanned through its full history, and its forks are checked for copies.
  • Gists and paste sites: Public gists and paste sites are searched for the same terms, since short snippets are often shared there.
  • Issues and build logs: Issue threads and public build logs are included, because errors get pasted with their secrets.

The platforms also scan on their own. GitHub Docs state that secret scanning runs free and automatically for public repositories, across all branches and history, issues, pull requests, discussions, wikis and secret gists, and the partner program sends matches for a provider’s key format to that provider, which can revoke them.

GitLab Docs describe automatic revocation of leaked GitLab personal access tokens in public projects on GitLab Ultimate, with some cloud and SaaS providers notified of their keys. Each platform works only on code it hosts and patterns it knows, so neither tells an organization when a vendor’s repository holds its database password.

Validating a Found Secret

A match is a candidate until validation confirms whether the secret belongs to the organization, still works, and what it can reach.

The safest check runs from the owner’s side. Calling a service with a found key can itself be unauthorized access, so the check uses the organization’s own consoles and logs.

  • Ownership: The hostname, account ID or key identifier is matched to the organization’s own assets, since a match on a common word may belong to someone else.
  • Status: The provider’s console shows whether the key or account is active, disabled or already rotated.
  • Last use: Many providers record when a key was last used and from where, which shows at once whether someone else has tried it.
  • Permissions: The key’s roles or scopes show how far it reaches, from one test bucket to the whole account.
  • Exposure window: The commit date, and the date the repository became public, set the period that the log search has to cover.

GitHub Docs describe optional validity checks in secret scanning that show whether a detected secret is still active, which may involve contacting the issuing service. A result of active, with broad permissions and a recent last use from an unknown address, makes the finding an incident.

Some findings cannot be fully validated, such as a password for a system that keeps no record of failed attempts. Those are treated as live.

Rotation Before Cleanup

The first action on a confirmed secret is to revoke or rotate it. GitHub Docs advise rotating first because a revoked secret can no longer be used for access, and rewriting history is time-consuming and often unnecessary once that is done. GitLab Docs likewise say exposed secrets should be revoked and replaced as soon as possible.

Cleaning the repository first gets the order backwards. The secret has already been copied by anyone who saw it, and the NCSC’s guidance on securing HTTP-based APIs notes that attackers often scan public repositories for credentials and that secrets may be difficult to fully remove once committed.

  1. Revoke or rotate. The owner disables the secret, issues a replacement and stores it in a secrets manager in place of the code.
  2. Update what depends on it. Applications and pipelines that used the old secret are moved to the new one.
  3. Search the logs for use. Audit logs for the service the secret opens are searched across the whole exposure window, looking for activity from addresses and clients the organization does not use.
  4. Contain any misuse. If the search finds activity, the incident response process takes over, with sessions revoked and changes made by the intruder reversed.
  5. Clean the repository. History cleanup follows, to reduce further spread and remove personal data.

The log search is the step most often skipped. A rotated key stops future use, and only the logs show whether the key was used while it was public, and what was read or changed.

Cleaning Repository History

History cleanup removes the secret or file from every commit and replaces the published history. It reduces how long the data stays easy to find, and for personal data it is usually required.

GitHub Docs name git-filter-repo as the tool, with version 2.47 or later for its sensitive data removal option. They also list the side effects: every commit after the change gets a new hash, commit signatures are lost, diffs for closed pull requests that depend on the old history become unavailable, and any collaborator with an old clone can push the data back.

  • Coordinate first: Open pull requests are merged or closed and collaborators are told to stop pushing until the rewrite is done.
  • Rewrite and force push: The secret or file is removed from all branches and tags, and the cleaned history replaces the old one.
  • Ask for clones to be replaced: Colleagues delete old clones and clone again, because GitHub Docs state that data cannot be removed from other users’ clones.
  • Contact fork owners: Owners of forks are asked to delete or clean them, and GitHub notes it cannot provide their contact details.
  • Request platform cleanup: GitHub Support can remove cached views and pull request references and run garbage collection, though GitHub Docs say Support helps only where rotating credentials cannot mitigate the risk.

GitLab Docs describe redact text, which replaces exact strings with a marker and keeps the files, and remove blobs, which deletes whole files from history. Each rewrites history and cannot be undone.

When the repository belongs to a vendor or a former employee, the organization depends on that person to act. A written request should name the repository, the commits, the forks found and a date, and the vendor’s contract is the place where that duty should already be set out.

Records to Collect

Each leak leaves records in the repository, in the platform and in the systems the secret opened. Collecting them early matters, because a cleanup changes the repository and some logs expire.

Artifact What it settles Where it lives
Repository URL and commit hash Exactly where the secret was, and the version that contained it The platform’s commit page, saved with a screenshot before cleanup
Commit date, author and visibility change When the secret was published, from which account, and when the repository became public Commit metadata in the cloned history and the platform’s audit records
Fork list Who else holds a copy of the history The repository’s forks view on the platform
Key status and last use Whether the secret was active and when it was last used The issuing provider’s console for that key or account
Service audit logs Calls made with the secret during the exposure window, and from where The cloud provider’s audit log, database logs or the SaaS admin audit log
Sign-in logs Use of a leaked password for a directory account Microsoft Entra ID sign-in logs, or the identity provider’s equivalent
Push protection bypass records Who pushed a detected secret anyway, and the reason given GitHub alerts and audit log, or GitLab audit events for skipped secret push protection
Rotation and cleanup records When the secret was revoked and the history rewritten Change tickets, provider audit logs and the rewritten repository

A Leak Followed Through

One case at acme-corp shows the whole sequence, from a search match to a closed finding.

  1. Discovery. A search for acmecorp.com hostnames finds a public repository on a contractor’s personal GitHub account. It holds a reporting tool the contractor built with an AI coding assistant for acme-corp’s finance team.
  2. History scan. The current code reads its settings from environment variables. A commit from three months earlier holds a settings file with a cloud storage access key and a database connection string for reports.acmecorp.com, plus a sample export of customer records, all deleted in the next commit. The repository has one fork.
  3. Validation. The key identifier matches an access key in acme-corp’s cloud account. The console shows it active, with read access to every storage bucket, and last used two days earlier from an address that belongs to neither acme-corp nor the contractor.
  4. Rotation. The cloud administrator disables the key and issues a new one into the secrets manager, and the database owner changes the password. The contractor’s tool is moved to the new values the same day.
  5. Log search. The cloud audit log shows the unknown address listing the buckets and reading two files from a reports bucket. The database is reachable only from acme-corp’s network, and its logs show no outside connections.
  6. Containment and assessment. The incident team blocks the address and finds no permission changes. The privacy officer assesses the customer export and the two files against acme-corp’s notification duties.
  7. Cleanup. The contractor rewrites the history and force pushes, acme-corp asks the fork owner to delete the fork, and a request goes to GitHub Support to remove cached views.
  8. Prevention. The contractor’s work moves into acme-corp’s own GitHub organization behind single sign-on, with push protection turned on, and the contractor agreement gains a clause on code and credentials.

The current code looked clean, so the history scan found the leak. The log search then answered what the unknown address read, a question rotation alone would have left open.

Push Protection and Pre-commit Checks

Prevention works best before a secret reaches any server. Checks run on the developer’s machine, at the push and in the pipeline, and each catches what the earlier one missed.

GitHub Docs state that push protection blocks pushes containing secrets from the command line, the web interface, file uploads and the REST API. Anyone with write access can bypass a repository block by giving a reason, which raises an alert, and delegated bypass limits who may do so. Push protection for users is on by default for public repositories on GitHub.com, so it covers staff personal accounts unless the user turns it off.

GitLab Docs describe secret push protection on GitLab Ultimate, which blocks pushes with detected secrets and logs each skipped push as an audit event. It scans only the diffs of pushed commits, leaving secrets already in the repository to pipeline secret detection.

Control Where it runs What it stops What it leaves open
Pre-commit scanner The developer’s machine Secrets before they enter local history Machines where it was never installed
Push protection The code platform, at each push Known secret formats reaching the server Bypasses, unknown formats, and other platforms
Pipeline secret detection The build pipeline Secrets that reached a branch Exposure that already happened on a public repository
Secrets manager Runtime configuration The need to write secrets into code at all Scripts written outside the approved process
Public code monitoring Outside the organization Leaks in accounts the organization does not manage Code that was never public

The NCSC’s guidance to protect your code repository gathers the same ideas into one practice: separate secret credentials from source code, inject them through a defined process, rotate keys, and scan repositories for secrets automatically.

Policy for Staff and Vendors

Technical controls only reach the accounts and machines the organization manages. Policy carries the rules to personal accounts, contractors and the new builders who use AI assistants.

A good policy is short and makes reporting easy. Someone who pushed a key by mistake should be able to report it in minutes, with no penalty for the report, because rotation speed matters most.

  • Company code in company accounts: Work for the organization lives in its own GitHub or GitLab organization, reached through single sign-on with multi-factor authentication.
  • Secrets in the manager: Credentials are stored in the approved secrets manager and injected at runtime, never typed into code or prompts.
  • Push protection on personal accounts: Staff who use personal accounts for any work keep user push protection turned on.
  • Rules for AI tools: Staff building tools with AI assistants use test data in place of real records and ask before publishing anything that touches company systems.
  • Vendor clauses: Contracts require suppliers to keep client code private, report leaks within a set time, rotate on request and clean history when asked.
  • Leavers and access reviews: The NCSC advises revoking repository access swiftly when it is no longer needed and reviewing developer accounts periodically.

A developer’s GitHub password stolen by malware appears in stealer logs and opens every private repository the account can reach, so multi-factor authentication on personal accounts used for work belongs in the policy.

Starting a Code Leak Program

A first pass finds the leaks that already exist, and the following weeks set up the controls that stop new ones.

  • Week 1, the search list: The team lists its domains, hostnames, project names, email formats and key formats, and its own GitHub and GitLab groups. Known public accounts of developers and suppliers are added.
  • Week 2, the historical sweep: Organization repositories and the public repositories found for the search list are scanned through their full history, with forks and gists included. Each match is checked for ownership.
  • Week 3, rotation and log searches: Every live secret is rotated by its owner and the logs are searched across its exposure window. Personal data findings go to the privacy officer.
  • Week 4, controls: Push protection and pipeline detection are turned on for the organization’s repositories, and a pre-commit scanner is issued to developers. The most exposed static keys are moved to the secrets manager.
  • Weeks 5 and 6, policy and vendors: The policy is published, suppliers with code access are asked to confirm the new clauses, and history cleanup requests go out for the findings that need them.
  • After that, continuous monitoring: New public commits are watched as they appear, and the search list is updated whenever a domain, project or supplier is added.

Watching Public Code With ThreatDefence

For ThreatDefence customers, public code is watched by the Brand monitor agent across GitHub, GitLab, public gists and paste sites, with old commits read as closely as the latest files. It searches for the customer’s domains, hostnames and recognizable key formats, which is how a repository on a vendor’s or an employee’s personal account comes to light.

  • Keys and signing secrets: Every key is linked to the service it unlocks, and a token-signing secret is ranked near the top because whoever holds it can mint sessions for the application.
  • Records and hostnames: A spreadsheet or export of customer or staff records is raised as a data exposure, and files that name internal hosts go to review.
  • Rotation first: Once an analyst has confirmed a significant leak, the system’s owner gets a request to rotate the secret, and in monitored environments the SOC then works through the logs for the full period of exposure.
  • Removal: A phishing kit or fake app in a public repository goes to the Takedown agent, which contacts the code host once the customer approves.

Evidence that a secret was used turns the finding into an investigation by the 24x7 SOC. Brand monitoring describes the service.

Frequently Asked Questions

Does deleting a file remove a secret from a public repository?

No. Deleting a file removes it from the latest version only, and every earlier commit still contains it. Anyone who clones the repository or opens an old commit can read the secret, and forks and existing clones keep their own copies. Treat the secret as exposed from the first push, rotate it, and then rewrite the history if the data needs to be removed.

Is a secret gist private?

No. GitHub Docs state that secret gists aren’t private: they stay out of Discover and search, but anyone with the URL can view one. A link shared in a chat, a ticket or a browser history is enough to expose its contents. Code or configuration that must stay hidden belongs in a private repository with access control.

Should a leaked key be rotated before the history is cleaned?

Yes. Rotation stops the key from working, while cleanup only makes it harder to find, and copies may already exist. GitHub Docs advise rotating first and note that rewriting history is often unnecessary once the secret is revoked. After rotation, search the service’s logs across the exposure window to learn whether the key was used.

Does making a public repository private end the exposure?

No. GitHub Docs state that when a public repository is made private, its public forks stay public in a separate network. Anyone who cloned it while it was public also keeps a full copy. Changing visibility can limit further spread, but the secret still needs to be rotated and its use checked in the logs.

Do code platforms tell the provider when a key leaks?

Yes. For some key formats, GitHub’s partner program sends a match found in public content to the provider that issued the key, and the provider can revoke it. GitLab Docs describe revoking leaked GitLab personal access tokens in public projects on GitLab Ultimate and notifying some cloud and SaaS providers. Both cover only known formats on their own platform.

Does GitHub push protection cover personal accounts?

Yes. GitHub Docs state that push protection for users is enabled by default and stops a user from pushing detected secrets to public repositories on GitHub.com. A user can turn it off, it recognizes only supported secret formats, and it does nothing for personal data such as a spreadsheet of customer records, so policy and monitoring are still needed.

Can code written with an AI coding assistant leak secrets?

Yes. Assistants write whatever values make the code run, so a key pasted into a prompt often ends up in a settings file or script. People who build tools this way may also commit real data used for testing and publish to a personal public repository by default. Test data, a secrets manager and a rule to ask before publishing reduce the risk.

Who should rotate a secret found in a vendor's repository?

The owner of the account the secret belongs to rotates it. If the key opens the organization’s cloud or SaaS account, the organization’s administrator rotates it at once and does not wait for the vendor. The vendor is then asked to clean its history and forks, and to confirm in writing, which is easier when the contract already requires it.

Why watch repositories outside the organization's control?

Most leaks sit in accounts the organization cannot scan itself. Secret scanning checks repositories an organization owns or hosts for known secret formats, while public code monitoring watches repositories the organization does not control, including staff, former staff and vendor accounts, for its domains, hostnames and project names as well as its keys. It finds leaks that platform scanning would only report to the repository’s owner, or never report at all.

Talk to Our Experts

See how ThreatDefence automates security monitoring, compliance and cyber risk management in one platform.

    I'm an MSP, MSSP, or reseller

    By submitting this form, you accept the terms in our privacy policy.