Your Secrets Are Probably Leaking : Follow this to fix it
From the publisher’s feed, collected in the ZeroLabs newsroom.
Your Secrets Are Probably LeakingPart 1 of 5 — Machine identity, credential sprawl, and why most teams discover the problem too late.Most teams spend months hardening user authentication and still ship applications with passwords in .env files, CI variables, Terraform state, and container manifests. The result is a second identity plane — one that often has weaker controls, weaker auditability, and a much larger blast radius than user auth ever had.A valid token proves who a user is. A secret proves who a service is.These are not the same problem. And most teams have solved only one of them.This article covers:What a secret really is — and why not all secrets are passwords.Why credential sprawl happens and compounds silently.Why environment variables are a delivery mechanism, not a security system.Why Kubernetes Secrets are not the same as secret management.Why Secret Zero exists and how modern platforms solve it with identity.The six design principles behind modern secret management platforms.Defenses you can apply today, without a full platform rollout.The Hidden Security ProblemConsider a typical application.The user authenticates to the application. That part is usually well-designed — MFA, OAuth, rate limiting, the works.But how does the application authenticate to the database?Usually with a credential:Username + passwordAPI keyPrivate key or certificateService account tokenCloud IAM role assumptionThat credential must exist somewhere. And “somewhere” tends to multiply.Common locations where credentials end up:Environment variables set in shell profiles.env files committed before .gitignore was updatedConfiguration files: application.yml, settings.py, database.jsonGit repositories — including commit history long after the file was deletedCI/CD variable stores: GitHub Actions secrets, GitLab CI variables, Jenkins credentialsContainer images — including intermediate layer caches from multi-stage buildsKubernetes SecretsTerraform state files, often stored in S3 or Terraform CloudBuild logs and CI job outputDeveloper laptops and local shellsEvery copy increases the attack surface. Every copy is a potential breach point.The Credential Propagation ProblemA single database password often spreads further than anyone on the team realizes.Once a secret is copied, teams quickly lose confidence in answering basic questions:Who has access right now?Which copy is authoritative?Has it been rotated — everywhere?Did it leak into logs or crash dumps?Can it be revoked without breaking production?Usually the honest answer to all five is: we don’t know.Why Attackers CareLeaked secrets are valuable because they provide direct system access without needing to exploit a software vulnerability first. No CVE. No patch window. No exploit chain.Time-to-exploit for a secret published to a public GitHub repository is measured in seconds, not hours. Automated bots continuously scan public repositories and attempt to use credentials immediately upon discovery.What Is a SecretA secret is any sensitive value used to authenticate, authorize, encrypt, or establish trust between systems.Two important distinctions:Certificates are not secrets. A TLS certificate is a public artifact — it’s transmitted to every client that connects to your server. The private key is the secret. Losing a certificate is inconvenient. Losing the private key is a security incident.Not all secrets are passwords. Some represent identity (service account tokens). Others represent cryptographic trust (signing keys). Others represent authorization scope (API keys scoped to specific resources). These distinctions matter because the controls for managing a static password are different from the controls for issuing short-lived certificates or dynamic database users.Why Traditional Approaches FailMost systems start simply. A few environment variables, a shared database user, maybe a .env file checked into the repository "temporarily."DB_HOST=postgres.internalDB_USER=app_userDB_PASSWORD=password123That pattern does not stay contained. Here is why.Problem 1: Long-Lived CredentialsThe lifecycle of most credentials looks like this:Created → Used → Forgotten → Never RotatedMonths — or years — later, they are still:ValidShared across multiple consumersOverprivileged for what they actually needPoorly tracked (who created this? for which system? when does it expire?)Not covered by offboarding processes when engineers leaveAttackers prefer credentials that never expire. Most production credentials oblige them.Problem 2: Shared IdentitiesMany services share the same credential because sharing is easier to set up than issuing separate credentials per service.The consequences compound:No accountability. Audit logs show app_user, not which service made the query.No traceability. Impossible to attribute a suspicious query to a specific service.Overprivilege by default. The shared user needs the union of every service’s permissions.Large blast radius. Compromising Service C potentially exposes data that only Service A should access.Coordinated rotation required. All services must update simultaneously when the credential changes.If one service is compromised, every service sharing that credential is suspect.Problem 3: Rotation Becomes Operationally RiskySuppose the database password needs to change. Every dependent system must update in a coordinated window.The dual-validity window is the real problem. During rotation, both the old and new credential are typically valid simultaneously. If the rollout fails partway through, the team must choose between downtime and leaving the old secret active longer than planned.That operational risk is why rotation gets deferred. Security debt accumulates because availability pressure usually wins. Credentials that were supposed to rotate quarterly are still using the same value from two years ago.Problem 4: No Audit TrailWith environment variables and static shared credentials, there is typically no way to answer:Which process read this credential today?Was it used from an unexpected IP address or cloud region?Has it been accessed outside business hours?Was it accessed by something that should not have it?Without auditability, credential misuse is invisible until breach indicators surface — and by then the damage is done.Environment Variables Threat ModelEnvironment variables are not inherently unsafe. The problem is that teams routinely underestimate how widely they propagate.They can leak through:Child process inheritance. Any subprocess inherits the parent’s full environment by default. This includes shells spawned by build tools, test runners, and deployment scripts./proc//environ on Linux. Readable by processes running as the same UID, or by root. A compromised process running as the same user can read another process's secrets.Crash dumps and support bundles. Many crash reporting tools capture the full process environment at the time of the crash.Debug endpoints. Spring Boot Actuator (/actuator/env), Django with DEBUG=True, and misconfigured Express error pages can all expose environment variables directly in HTTP responses.APM agents and structured logging. Datadog, New Relic, and Sentry agents sometimes capture environment context for debugging. One misconfigured log level can expose secrets in your observability platform.CI job output. env commands, verbose build tools, or incomplete log masking expose secrets in build logs accessible to everyone with repository access.Shell history and local scripts. export DB_PASSWORD=abc123 in .bashrc or inline in shell scripts persists in shell history files.Container image inspection. Secrets baked into a Dockerfile with ENV instructions are visible via docker inspect and in the image manifest. This includes every layer of a multi-stage build.Heap dumps and memory analysis. Environment variable values remain in process memory. Heap dumps, core dumps, and memory forensics can recover them.The real problem is not that environment variables are evil. The problem is that they are easy to copy, nearly impossible to audit, and tend to live forever.Environment variables are a delivery mechanism, not a secret lifecycle system.What this means in practice: it is entirely acceptable to inject a short-lived, dynamically fetched token into an environment variable at pod startup. It is not acceptable to store a permanent credential there with no rotation plan, no audit trail, and no revocation mechanism.Kubernetes Secrets ExplainedA common misconception is that Kubernetes Secrets are encrypted. The reality is more nuanced — and the nuances matter.Kubernetes Secrets are API objects designed to separate sensitive configuration from non-sensitive configuration. A Secret object looks like this:apiVersion: v1kind: Secretmetadata: name: database-secret namespace: productiontype: Opaquedata: username: YWRtaW4= password: cGFzc3dvcmQxMjM=Notice what YWRtaW4= and cGFzc3dvcmQxMjM= are:$ echo "YWRtaW4=" | base64 --decodeadmin$ echo "cGFzc3dvcmQxMjM=" | base64 --decodepassword123Base64 is encoding, not encryption. Anyone who can read the Secret object can read the values.How Kubernetes Actually Delivers Secrets to PodsThe pod itself does not call the API server to fetch its own secrets. The Kubelet does — during pod scheduling, before the container starts.When a Secret is mounted as a file, Kubernetes uses a tmpfs volume — a memory-backed filesystem. The secret never touches the node's disk. This is why file mounts are the preferred delivery method over environment variable injection: the secret is not visible in kubectl describe pod output and does not appear in node-level process crash dumps.What Kubernetes Does and Does Not ProtectKubernetes provides real protections around Secrets:RBAC — fine-grained control over which service accounts can access which secretsNamespace isolation — secrets are namespace-scoped; cross-namespace access requires explicit grantsAudit logging — every API call is logged with subject, verb, resource, and timestampAdmission controllers — OPA/Gatekeeper or Kyverno can enforce secret hygiene policiesEncryption at rest — when explicitly configured via EncryptionConfiguration (disabled by default in most distributions, including EKS, GKE, and AKS without additional configuration)⚠️ The most common real-world Kubernetes Secret failure is not Base64. It is over-permissive RBAC — specifically, service accounts or ClusterRole bindings with list or watch on secrets cluster-wide. When you kubectl get secrets -A with sufficient permissions, you do not get a list of names — you get the actual secret values. A service account that can list secrets in a namespace can read every secret in that namespace.⚠️ Second common failure: imagePullSecrets leakage. Registry credentials stored as imagePullSecrets are accessible to any pod in the namespace that has get secret permission — which is often broader than intended.The more important question is not whether Kubernetes can store secrets. It can.The question is whether Kubernetes should be responsible for generating, rotating, revoking, auditing, and distributing secrets across a multi-cluster, multi-cloud platform. At scale, for most teams, the answer is no.The Secret Zero ProblemEvery secret management discussion eventually hits the same wall.Suppose an application needs a database credential and you have set up a secret manager to provide it.The application authenticates to the secret manager, receives a dynamic database credential, and connects. The database never sees the secret manager — the secret manager issues a credential and the application uses it directly.But how does the application authenticate to the secret manager in the first place?If the answer is a hardcoded Vault token or a static AppRole Secret ID, the problem has not been solved. It has been moved one level down.Application │ ▼ presentsStatic Vault Token or AppRole Secret ID ← this is Secret Zero │ ▼ to accessSecret Manager │ ▼ which issuesDynamic Database CredentialThe static token or Secret ID is Secret Zero — the foundational secret that protects all other secrets. If it leaks, everything underneath it is exposed.The Recursion ProblemEach layer pushes the problem down one level. You never reach a layer that doesn’t require another secret to protect it — unless you change the model entirely.The Solution: Platform Identity Instead of a Bootstrap SecretModern secret management platforms solve Secret Zero by replacing the bootstrap secret with a trusted platform identity — a cryptographic proof of who the workload is, signed by the execution environment itself.Instead of:Service → presents Static Secret → Secret Manager grants accessModern platforms use:Service → proves Platform Identity → Secret Manager verifies with IdP → grants accessNo secret is needed to get the first secret. The workload’s identity is the credential.The service proves what it is using infrastructure that already exists — not a password someone typed in a terminal and pasted into a config file.Modern Secret Management ArchitectureA dedicated secret management platform becomes the trust broker for the entire platform.The secret manager does not proxy connections to backends. It issues short-lived credentials, and the application uses those credentials to connect directly. The database has no idea Vault exists — it just sees a valid, scoped user with a defined expiry.Applications no longer store credentials permanently. Instead, on each startup (or credential renewal cycle):Authenticate using the workload’s platform identity — no stored secret required.Request a credential, secret, or certificate from the secret manager.Receive a temporary credential with a short TTL (1 hour for database users, 24 hours for TLS certificates).Use the credential for the duration of the TTL.Renew (if the lease supports it) or re-request before expiry.Automatic revocation at TTL expiry — the database user is dropped, no manual cleanup needed.The Full Dynamic Credential FlowNotice what is absent: no hardcoded passwords, no shared database users, no manual rotation, no rotation window coordination.Security Design PrinciplesEvery mature secret management solution converges on the same six principles.1. CentralizationOne authoritative system for:Secret storage and versioningAccess policy definition and enforcementRotation schedules and automated rotationImmutable audit logsEmergency revocation and break-glass accessPartial centralization creates a false sense of security. A secret manager that covers 80% of your systems still leaves shadow credential stores in the other 20% — often the oldest and most privileged ones.2. Least PrivilegeEvery service should have its own credential, scoped to exactly what it needs.-- Preferred: scoped per service, minimum required permissionsGRANT SELECT ON reporting.monthly_summary TO svc_reporting;GRANT INSERT, UPDATE ON payments.transactions TO svc_payments;-- Anti-pattern: shared user, full permissionsGRANT ALL PRIVILEGES ON DATABASE production TO app_user;The reporting service does not need write access. The payments service does not need to read the reporting schema. Shared over-privileged users make both of these true by default.3. Short-Lived CredentialsA credential with a short TTL limits the exploitation window. Even if a credential is leaked, it expires before most attackers can operationalize it. A one-hour database user that has already been dropped is useless.4. Identity-Based AccessTrust what a workload is, not a password it was given.Identity-based: “This request originates from Pod X in Namespace Y in Cluster Z, verified by the Kubernetes API server.”Password-based: “This request presents the string abc123 — we assume it's Service A."Identity-based access also enables context-aware policies — access rules that account for more than just who is asking:Deny requests originating from unexpected cloud regions.Alert on access outside defined time windows.Require additional verification for requests from new IP ranges.None of these are possible with a static shared credential.5. AuditabilityEvery secret access should produce an immutable log entry that answers:Who? — the workload identity, service account, or human (not just a username)When? — timestamp with timezoneWhat? — which secret, credential, or certificate was accessedFrom where? — IP address, cluster, namespace, cloud regionWas it allowed? — which policy evaluated the request and what was the resultAn audit trail that can answer these questions turns secret management from a prevention-only control into a detection-and-response capability.6. Break-Glass and RevocationEvery secret management system must handle the incident scenario:Service C is compromised. What do we do in the next five minutes?The system must support:Emergency revocation — revoke a single lease, a service’s token, or all credentials for a compromised workload, immediately, without a deployment.Revocation cascade — when a Vault token is revoked, all secrets and credentials issued under that token’s lease hierarchy are also revoked automatically.Break-glass access — an emergency escalation path for incident response that is itself time-limited, scoped, and fully audited.Without these capabilities, incident response devolves into manually hunting down every system that might have a copy of the compromised credential.Immediate DefensesA full secret management platform rollout takes time. These controls reduce your most common leakage paths today.Git and Local Secrets# Add to .gitignore — and audit that these aren't already committed.env.env.**.pem*.key*.p12*.pfxid_rsaid_ed25519credentials.jsonservice-account.json*.secretAdding a file to .gitignore does not remove it from commit history. Run a history scan:# Scan git history for secrets already committedtrufflehog git file://. --since-commit HEAD~100# Check if a specific file was ever committed (even after deletion)git log --all --full-history -- "*.pem"git log --all --full-history -- ".env"Add pre-commit hooks to prevent future commits:# Install pre-commit frameworkpip install pre-commit# Example .pre-commit-config.yamlrepos: - repo: https://github.com/gitleaks/gitleaks rev: v8.18.0 hooks: - id: gitleaksCI/CDRun secret scanning on every pull request: gitleaks, detect-secrets, or trufflehog.Mask secret values in CI log output: GitHub Actions uses ::add-mask::${{ secrets.MY_SECRET }}; GitLab CI uses masked CI variables.Audit which CI jobs have access to which secrets. CI service accounts often have broader access than needed. Apply least privilege.TerraformRemove secrets from output blocks — Terraform outputs appear in state in plaintext.Mark sensitive values with sensitive = true (Terraform ≥ 0.14) to suppress them from console output:variable "db_password" { type = string sensitive = true}output "db_connection_string" { value = "postgres://${var.db_password}@..." sensitive = true}Store state in an encrypted backend with access controls: S3 with SSE and a restrictive bucket policy, or Terraform Cloud with RBAC.Use terraform-provider-vault or cloud-native provider integrations (aws_secretsmanager_secret_version, google_secret_manager_secret_version) instead of hardcoding credentials in .tf files.KubernetesSeparate ConfigMap and Secret usage. If a value needs confidentiality or tighter RBAC, it does not belong in a ConfigMap.Enable encryption at rest explicitly in production clusters using EncryptionConfiguration. Most managed distributions (EKS, GKE, AKS) do not enable this by default.Audit RBAC permissions regularly:# Check if the default service account can list secrets cluster-widekubectl auth can-i list secrets \ --all-namespaces \ --as=system:serviceaccount:default:default# Find all service accounts with secret list/watch permissionskubectl get clusterrolebindings -o json | \ jq '.items[] | select(.roleRef.name | contains("secret"))'Prefer mounting Secrets as files over environment variable injection. Env vars are visible in kubectl describe podoutput and in process crash dumps. File mounts use tmpfs and are not persisted to node disk.Set automountServiceAccountToken: false on pods that do not need API server access:spec: automountServiceAccountToken: false containers: - name: appApplication-LevelNever log secrets. Add secret values to your logging framework’s redaction/denylist configuration. A single logger.debug("Config: %s", config) can expose every environment variable to your log aggregator.Avoid passing secrets as CLI arguments. They appear in /proc//cmdline and are visible to any user who can run ps aux.Zero out secrets after use in memory-managed languages where possible (most relevant in Go, Rust, and C/C++). In Go, use []byte instead of string for secrets so the value can be zeroed.What’s NextPart 1 established the problem: credentials spread, shared identities create risk, static secrets have no lifecycle, and most teams are operating blind without auditability or revocation capability.In Part 2, the series moves to implementation with HashiCorp Vault — the most widely deployed open-source secret management platform:Vault architecture and the seal/unseal lifecycle — what it means for a secret manager to be “sealed” and why it matters.Authentication methods: Kubernetes Service Account auth, AppRole for non-cloud workloads, AWS IAM auth, and OIDC.KV v1 vs KV v2 — and why secret versioning matters during rotation.Dynamic secrets engine: how Vault creates and revokes database users on demand, and how lease management works.Vault Agent Injector — the vault-k8s mutating admission webhook that injects secrets into pods without application code changes.PKI secrets engine — issuing short-lived TLS certificates at scale.Transit secrets engine — encryption-as-a-service for applications that should not handle raw keys.Production deployment: HA with Integrated Storage (Raft), auto-unseal with cloud KMS, and operational runbooks.The hardest secret to protect is often the one protecting all the others.Stay ConnectedIf this helped you think more clearly about secrets management, the best thing you can do is share it with someone building on the same problems.Follow TheProdSDE for more content on platform engineering, cloud architecture, and production systems:🔗 LinkedIn: linkedin.com/in/TheProdSDE🐦 X (Twitter): x.com/TheProdSDE▶️ YouTube: youtube.com/@TheProdSDE✍️ Medium: medium.com/@TheProdSDEEvery article, video, and thread in this space is aimed at one thing: helping engineers build production systems that don’t break quietly.@TheProdSDEYour Secrets Are Probably Leaking : Follow this to fix it was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.