Skip to content

Secrets in applications: from a .env file to a vault

B2Bnetwork team · · 6 min

Security

In brief

A secret is any piece of data that grants access: a database password, an API key, a token, a certificate's private key. Do not keep it in code or in the repository. A .env file is enough on a developer's laptop, but servers need a secrets vault that encrypts the data, hands it out only to authorized services, logs every read, and makes rotation easier. A secret that has leaked must be revoked, because removing it from git history is not enough.

What counts as a secret and where it most often leaks

A secret is anything that lets someone act on behalf of an application: passwords to databases and queues, API keys for payment and SMS providers, cloud access tokens, private keys for TLS certificates and signing keys, passwords of service accounts for systems such as an ERP.

The most common leak points are mundane:

  • a configuration file or .env added to the repository “just for a moment”,
  • a secret written into test code or a migration script,
  • application logs that print the full database connection string,
  • environment variables visible in CI pipeline logs or in a container configuration dump,
  • screenshots and pastes in the team chat.

Each of these places has a different defense, but the rule is one: a secret lives in a single trusted store, and the application receives it at startup.

The .env file: when it is enough and when it is not

A .env file separates configuration from code, and that is its advantage. A developer keeps local database passwords for a container in it, and the repository holds only `.env.example` with variable names and no values. The .env file must be in `.gitignore`.

On servers, .env quickly stops being enough, because:

  • you do not know who read a value or when,
  • rotation requires a manual change on every machine,
  • server backups contain secrets in plain text,
  • anyone with access to the server has all the passwords.

So the line is simple: .env locally and in isolated development environments, a vault everywhere there is real data.

A secrets vault: how it works

A secrets vault is a service that stores secrets encrypted, hands them out after a service authenticates, and logs every access. Examples are HashiCorp Vault and cloud provider services: AWS Secrets Manager, Azure Key Vault, and Google Cloud Secret Manager.

A vault gives you four things a file cannot:

  1. Per-service access control. The payments service reads only its own database password, not the passwords of the whole system.
  2. An audit trail. Every read has an author and a time, which helps during an incident and an audit.
  3. Rotation. A password changes on a schedule or after an incident, without walking around to servers by hand.
  4. Dynamic secrets. Some vaults can issue a short-lived database account for the lifetime of a service, which expires on its own.

A service authenticates to the vault with the platform's identity, for example a Kubernetes service account or a cloud machine role. That way there is no “first secret” that would have to be stored somewhere.

Secrets in application code

A vault will not help if the application prints the secret to a log after reading it. A few rules for developers:

  • the logger masks fields with names such as `password`, `token`, `secret`, `apiKey`, and the database connection string goes to the log without the password,
  • an error message shown to the user contains no configuration or stack trace,
  • the application reads the secret at startup or from a short-lived cache and can reload it after rotation without a restart,
  • unit tests use fake values, and integration tests use separate accounts with permissions only for the test environment.

A bank example: a service integrating with a credit bureau has a client certificate for an mTLS connection. The private key sits in the vault, the service receives it at startup, and renewing the certificate before it expires is a task on the team's calendar, not a surprise in the middle of the night.

Secrets in CI/CD and Kubernetes

A CI pipeline needs access to the image registry, the cloud, and the environments. Instead of keeping static access keys in it, many CI and cloud providers allow identity federation through OpenID Connect: the pipeline receives a short-lived token for a single run, limited to the specified repository and branch. We write more about this mechanism in the article OAuth 2.0 and OpenID Connect demystified.

In Kubernetes, a Secret object is stored in the cluster database by default as base64, which is encoding, not encryption. The Kubernetes documentation recommends enabling encryption at rest and narrowing RBAC permissions to read secrets. A common pattern is an operator that syncs secrets from an external vault into the cluster, so the vault remains the source of truth.

Secrets in infrastructure definitions, for example in Terraform, require the same discipline: a state file can contain passwords in plain text, so it is kept in an encrypted, access-controlled store. We describe this in the article Infrastructure as code.

When a secret leaks

Treat a secret that reached the repository as exposed, even if the repository is private. The order of actions:

  1. Revoke it and generate a new secret at the source: in the database, at the API provider, in the cloud.
  2. Check the access logs for the period when the secret was visible.
  3. Remove the secret from the repository history, but treat that as housekeeping, not a fix, because copies and forks already exist.
  4. Add a guard: a secret scanner in a pre-commit hook and in CI, for example gitleaks or trufflehog, so the same mistake does not return.

Secret scanners are one of the first checks worth adding to a pipeline. We describe the others in the article SAST, DAST, and SCA. B2Bnetwork engineers build such pipelines in cloud and DevOps projects.

Questions and answers

Are environment variables a safe place for secrets?

Environment variables are better than code, but they are not a vault. They show up in a process configuration dump, can end up in error logs, and are inherited by child processes. A reasonable compromise is a vault as the source of truth, with the secret injected into a variable or an in-memory file only when the service starts.

How often should you rotate secrets?

Immediately after a suspected leak and after the departure of a person who knew the secret. Otherwise according to company policy, usually more often for accounts with broad permissions. It is best when rotation is automated in the vault or when secrets are short-lived, because then the question of frequency stops being a problem.

Is it enough to remove the secret from git history?

No, because anyone who cloned the repository earlier has a copy, and hosting services may keep old versions in their caches. The only effective fix is revoking the secret at the source and issuing a new one. History cleanup is done afterward, so that scanners do not report the old finding.

Where do you start in an existing system?

With an inventory: scan the repositories with a secret scanner, list the service accounts and where they are used. Then move the production secrets with the broadest permissions into a vault, add a scanner to CI, and only then tidy up the test environments. Such a plan gives quick results without downtime.

What it looks like in a project

Want to check your application's security? Talk to an engineer.

Let's talk

Read more: Security