Skip to content
Back to Blog
·9 min read·technology

Secrets Management: Stop Leaking API Keys and Passwords

Secrets management stops leaked API keys, tokens, and DB passwords before they happen — see how vaults, rotation, and pre-commit scanning prevent breaches.

BR

Bachao.AI Research Team

Cybersecurity Research

Scan Your Attack Surface

Security exposure this creates

Unpatched vulnerabilities in your tech stack are the #1 entry point for breaches targeting Indian businesses. Here's what to watch.

Secrets management is the practice of generating, storing, injecting, rotating, and revoking API keys, database passwords, cloud credentials, and tokens so they never sit in plaintext in code, git history, CI logs, or environment files. Most leaks happen because a developer hardcoded a key "just for now," committed it, or pasted it into a Slack thread or CI log — and it was never rotated. The fix is a secret manager (Vault, AWS/GCP/Azure Secrets Manager), short-lived credentials injected at runtime, pre-commit scanning, and a tested leak-response playbook.

If your team's secrets live in .env files checked into git, in Jenkins/GitHub Actions logs, or hardcoded in a config file "temporarily," you are one public repo, one misconfigured bucket, or one compromised laptop away from a credential-based breach.

Why Secrets Leak So Often

Secrets sprawl is not a niche mistake — it is one of the most common root causes of cloud breaches globally. Verizon's Data Breach Investigations Report has repeatedly identified stolen or leaked credentials as a leading initial access vector across confirmed breaches, and independent secret-scanning research from GitGuardian's annual State of Secrets Sprawl report has documented millions of hardcoded secrets found in public GitHub commits every year, with the trend rising, not falling.

The pattern is almost always the same:

    1. Hardcoded in source. A developer pastes an API key directly into a config file or test script to unblock local development, intends to remove it before commit, and forgets.
    2. Committed to git. Once a secret hits a commit, it is in history forever unless the repo is rewritten — git rm does not remove it from earlier commits, and most engineers don't know that.
    3. Public repos and forks. A private repo secret leaks the moment someone forks it, makes it public by mistake, or a contractor's access to a private repo is never revoked.
    4. CI/CD logs. Build pipelines routinely echo environment variables for debugging, or a badly configured step dumps the full environment to a log that's visible to every contributor with CI read access — sometimes to the public if the pipeline is misconfigured.
    5. Misconfigured storage. Secrets dropped into an S3 bucket, a shared drive, or a Notion doc "temporarily," with the bucket or doc never locked down.
    6. Long-lived static credentials. Cloud access keys and database passwords that are created once and never rotated remain useful to an attacker indefinitely — a two-year-old leaked key is just as valid as a two-day-old one if nobody rotated it.
🚨
DANGER
A secret committed to a public GitHub repository is typically discovered by automated scanners within minutes, not days. Bots continuously scan public commits for API key patterns (AWS AKIA, Stripe sk_live, Slack tokens, database connection strings) and attempt to use them immediately. There is no window to "quietly fix it later."

The Secret Lifecycle — Where Teams Skip Steps

A secret should move through a defined lifecycle. Most leaks happen because teams skip the storage and rotation stages and go straight from "generate" to "hardcode."

graph TD A[Generate secret] --> B[Store in vault or KMS] B --> C[Inject at runtime] C --> D[Rotate on schedule] D --> E{Leak detected} E -->|No| C E -->|Yes| F[Revoke immediately] F --> A G[Hardcode in source] --> H[Commit to git] H --> I[Public exposure] style A fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style B fill:#1e3d2f,stroke:#10B981,color:#e2e8f0 style C fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style D fill:#1e3d2f,stroke:#10B981,color:#e2e8f0 style E fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style F fill:#1e3d2f,stroke:#10B981,color:#e2e8f0 style G fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0 style H fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0 style I fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0

The healthy path (top row) treats a secret as a managed asset with an owner, an expiry, and a revocation path. The failure path (bottom row) treats it as a string of text pasted wherever it's convenient — and once it hits step I, the organization no longer controls where it has been copied.

Where Leaked Secrets Actually Come From

Across public-repo scanning research and incident postmortems, a handful of sources account for the overwhelming majority of secret exposure. This is qualitative — treat the proportions as directional, not a precise industry-wide census, since exact splits vary by report and methodology.

pie title Common Sources of Leaked Secrets (Qualitative) "Public git repos and history" : 35 "Hardcoded in application code" : 25 "CI/CD logs and pipeline configs" : 20 "Misconfigured storage (buckets, drives)" : 12 "Shared docs, chat, tickets" : 8
Up to 250 croreMaximum DPDP Act penalty for failure to implement reasonable security safeguards, including credential protection (MeitY, DPDP Act 2023)
6 hoursMandatory CERT-In window to report cyber incidents, including credential compromise (CERT-In 2022 Directions)
🛡️
SECURITY
Credential-based attacks don't need a zero-day. A valid, unrotated AWS key or database password lets an attacker walk in through the front door with no exploit at all. This is why secrets hygiene is consistently rated among the highest-leverage, lowest-effort security investments a dev team can make.

