Skip to main content
Version: 2.x

How to Read Secrets

A secret is a value such as a password or an API key. This guide shows how to read one without writing it into a file in the repository, and how to keep it out of logs.

Goalโ€‹

Read a database password from an environment variable, or from a file that the deployment platform mounts, and never print it.

Step 1: Describe the Secret as Config.Secretโ€‹

Config.secret reads a value into a Config.Secret. Its toString hides the value, so printing the config does not leak it:

import zio._
import zio.config._
import zio.config.magnolia.deriveConfig

final case class Credentials(user: String, password: Config.Secret)

val credentials: Config[Credentials] =
(Config.string("DB_USER") zip Config.secret("DB_PASSWORD")).to[Credentials]

Step 2: Load It from the Environmentโ€‹

val fromEnvironment: IO[Config.Error, Credentials] =
ConfigProvider.envProvider.load(credentials)

Set DB_USER and DB_PASSWORD in the environment of the process. The value never appears in the source tree.

Step 3: Read It from a Mounted Fileโ€‹

Some platforms put each secret in a file, for example /run/secrets/db_password. Read the file's content into a map and load from it. The file's content is read as the value, so strip the trailing newline:

import java.nio.file.{Files, Paths}

val fromFile: Task[ConfigProvider] =
ZIO.attempt {
val password = Files.readString(Paths.get("/run/secrets/db_password")).trim
ConfigProvider.fromMap(Map("DB_USER" -> "orders", "DB_PASSWORD" -> password))
}

val loadedFromFile: Task[Credentials] =
fromFile.flatMap(_.load(credentials).mapError(e => new RuntimeException(e.toString)))

Step 4: Use the Value at the Point of Needโ€‹

Call Config.Secret#stringValue only where the password is passed to a client. Do not store it in a log message or a string:

def openConnection(user: String, password: String): Task[Unit] = ZIO.unit

val connect: IO[Config.Error, Task[Unit]] =
ConfigProvider.envProvider
.load(credentials)
.map(c => openConnection(c.user, c.password.stringValue))

The value is available through Config.Secret#stringValue, which returns a String, and Config.Secret#value, which returns a Chunk[Char].

Checksโ€‹

Check that the file containing the secret is not committed (look in .gitignore), and that errors from a missing secret name the key, not the value; see Errors.

See Config providers for each source, and Tutorial: Configure an App from HOCON and Environment Variables for layering secrets and defaults.

ZIO Chat

๐ŸŽ‰ Hey there, ZIO aficionado! ๐ŸŽ‰ Step into the ZIO wonderland with me as your guide. Whether you're a functional fanatic or just dipping your toes into the ZIO ecosystem, I'm here to make your journey smooth. Got ZIO questions? I've got answers! Let's navigate the ZIO universe together and unlock its infinite possibilities!