Documentation
¶
Overview ¶
Package dotenvx loads dotenvx-compatible .env files, including encrypted ones, into a Go process.
It ports the parsing and decryption of dotenvx's config() (https://dotenvx.com), reading files in process, with no Node and no dotenvx binary. It doesn't redact output, use key stores or apply Dotenvxfile policies, as config() can; for redaction, run the program with dotenvx run. Encrypting and editing files stay with the dotenvx CLI.
Load reads .env into the process environment, keeping variables that are already set; Overload replaces them; Read and Parse return the values without touching the environment. Options configures all four.
Values are parsed as dotenvx parses them, including quotes, multiline values, $VAR and ${VAR:-default} expansion and $(command) substitution. Values that start with "encrypted:" are decrypted with private keys from .env.keys files, DOTENV_PRIVATE_KEY* variables or Options.KeyProvider.
The port follows Node's @dotenvx/primitives, which is what dotenvx runs. Where it deliberately differs, mostly because dotenvx relies on an accident of JavaScript, the function concerned documents it.
Index ¶
- Variables
- func Decrypt(privateKey, value string) (string, error)
- func Encrypt(publicKey, value string) (string, error)
- func GenerateKeypair() (privateKey, publicKey string)
- func Load(files ...string) error
- func Overload(files ...string) error
- func Parse(r io.Reader) (map[string]string, error)
- func PublicKey(privateKey string) (string, error)
- func Read(files ...string) (map[string]string, error)
- type Error
- type Options
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingPrivateKey = &Error{Code: "MISSING_PRIVATE_KEY", Message: "could not decrypt because private key is missing"} ErrInvalidPrivateKey = &Error{Code: "INVALID_PRIVATE_KEY", Message: "could not decrypt using private key"} ErrWrongPrivateKey = &Error{Code: "WRONG_PRIVATE_KEY", Message: "could not decrypt using private key"} ErrDecryptionFailed = &Error{Code: "DECRYPTION_FAILED", Message: "could not decrypt value"} ErrInvalidPublicKey = &Error{Code: "INVALID_PUBLIC_KEY", Message: "could not encrypt using public key"} ErrEncryptionFailed = &Error{Code: "ENCRYPTION_FAILED", Message: "could not encrypt value"} )
These are for matching with errors.Is. The errors returned are new values with the same codes, so changing them doesn't change these. Parse, Read and Load report values they couldn't decrypt with an error that matches ErrDecryptionFailed and names their keys.
var ( // ErrReferenceCycle is reported, wrapped, when a value can't be // expanded because a variable refers back to itself, as in A=$B with // B=x$B. ErrReferenceCycle = errors.New("reference cycle") // ErrExpansionLimit is reported, wrapped, when expanding a value would // take more than 10,000 substitutions of values that contain "$", or // make it longer than 16 MiB, as happens when each of a chain of // variables refers to the next one twice. ErrExpansionLimit = errors.New("expansion limit exceeded") )
Functions ¶
func Decrypt ¶
Decrypt decrypts a value encrypted for dotenvx with privateKey, a secp256k1 private key in hex. Like dotenvx, it returns values that don't start with "encrypted:" as they are.
Its errors match ErrMissingPrivateKey, ErrInvalidPrivateKey, ErrWrongPrivateKey (when the value was encrypted for another key) and ErrDecryptionFailed (when it isn't a valid encrypted value), as dotenvx's do. Unlike dotenvx, it parses the private key strictly as 64 hex digits: Node reads hex up to the first character that isn't. It skips characters outside ASCII in the base64, which Node reads by the low byte of their UTF-16 code units. And it returns plaintext that isn't valid UTF-8 as it is, where dotenvx gives U+FFFD.
The library dotenvx uses is written to make timing attacks harder; Decrypt isn't. The steps it takes depend on the private key, so another process that can watch it run on the same machine, by timing it or through the CPU's caches, could learn the key. That doesn't matter where nothing untrusted shares the machine. PublicKey and GenerateKeypair have the same weakness, and so does Encrypt, which could give away the value it encrypts. Parse, Read, Load and Overload decrypt with Decrypt.
Example ¶
package main
import (
"errors"
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
// The private key and an encrypted value from testdata/encrypted.
const privateKey = "ec9e80073d7ace817d35acb8b7293cbf8e5981b4d2f5708ee5be405122993cd1"
value, err := dotenvx.Decrypt(privateKey, "encrypted:BG8M6U+GKJGwpGA42ml2erb9+T2NBX6Z2JkBLynDy21poz0UfF5aPxCgRbIyhnQFdWKd0C9GZ7lM5PeL86xghoMcWvvPpkyQ0yaD2pZ64RzoxFGB1lTZYlEgQOxTDJnWxODHfuQcFY10uA==")
fmt.Println(value, err)
other, _ := dotenvx.GenerateKeypair()
_, err = dotenvx.Decrypt(other, "encrypted:BG8M6U+GKJGwpGA42ml2erb9+T2NBX6Z2JkBLynDy21poz0UfF5aPxCgRbIyhnQFdWKd0C9GZ7lM5PeL86xghoMcWvvPpkyQ0yaD2pZ64RzoxFGB1lTZYlEgQOxTDJnWxODHfuQcFY10uA==")
fmt.Println(errors.Is(err, dotenvx.ErrWrongPrivateKey), err)
}
Output: encrypted <nil> true [WRONG_PRIVATE_KEY] could not decrypt using private key
func Encrypt ¶
Encrypt encrypts value for publicKey, a secp256k1 public key in hex, compressed or not and optionally starting with "0x", the way dotenvx does. Encryption is randomized, so encrypting the same value twice gives different results. Its errors match ErrInvalidPublicKey, or ErrEncryptionFailed when the scheme isn't allowed, as with GODEBUG=fips140=only.
Example ¶
package main
import (
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
privateKey, publicKey := dotenvx.GenerateKeypair()
encrypted, err := dotenvx.Encrypt(publicKey, "World")
if err != nil {
fmt.Println(err)
return
}
value, _ := dotenvx.Decrypt(privateKey, encrypted)
fmt.Println(value)
}
Output: World
func GenerateKeypair ¶
func GenerateKeypair() (privateKey, publicKey string)
GenerateKeypair returns a new secp256k1 private key and its compressed public key, both in hex.
Example ¶
package main
import (
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
privateKey, publicKey := dotenvx.GenerateKeypair()
// 32 bytes, and a compressed point of 33, in hex.
fmt.Println(len(privateKey), len(publicKey))
}
Output: 64 66
func Load ¶
Load loads env files into the process environment with the default Options. Variables that are already set keep their values.
Example ¶
package main
import (
"errors"
"fmt"
"io/fs"
"log"
"os"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
// Load .env from the current directory, if there is one, keeping
// variables that are already set.
if err := dotenvx.Load(".env"); err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Fatal(err)
}
fmt.Println(os.Getenv("HELLO"))
}
Output:
func Overload ¶
Overload loads env files into the process environment, replacing variables that are already set.
Example ¶
package main
import (
"log"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
// Overload replaces variables that are already set, and .env.local,
// read last, wins over .env.
if err := dotenvx.Overload(".env", ".env.local"); err != nil {
log.Fatal(err)
}
}
Output:
func PublicKey ¶
PublicKey returns the compressed public key, in hex, of privateKey, a secp256k1 private key in hex. dotenvx files name the keys they are encrypted for by this public key.
Example ¶
package main
import (
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
publicKey, err := dotenvx.PublicKey("ec9e80073d7ace817d35acb8b7293cbf8e5981b4d2f5708ee5be405122993cd1")
fmt.Println(publicKey, err)
}
Output: 03eaf2142ab3d55bdf108962334e06696db798e7412cfc51d75e74b4f87f299bba <nil>
Types ¶
type Error ¶
Error is an error with one of dotenvx's codes, such as "WRONG_PRIVATE_KEY". Its message has dotenvx's "[CODE] message" form, followed by the underlying error, if any. errors.Is matches an Error against the Err variables by code alone.
type Options ¶
type Options struct {
// Env is the existing environment that Parse and Read resolve against,
// in the "KEY=value" form of os.Environ. A key that already exists in
// Env keeps its existing value unless Overload is set. If Env is nil,
// they use the current process environment; use an empty slice for no
// existing environment at all. Load ignores Env: it always resolves
// against the process environment it sets values in.
Env []string
// Overload lets values from the source replace values that already
// exist in Env.
Overload bool
// DisableCommandSubstitution turns off $(command) substitution. By
// default, as in dotenvx, each $(command) in a value that isn't
// single-quoted is replaced with the output of running the command with
// /bin/sh. That includes the existing value of a key the source
// assigns, unless Overload is set. The command sees Env plus the values
// parsed before it. When a command fails, writes more than 1 MiB to
// stdout and stderr together, or can't run because there is no /bin/sh
// (as on Windows or in minimal container images), the value is kept as
// it is. What a command writes to stderr is written to os.Stderr after
// it finishes, as dotenvx does.
DisableCommandSubstitution bool
// KeyFiles are the files, usually named .env.keys, to read the private
// keys of encrypted values from: the values of their DOTENV_PRIVATE_KEY*
// keys, each of which may list several keys separated by commas. Files
// that can't be read are skipped. If KeyFiles is nil, Parse reads
// .env.keys in the current directory, and Read and Load the .env.keys
// next to each env file, as dotenvx does; but when that file's own
// private key is set in the environment (DOTENV_PRIVATE_KEY_PRODUCTION
// for .env.production), dotenvx reads .env.keys in the current
// directory instead, and so do they. Use an empty slice to read none.
//
// Like dotenvx's config, a source that declares its public keys, in
// DOTENV_PUBLIC_KEY* values, only takes the private keys of those (and
// of the environment's DOTENV_PUBLIC_KEY* variables) from the key
// files, so a value encrypted for another key in .env.keys stays
// encrypted. A source that declares none takes every key.
//
// Private keys also come from the DOTENV_PRIVATE_KEY* variables of the
// existing environment, each holding a single key, and always count.
// Keys must be exactly 64 hex digits: a value with anything else in it,
// such as a comma-separated list or trailing whitespace, is ignored,
// where dotenvx would use the hex it starts with.
KeyFiles []string
// KeyProvider, if set, is asked for the private key of each public key
// that has none from KeyFiles or the environment: those the source
// declares in its DOTENV_PUBLIC_KEY* values, and those of the
// environment's DOTENV_PUBLIC_KEY* variables. It returns the private key
// in hex, or "" if it has none; an invalid key is ignored. It is where
// key stores plug in. If it returns an error, the source is parsed
// without it, with every key in the key files, as dotenvx does, and
// the error is returned with the values.
KeyProvider func(publicKey string) (privateKey string, err error)
}
Options configures how dotenv source is resolved. The zero value is ready to use and matches the defaults of dotenvx.
Example (KeyProvider) ¶
package main
import (
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
// A provider looks private keys up by public key, for example in a key
// store. This one knows the key of testdata/encrypted.
keys := map[string]string{
"03eaf2142ab3d55bdf108962334e06696db798e7412cfc51d75e74b4f87f299bba": "ec9e80073d7ace817d35acb8b7293cbf8e5981b4d2f5708ee5be405122993cd1",
}
opts := dotenvx.Options{
Env: []string{},
KeyFiles: []string{}, // Don't read .env.keys.
KeyProvider: func(publicKey string) (string, error) {
return keys[publicKey], nil
},
}
values, err := opts.Read("testdata/encrypted/.env")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(values["HELLO"])
}
Output: encrypted
func (Options) Load ¶
Load reads env files as Read does, and sets their values in the process environment, in the order dotenvx would set them. It ignores Env. Like Read, it sets every value it could read even if some files fail.
func (Options) Parse ¶
Parse reads dotenv source from r and returns its values. It doesn't modify the process environment. When a key is assigned more than once, the last assignment wins.
Values that start with "encrypted:" are decrypted first, with the keys that KeyFiles, the environment and KeyProvider supply. A value that can't be decrypted stays encrypted, and isn't evaluated or expanded; Parse returns the values together with an error that matches ErrDecryptionFailed and names the keys it couldn't decrypt. Decryption isn't constant-time; see Decrypt.
Values that aren't single-quoted then have each $(command) replaced with the command's output, unless DisableCommandSubstitution is set. Each output is inserted as it is, where the command was. dotenvx instead treats it as a String.prototype.replace pattern ($$, $&, $` and $') and replaces the first copy of the command's text, which may be in an earlier command's output; it also turns invalid UTF-8 into U+FFFD, and runs commands with cmd.exe on Windows rather than /bin/sh.
Values that aren't single-quoted, and had no command substituted, then have their $NAME and ${NAME} references expanded, as do ${NAME:-default}, ${NAME-default}, ${NAME:+alternative} and ${NAME+alternative}, the way dotenvx expands them. Names resolve to existing values first, then to values parsed earlier, or the other way round with Overload. A backslash keeps a "$" from starting a reference. Existing values that aren't empty aren't expanded, though they do go through command substitution.
Expansion differs from dotenvx where dotenvx relies on accidents of JavaScript: a value is inserted as it is, even if it contains "$$" or "$&"; the reference that matched is the one replaced, even if an escaped copy of it comes first; and names containing "null", or naming properties of Object.prototype, resolve like any other. Where dotenvx would loop forever, because a variable refers back to itself, Parse leaves the rest of that value unexpanded and returns its values with an error that wraps ErrReferenceCycle. It does that as soon as a reference that came entirely from a variable's value would insert that value again, which also stops a few contrived inputs that dotenvx finishes. A value that would take more than 10,000 substitutions of values containing "$", or grow past 16 MiB, stops the same way, with ErrExpansionLimit.
Source that starts with a UTF-16LE byte order mark is decoded from UTF-16LE, with unpaired surrogates, which dotenvx keeps, becoming U+FFFD; anything else is read as UTF-8. Bytes that aren't valid UTF-8 are kept as they are, where dotenvx, which only sees decoded text, would have replaced them with U+FFFD. Keys such as constructor or __proto__, which make dotenvx throw, are parsed like any other key.
Example ¶
package main
import (
"fmt"
"strings"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
src := `# comments and blank lines are skipped
HELLO=World
GREETING="Hello, ${HELLO}
on two lines"
EXISTING=from the file
`
opts := dotenvx.Options{Env: []string{"EXISTING=from the environment"}}
values, err := opts.Parse(strings.NewReader(src))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(values["HELLO"])
fmt.Println(values["GREETING"])
fmt.Println(values["EXISTING"])
opts.Overload = true
values, _ = opts.Parse(strings.NewReader(src))
fmt.Println(values["EXISTING"])
}
Output: World Hello, World on two lines from the environment from the file
Example (Embedded) ¶
An encrypted .env can be compiled into the binary, which then only needs the private key at run time.
package main
import (
"bytes"
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
//go:embed testdata/encrypted/.env
var encryptedEnv []byte
func main() {
// In production, the private key would be the only dotenvx variable in
// the environment: here, it is the only entry in Env, and there are no
// key files.
opts := dotenvx.Options{
Env: []string{"DOTENV_PRIVATE_KEY=ec9e80073d7ace817d35acb8b7293cbf8e5981b4d2f5708ee5be405122993cd1"},
KeyFiles: []string{},
}
values, err := opts.Parse(bytes.NewReader(encryptedEnv))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(values["HELLO"])
}
Output: encrypted
func (Options) Read ¶
Read reads the given env files and returns their values without modifying the process environment. A file that is a directory stands for the .env in it. Paths are used as given: unlike the path option of dotenvx's config, a leading "~" isn't expanded and commas don't separate paths. With no files, like dotenvx, Read reads the comma-separated files named by DOTENV_FILE, DOTENV_PATH or DOTENV_F, the first that isn't empty; or else, if DOTENV_PRIVATE_KEY* variables are set, the files they stand for, in the environment's order (.env.production for DOTENV_PRIVATE_KEY_PRODUCTION); or else ".env". It looks for those in the existing environment only: with Env set, that is Env, where dotenvx would also check the process environment.
Files are read in order, and each one sees the values set by the files before it as existing values. So unless Overload is set, the first file to set a key wins, and with Overload the last one does.
A file that can't be read doesn't stop the others: Read returns the values it could read together with the errors. To make a single file optional, ignore an error that wraps fs.ErrNotExist. With several files, that would also ignore errors joined with it.
Example ¶
package main
import (
"fmt"
_ "embed"
"github.com/narasaka/dotenvx-go"
)
func main() {
// Files are read in order, and the first to set a key wins, so the
// local override comes first. The later file sees its values.
values, err := dotenvx.Options{Env: []string{}}.Read("testdata/load/.env.local", "testdata/load/.env")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(values["HELLO"])
fmt.Println(values["GREETING"])
}
Output: local Hello, local