Know your vulnerabilities before attackers do

Run a free VAPT scan — takes 5 minutes, no signup required.

Book Your Free Scan

Fix 1: Use a Secret Manager, Not Environment Files

.env files are convenient for local development but are routinely committed by accident, synced to personal laptops, and copied into Docker images. Production secrets belong in a purpose-built secret manager:

    1. HashiCorp Vault — self-hosted or Vault Cloud, strong for teams needing dynamic secrets (database credentials generated on demand, expiring automatically) and fine-grained access policies.
    2. Cloud-native managers — AWS Secrets Manager / Systems Manager Parameter Store, Google Secret Manager, Azure Key Vault. These integrate directly with IAM, support automatic rotation for supported services (like RDS), and avoid standing up separate infrastructure.
    3. KMS-backed envelope encryption — for secrets that must live in a config store, encrypt them with a cloud KMS key so the stored value is ciphertext, not plaintext, and access is auditable through KMS logs.
The core principle: secrets are fetched at runtime by an authenticated service identity (an IAM role, a Vault AppRole, a workload identity), not read from a file that sits on disk or in source control.

Fix 2: Prefer Short-Lived Credentials Over Static Keys

A static, long-lived API key or database password is a permanent liability from the moment it's created — it's valid until someone remembers to rotate or revoke it, which in practice can be years. Short-lived credentials shrink that window dramatically:

    1. Cloud IAM roles with temporary STS tokens instead of static access keys, wherever the workload supports it (EC2 instance roles, ECS task roles, GCP workload identity, Azure managed identities).
    2. Database credentials issued dynamically by Vault or a cloud secrets manager, valid for a bounded TTL (minutes to hours), auto-expiring without manual cleanup.
    3. OAuth tokens with short expiry and refresh flows instead of permanent API keys, for service-to-service calls where the provider supports it.
💡
TIP
If a credential type doesn't support short-lived issuance (some third-party SaaS API keys don't), compensate with aggressive scheduled rotation — every 30-90 days at minimum — rather than leaving it static indefinitely.

Fix 3: Catch Secrets Before They're Committed

Pre-commit and pre-push scanning stops the majority of accidental commits before they ever leave a developer's machine, which is far cheaper than cleaning up after a public leak.

ControlWhat it catchesWhere it runs
Pre-commit hook scanner (e.g. detect-secrets, gitleaks)Hardcoded keys, tokens, private keys before commitDeveloper's local machine
CI pipeline secret scanAnything that slipped past local hooks, including PR diffsCI job on every push/PR
Repo-wide history scanSecrets already committed in past historyScheduled job or one-time audit
Public exposure monitoringSecrets discovered by external scanners on public reposContinuous, via provider or GitHub secret scanning
CI log redactionSecrets accidentally echoed or dumped in build logsCI platform configuration
Most CI platforms (GitHub Actions, GitLab CI) now offer built-in secret masking that redacts registered secret values from logs automatically — this must be explicitly configured, not assumed to be on by default for every variable.

Fix 4: Rotate on a Schedule, Not Just After an Incident

Rotation should be routine, not reactive. A practical rotation cadence:

  1. Cloud IAM access keys — eliminate static keys where possible; where unavoidable, rotate every 90 days.
  2. Database passwords — automate rotation via the cloud provider's native integration (e.g. AWS Secrets Manager's RDS rotation Lambda) rather than manual resets.
  3. Third-party API keys (payment gateways, SMS/email providers, analytics) — rotate on the provider's supported cadence, and immediately on any team member offboarding who had access.
  4. CI/CD service tokens — scope narrowly to the minimum required permissions and rotate whenever a pipeline's access needs change.
⚠️
WARNING
Rotation without updating every consumer of the old secret causes production outages, which is why teams avoid it. The real fix is automating rotation end-to-end (secret manager updates the value, dependent services pull the new value automatically) rather than treating rotation as a manual, risky event to be postponed indefinitely.

Fix 5: Detect and Respond When a Secret Leaks

Even with strong prevention, assume a secret will eventually leak — through a contractor's laptop, a misconfigured repo visibility setting, or a dependency compromise. Response speed determines the blast radius.

  1. Detect — public GitHub secret scanning, GitGuardian-style continuous monitoring, or your own scheduled repo-history scans surface the exposure.
  2. Revoke immediately — disable the credential at the source (IAM console, database user, provider dashboard) before investigating root cause. Revocation is reversible if it turns out to be a false alarm; delay is not.
  3. Rotate and reissue — generate a new credential and redistribute it through the secret manager, not by re-hardcoding.
  4. Audit usage logs — check cloud audit trails (CloudTrail, GCP Audit Logs) or database access logs for any activity on the exposed credential between exposure and revocation.
  5. Purge from history — rewrite git history to remove the secret from past commits (tools like git filter-repo or BFG Repo-Cleaner), understanding this doesn't undo any prior public exposure but prevents ongoing discovery.
  6. Post-incident review — identify why the secret was hardcoded or committed in the first place, and close that gap (missing pre-commit hook, missing secret manager adoption for that service, missing offboarding step).
