Sub topic 4
Handling secrets safely
A secret is any value that grants access to something: a database password, an API key, a signing key for tokens, or a TLS private key. The previous chapter covered keeping configuration outside the artifact. This chapter covers the stricter rules secrets need on top of that. It assumes you can build a Spring Boot JAR, know how profiles and environment variables bind to properties, and have used a Linux shell.
Why secrets need extra care
Ordinary configuration, such as a port number, is harmless if it leaks. A secret is not. Three places leak secrets most often:
- Source control. A password committed once stays in the Git history even after you delete the line.
- The artifact. A JAR is a ZIP file. Anyone who can download it can unzip it and read
application.properties. The same is true of every layer in a container image. - Logs and diagnostics. Startup logs, error messages, crash dumps, and actuator endpoints can all print configuration values.
The rule that follows is simple: the artifact you build contains no secrets, and every secret arrives at run time from the environment that runs it.
Placeholders instead of values
The packaged application.properties from the earlier chapter shows the pattern:
spring.datasource.url=${DB_URL}
spring.datasource.password=${DB_PASSWORD}The file holds the names of the variables, not their values. Spring resolves ${DB_PASSWORD} when the application starts, by reading the environment variable of that name. If the variable is missing, startup fails with an unresolved placeholder error. That is a good outcome. A missing secret stops the deployment instead of letting the app run with a wrong or empty value.
Avoid default values for secrets, such as ${DB_PASSWORD:changeme}. A default that works in development will eventually be used in production by accident.
Where secrets can come from
Spring Boot reads configuration from many sources in a fixed order of precedence. These are the ones that matter for secrets, from the simplest to the most capable.
| Source | How it reaches the app | Main risk |
|---|---|---|
| Command-line argument | `--spring.datasource.password=...` | Visible to every user in the process list (`ps`) and often in shell history |
| Environment variable | `DB_PASSWORD=... java -jar app.jar` | Readable by the same user through `/proc/<pid>/environ`; inherited by child processes; easy to print by mistake |
| Environment file | systemd `EnvironmentFile=` | Safe only if file permissions are tight |
| Mounted file | A file such as `/run/secrets/db_password` | Safe if permissions are tight and the mount is read-only |
| Secret manager | The app or a sidecar fetches it at startup | Needs its own credentials to authenticate |
Never pass secrets as command-line arguments. Process listings are readable by other users on the same machine, which makes this the weakest option.
Environment variables and relaxed binding
Spring Boot maps environment variable names to property names using relaxed binding. Uppercase the name, replace dots and dashes with underscores, and the variable overrides the property. So SPRING_DATASOURCE_PASSWORD sets spring.datasource.password without any placeholder in the file.
export SPRING_DATASOURCE_URL=jdbc:postgresql://db.internal:5432/orders
export SPRING_DATASOURCE_PASSWORD="$(cat /run/secrets/db_password)"
java -jar target/myapp-1.0.0.jarBoth styles work. Explicit ${DB_PASSWORD} placeholders document which variables the app needs, which helps operators. Relaxed binding needs no placeholder but leaves the required variables undocumented.
Reading secrets from files
Environment variables are convenient, but a file is often safer. Container platforms and Kubernetes mount secrets as files, and a file can have restrictive permissions and be updated without rebuilding anything.
Spring Boot supports this directly with the configtree: import. Each file in a directory becomes a property, with the file name as the key and the file content as the value.
# application.properties
spring.config.import=optional:configtree:/run/secrets/If /run/secrets/ contains a file named spring.datasource.password, that property is set from the file content. Spring trims nothing silently in surprising ways, but make sure the file has no stray trailing newline from the way it was created. Use printf '%s' instead of echo when writing one:
printf '%s' 'S3cret-value' > /run/secrets/spring.datasource.password
chmod 400 /run/secrets/spring.datasource.passwordThe optional: prefix lets the app start when the directory is absent, for example on a developer laptop. In production you often want the opposite, so that a missing mount fails fast. Drop optional: in the production profile, or in a profile-specific file such as application-prod.properties.
Another option is to read a file path yourself through a property that points at the file, which is how many drivers accept TLS key material:
server.ssl.key-store=file:/run/secrets/keystore.p12
server.ssl.key-store-password=${KEYSTORE_PASSWORD}Secret managers
For anything beyond a single server, a dedicated secret manager is the usual answer. Examples are HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, and Google Secret Manager. They add what files and variables lack: central rotation, audit logs of who read what, and fine-grained access policies.
There are two common integration styles:
- Fetch at startup in the application. Libraries such as Spring Cloud Vault or Spring Cloud AWS add the manager as a property source, so
${DB_PASSWORD}resolves from it. The app needs its own identity, such as an IAM role, to authenticate. - Inject before startup from outside. The platform reads the secret and presents it to the app as an environment variable or a mounted file. Kubernetes, ECS, and systemd credential features work this way. The app code stays unaware of the manager.
The second style keeps the application simple and portable. The first gives you rotation without a restart if you also refresh the properties, but it ties the app to a specific product.
All of these still rely on one starting credential, such as a role or token. Prefer platform identities, which are issued automatically and expire, over long-lived keys stored in a file.
Keeping secrets out of logs and endpoints
Even a well-delivered secret can leak after it is loaded.
- Actuator
envandconfigprops. Spring Boot masks values whose keys end in words likepassword,secret,key, ortoken. Masking is by key name, so a property calledpayment.signingis not masked. Name secrets so the pattern matches, or configuremanagement.endpoint.env.show-valuesandmanagement.endpoint.configprops.show-valuestonever. Better, do not expose these endpoints at all. The earlier chapter exposes onlyhealthandinfo, which is the right default. - Application logs. Do not log request bodies, connection strings with passwords, or whole configuration objects. A
toString()on a properties class can print a password. - Exception messages. A JDBC URL containing
password=can appear in a stack trace. Pass credentials as separate properties, not inside the URL. - Container builds. Do not use
ENV DB_PASSWORD=...orARGfor secrets in a Dockerfile. Both are recorded in image metadata or layers and can be read withdocker historyor by inspecting the image.
Secrets in a systemd deployment
The systemd unit from this tutorial loads variables with EnvironmentFile=/etc/myapp/env. That file is now your secret store, so lock it down:
sudo install -o root -g myapp -m 0640 /dev/null /etc/myapp/env
sudo editor /etc/myapp/envThe file should be owned by root and readable only by the service group. Mode 0640 lets the myapp user read it while keeping other users out. The variables inside look like this:
DB_URL=jdbc:postgresql://db.internal:5432/orders
DB_PASSWORD=S3cret-valueDo not put quotes around values unless you want them included, because systemd parses this file with its own rules, not those of a shell. Never commit this file. Manage it through your provisioning tool, with the values supplied from a secure store.
Rotation and revocation
Secrets leak eventually, so plan for replacing them.
- Use separate credentials per environment and per application, so one leak has a small blast radius.
- Give each credential the least privilege it needs. A web app rarely needs to drop tables.
- Rotating a secret that the app reads once at startup requires a restart. A graceful restart, covered in the shutdown chapter, makes that safe.
- If a secret reaches Git, rotate it first, then clean the history. Rewriting history does not undo exposure, because clones and caches may already hold the value.
A scanner such as gitleaks or GitHub secret scanning, run in CI, catches many accidental commits before they merge.
Secrets in Kubernetes
Kubernetes provides a Secret object that you can expose to a pod as environment variables or mounted files. Prefer mounted files with configtree:, since environment variables are copied into child processes and crash reports. Remember that a Kubernetes Secret is base64 encoded, not encrypted, by default. Restrict who can read Secrets with RBAC, and enable encryption at rest on the cluster. The Kubernetes chapter shows the manifests.
Common mistakes
- Committing
application-prod.propertieswith real values because it was "just for the server". - Giving a placeholder a default that works, which hides a missing secret.
- Exposing the
envorheapdumpactuator endpoints to the network. - Logging the full set of environment variables at startup for debugging.
- Reusing one database account across all environments.
Exercise
Your team puts spring.datasource.password=${DB_PASSWORD:changeme} in the packaged application.properties, and a production deployment forgets to set DB_PASSWORD. What happens, and what should the line be instead?
Show answer
The application starts using the password changeme, so it either fails to connect with a confusing authentication error or, worse, connects to a database that accepts the default. The default hides the missing configuration. The line should be spring.datasource.password=${DB_PASSWORD} with no default, so startup fails immediately with an unresolved placeholder error when the variable is absent.
Exercise
A colleague passes the database password with java -jar app.jar --spring.datasource.password=S3cret. Give two reasons this is unsafe and one safer alternative.
Show answer
The argument is visible to other users through the process list (ps), and it is likely stored in shell history and in deployment scripts or CI logs. A safer alternative is to put the password in a file readable only by the service user and load it with spring.config.import=optional:configtree:/run/secrets/, or to supply it through a restricted systemd EnvironmentFile.