🎯Key Takeaway
Secrets leak because they're treated as configuration convenience rather than managed assets. The fix isn't a single tool — it's a lifecycle: generate into a vault, inject at runtime with short-lived credentials, scan before every commit, rotate on a schedule, and have a tested revoke-and-rotate playbook ready before the first leak, not after.

Building Secrets Management Into an Indian Dev Team's Workflow

For most Indian startups and mid-size dev teams, the realistic adoption path is incremental, not a big-bang migration:

    1. Start with pre-commit secret scanning (gitleaks or detect-secrets) — it's free, takes under an hour to wire into a repo, and immediately stops new leaks.
    2. Move production secrets for your most critical services (payment gateway keys, database credentials, cloud access keys) into a cloud-native secrets manager first; it requires no new infrastructure if you're already on AWS, GCP, or Azure.
    3. Enable your CI platform's built-in secret masking and audit which pipeline steps print environment variables.
    4. Run one repo-history scan across your active repositories to find what's already leaked, then rotate everything it finds — assume anything found has already been seen by an automated scanner if the repo was ever public, even briefly.
    5. Add credential exposure to your incident response plan as a named scenario with an owner, not an edge case improvised on the day it happens.
This is exactly the kind of control gap a structured vulnerability assessment surfaces — exposed credentials, overly permissive IAM roles, and missing rotation policies are common findings in a free VAPT scan. Bachao.AI's automated platform, built by Dhisattva AI Pvt Ltd, checks for exposed secrets and credential hygiene issues as part of its broader assessment, alongside the DPDP-relevant data protection controls covered on the Bachao.AI blog.

Sources: MeitY, Digital Personal Data Protection Act 2023 (meity.gov.in), CERT-In Directions under Section 70B (cert-in.org.in), NIST Cybersecurity Framework and secure credential guidance (nist.gov).

Frequently Asked Questions

What is the fastest way to find secrets already committed to our git history?
Run a dedicated secret-scanning tool (gitleaks or truffleHog are common open-source options) against your full repository history, not just the current branch. This surfaces hardcoded keys, tokens, and passwords committed at any point in the past, even if they were later removed from the latest commit.
Does deleting a file with a secret in a new commit remove it from git history?
No. The secret remains recoverable in every earlier commit that included it. You need to rewrite history with a tool like git filter-repo or BFG Repo-Cleaner, and even then, treat the secret as compromised and rotate it — history rewriting prevents future discovery, it doesn't undo past exposure.
Should we use Vault or a cloud-native secrets manager like AWS Secrets Manager?
If you're already committed to a single cloud provider, the native secrets manager is usually the lower-friction choice since it integrates directly with IAM and supports automatic rotation for services like RDS. Vault is worth the added operational overhead when you need multi-cloud support, dynamic secret generation across many secret types, or very fine-grained access policies.
How often should database passwords and API keys be rotated?
Automate rotation wherever the provider supports it, ideally on a 30-90 day cycle for anything that can't be made short-lived. Credentials that support short-lived, dynamically issued access (minutes to hours) are preferable to any fixed rotation schedule, because there's no static value sitting around to leak in the first place.
What should we do the moment we discover a leaked API key in a public repo?
Revoke the credential immediately at the source before doing anything else — investigation and root-cause analysis can happen after the exposure window is closed. Then rotate and reissue through your secret manager, audit access logs for any activity during the exposure window, and purge the secret from git history.
Can CI/CD pipelines leak secrets even if we never commit them to code?
Yes. A common cause is a build step that prints environment variables for debugging, or a misconfigured log level that dumps the full runtime environment into CI logs visible to all contributors. Enable your CI platform's built-in secret masking for every registered secret and audit pipeline steps for accidental echoing.
BR

Bachao.AI Research Team

Cybersecurity Research

AI-powered security research and threat intelligence from the Bachao.AI team. Covering the latest vulnerabilities, CVEs, and cybersecurity developments affecting Indian businesses.

Get cybersecurity insights for Indian SMBs

Weekly vulnerability alerts, DPDP compliance tips, and security guides. No spam — unsubscribe anytime.

We respect your privacy. Your email is never shared.

Find out if you're exposed to this class of threat

Free automated scan — risk score in under 2 hours. No credit card required.

Scan Your Attack Surface
Find your vulnerabilitiesStart free scan →