Documentation
¶
Overview ¶
Package secret finds the passwords and tokens a command-line tool needs, and keeps them between runs without writing them anywhere in plain sight.
A Store keeps one secret per account name. Keyring uses the operating system's keyring (macOS Keychain, Windows Credential Manager, the Secret Service on Linux desktops). FileStore keeps each secret in a file only its owner can read, for machines without a keyring, such as servers and containers; Fallback combines the two, and Migrating also moves what the files hold into the keyring once there is one. Unavailable stands in for a store that could not be set up. Memory is for tests; a test binary never reaches the operating system keyring (see Keyring).
A Resolver decides where a secret comes from on a given run. It tries, in this order:
- a file the user named (a --password-file flag), or "-" for stdin,
- an environment variable,
- a piped stdin,
- the Store,
- an interactive prompt with hidden input: TTYPrompt, or a text field of the tool's own through InputPrompt.
Explicit sources come first, so a secret passed for one run always wins over the one remembered from an earlier run. Once the secret proved valid, Resolver.Save remembers it; when a service rejects it, Resolver.Forget drops it so the next attempt asks again.
WriteFile writes a file only its owner can read, such as a token cache, replacing an existing one atomically.
Nothing in this package prints, logs or embeds a secret value in an error. Redact removes known secrets from text that is about to be logged.
Index ¶
Examples ¶
Constants ¶
const DefaultMaxLen = 4096
DefaultMaxLen bounds what a Resolver reads from a file or stdin when MaxLen is zero.
const Redacted = "[REDACTED]"
Redacted replaces a secret in text passed through Redact.
const TestKeyringEnv = "CLI_KIT_TEST_KEYRING"
TestKeyringEnv names the environment variable that lets a test binary use the operating system keyring: tests run with CLI_KIT_TEST_KEYRING=system reach it.
Variables ¶
var ( // ErrNoSource reports that no source offered a secret: no file, no // environment variable, nothing on stdin, nothing stored, and no // terminal to ask on. It is typical of a CI job or a service unit. ErrNoSource = errors.New("secret: no secret available") // ErrFixedSource reports, from [Resolver.Forget], that a rejected // secret came from a source the Resolver cannot change, such as an // environment variable. Asking again would return the same secret, so // the user has to fix the source. ErrFixedSource = errors.New("secret: rejected secret comes from a fixed source") // ErrMismatch reports that the two entries of a confirmed prompt // differ. ErrMismatch = errors.New("secret: entries do not match") )
var ( // ErrNotFound reports that a store holds no secret for an account. ErrNotFound = errors.New("secret: not found") // ErrEmpty reports an attempt to store or use an empty secret. ErrEmpty = errors.New("secret: empty value") )
var ErrInsecureFile = errors.New("secret: insecure secret file")
ErrInsecureFile reports a secret file that is a symbolic link, not a regular file, or readable by other users. A FileStore refuses to read such a file rather than trust a secret someone else could have planted or read.
var ErrNoService = errors.New("secret: keyring service name is required")
ErrNoService reports a Keyring used without a service name.
var ErrTestKeyring = errors.New("secret: the operating system keyring is not used in tests")
ErrTestKeyring reports a Keyring used in a test binary, which leaves the operating system keyring alone; see Keyring.
ErrUnavailable is what a store from Unavailable fails with when it was given no error of its own.
Functions ¶
func Redact ¶
Redact returns text with every occurrence of each secret replaced by Redacted. Use it on anything that may carry a secret before it is logged or shown: an HTTP dump, an error from a server that echoes its input. Empty secrets are ignored; longer secrets are replaced first, so a secret that contains another is removed whole.
Example ¶
package main
import (
"fmt"
"github.com/mittwald/cli-kit/secret"
)
func main() {
token := "glpat-abc123"
fmt.Println(secret.Redact("GET /api?private_token=glpat-abc123", token))
}
Output: GET /api?private_token=[REDACTED]
func TTYPrompt ¶
TTYPrompt is the default PromptFunc. It asks on the controlling terminal, which works even when stdin and stdout are redirected, and reads the answer with echo turned off. Without a controlling terminal it returns an error wrapping ErrNoSource.
func WriteFile ¶ added in v0.3.0
WriteFile writes data to path for its owner's eyes only: the file gets mode 0600 (outside Windows) before any data reaches it, and replaces an existing file atomically, so a reader sees the old contents or the new ones, never part of either, and the new contents are never readable by others, whatever mode the old file had. Use it for anything that holds a credential, such as a token cache.
The directory must exist. A symbolic link at path is refused with an error wrapping ErrInsecureFile, so a link planted there cannot redirect the write.
Types ¶
type FileStore ¶
type FileStore struct {
// Dir is the directory holding the secret files.
Dir string
}
FileStore is a Store that keeps each secret in a file of its own, named after the account, in a directory only the owner can enter (mode 0700). Each file is readable by its owner only (mode 0600) and is replaced atomically, so an interrupted write never leaves half a secret behind.
The files are not encrypted: anyone who can act as the user can read them. Prefer Keyring, and use a FileStore as the Fallback where no keyring exists, such as on servers and in containers.
func NewFileStore ¶
NewFileStore returns a FileStore in the directory named app under the user's configuration directory (os.UserConfigDir), such as ~/.config/example-tool on Linux.
type Keyring ¶
type Keyring struct {
// Service is the keyring service name. It is required.
Service string
}
Keyring is a Store backed by the operating system keyring: the macOS Keychain, the Windows Credential Manager, or a Secret Service provider (GNOME Keyring, KWallet) over D-Bus on Linux and BSD.
Service names the application, such as "example-tool"; every account is stored under it. Use a second service name, such as "example-tool-user", to keep unrelated values, such as a user name, apart from passwords.
Where no keyring is available, every method fails with an error that does not wrap ErrNotFound; wrap the Keyring in Fallback to keep working.
A test binary (see testing.Testing) never reaches the operating system keyring, so no test can read, overwrite or delete the secrets of whoever runs it: every method fails with an error wrapping ErrTestKeyring, as if there were no keyring, and a Fallback moves on to its secondary store. This is done by switching the go-keyring package, which Keyring calls, to its mock when the test binary starts. A test that needs a working keyring uses a Memory store in its place, or installs go-keyring's in-memory mock with gokeyring.MockInit. Tests that are meant to reach the operating system keyring run with the environment variable TestKeyringEnv set to "system".
type Memory ¶
type Memory struct {
// contains filtered or unexported fields
}
Memory is a Store that keeps secrets in memory, for tests. The zero value is an empty store ready to use; it is safe for concurrent use.
type PromptFunc ¶
PromptFunc asks the user for a secret without echoing it. It returns an error wrapping ErrNoSource when there is no terminal to ask on.
TTYPrompt is the default. A tool with its own input widget, such as pick.Input from this module, turns it into a PromptFunc with InputPrompt.
func InputPrompt ¶ added in v0.4.0
func InputPrompt(in, out *os.File, input func(in, out *os.File, prompt string) (string, error)) PromptFunc
InputPrompt returns a PromptFunc that asks with input, a text field that draws nothing for what is typed, on in and out. With pick.Input from this module:
prompt := secret.InputPrompt(os.Stdin, os.Stderr,
func(in, out *os.File, prompt string) (string, error) {
return pick.Input(in, out, pick.InputOptions{Prompt: prompt, Secret: true})
})
Unlike TTYPrompt it asks on in and out only. Where either is not a terminal it returns ErrNoSource without calling input, so a Resolver names the sources the user could offer instead. Before the first question of a request it writes the request's Hint to out, its URLs as hyperlinks. The question passed to input is Request.Prompt; input's errors are returned as they are.
type Request ¶
type Request struct {
// Label is the question, such as "Password" or "Password to encrypt
// the export".
Label string
// Name is the secret as the messages call it, such as "password". The
// second question of a confirmed entry asks to repeat it.
Name string
// Hint is optional text to show before the first question, such as
// where to create a token and which scopes it needs. The prompts of this
// package show the URLs in it as hyperlinks (see term.Linkify).
Hint string
// Repeat marks the second question of a confirmed entry.
Repeat bool
}
Request describes one interactive question for a PromptFunc.
type Resolver ¶
type Resolver struct {
// Name is the secret as the messages call it, such as "password" or
// "API token". Empty means "secret".
Name string
// Label is the question an interactive prompt asks, such as "Password
// to encrypt the export". Empty means Name with a capital first letter.
Label string
// Account is the name the secret is stored under in Store. It is
// required when Store is set.
Account string
// Store remembers the secret between runs.
Store Store
// IgnoreStore skips reading Store, for a login command that should ask
// for a fresh secret. Save still writes to it.
IgnoreStore bool
// Env is the name of an environment variable that may carry the secret,
// such as "EXAMPLE_TOKEN". An empty value counts as unset.
Env string
// File is a path the user named to read the secret from, or "-" for
// stdin. Only its first line is used.
File string
// FileFlag is the flag that sets File, such as "--password-file". It is
// only used to word errors.
FileFlag string
// Stdin is the standard input to read a piped secret from; nil means
// os.Stdin.
Stdin *os.File
// StdinBusy says stdin carries the command's own input, so a piped
// stdin is not taken for the secret, and File "-" is refused.
StdinBusy bool
// Prompt asks interactively; nil means [TTYPrompt].
Prompt PromptFunc
// Hint is shown before an interactive prompt, never otherwise.
Hint string
// Confirm asks twice and compares, but only when prompting: a file or a
// pipe cannot be mistyped.
Confirm bool
// TrimSpace removes leading and trailing white space from the secret,
// as suits tokens. Without it only a trailing line ending is removed
// from file and stdin input, so a passphrase keeps its spaces.
TrimSpace bool
// MaxLen bounds a read from a file or stdin; zero means
// [DefaultMaxLen].
MaxLen int
}
Resolver finds one secret. See the package documentation for the order in which it tries its sources. All fields are optional; a source whose field is empty is skipped.
Its errors are worded for the user of the command, such as "no password found in /run/secrets/pw", and match the package's sentinel errors (ErrEmpty, ErrNoSource, ErrMismatch, ErrFixedSource) with errors.Is.
Example ¶
A token is looked up in $EXAMPLE_TOKEN, then in the keyring (or, without one, in a file under the user's configuration directory), and asked for interactively as a last resort. It is saved only after the service accepted it, and dropped again when the service rejects it.
package main
import (
"fmt"
"os"
"github.com/mittwald/cli-kit/secret"
)
func main() {
files, err := secret.NewFileStore("example-tool")
if err != nil {
fmt.Println(err)
return
}
r := &secret.Resolver{
Name: "API token",
Account: "default",
Store: secret.Fallback(secret.Keyring{Service: "example-tool"}, files),
Env: "EXAMPLE_TOKEN",
Hint: "Create a token at https://example.com/settings/tokens.",
TrimSpace: true,
}
call := func(token string) error { return nil } // a request to the service
for range 2 {
token, source, err := r.Resolve()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
err = call(token)
if err == nil {
_ = r.Save(token)
return
}
if forgetErr := r.Forget(source); forgetErr != nil {
fmt.Fprintln(os.Stderr, forgetErr)
return
}
}
}
Output:
func (*Resolver) Forget ¶
Forget prepares a retry after a service rejected the secret that came from source. A stored secret is deleted, so the next Resolve asks again; a prompted one needs nothing. A secret from a file, the environment or stdin would come back unchanged, so Forget returns an error wrapping ErrFixedSource that tells the user what to change; do not retry then.
func (*Resolver) Lookup ¶
Lookup returns the secret only when it is available without asking or reading stdin: from File (unless "-"), the environment or the Store. It returns an error wrapping ErrNotFound when none of them has it. Use it for optional work, such as an extra column only shown when a token is already configured.
type Source ¶
type Source int
Source says where a Resolver found a secret.
const ( // SourceNone means no secret was found. SourceNone Source = iota // SourceFile is a file the user named, such as through --password-file. SourceFile // SourceEnv is an environment variable. SourceEnv // SourceStdin is a piped or redirected standard input, including a // file named "-". SourceStdin // SourceStore is the Resolver's Store, holding a secret from an // earlier run. SourceStore // SourcePrompt is an interactive prompt. SourcePrompt )
type Store ¶
type Store interface {
// Get returns the secret stored for account, or an error wrapping
// ErrNotFound when there is none.
Get(account string) (string, error)
// Set stores value for account, replacing any earlier value. It refuses
// an empty value with ErrEmpty.
Set(account, value string) error
// Delete removes the secret stored for account, or returns an error
// wrapping ErrNotFound when there is none.
Delete(account string) error
}
Store keeps one secret per account name.
func Fallback ¶
Fallback returns a Store that uses primary and falls back to secondary when primary fails. It suits a keyring that may be missing (a server without a Secret Service, a container), with a FileStore behind it:
- Get reads primary, and secondary when primary has no secret or fails. When secondary has no secret either, the error wraps ErrNotFound, also when primary failed, so a Resolver goes on to prompt; it wraps primary's failure too.
- Set writes primary, and secondary only when primary fails.
- Delete removes the account from both, so a secret written to the secondary while the primary was unavailable does not come back. It succeeds when either store removed the secret.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/mittwald/cli-kit/secret"
)
func main() {
keyring := secret.NewMemory(nil) // stands in for secret.Keyring
files := &secret.Memory{} // stands in for a *secret.FileStore
store := secret.Fallback(keyring, files)
_ = store.Set("default", "hunter2")
value, err := store.Get("default")
fmt.Println(value, errors.Is(err, secret.ErrNotFound))
}
Output: hunter2 false
func Migrating ¶ added in v0.4.0
Migrating returns a Store that works like Fallback(primary, secondary) and also moves secrets from secondary into primary. It suits a tool that kept its secrets in files before it used a keyring, and a keyring that was missing when a secret was saved:
- Get reads primary. When primary answers that it holds no secret for the account, Get reads secondary, stores the value in primary and only then deletes it from secondary. When primary does not take the value, the secondary copy stays where it is. Failing to delete the copy is not an error, since primary is read first from then on.
- When primary fails for another reason, such as a missing keyring, secondary is the store: Get returns what secondary returns, its errors alone, and moves nothing.
- Set and Delete are those of Fallback.
Example ¶
A tool that kept its token in a file before it used the keyring finds it there once more, and moves it into the keyring on the way.
package main
import (
"errors"
"fmt"
"github.com/mittwald/cli-kit/secret"
)
func main() {
keyring := secret.NewMemory(nil) // stands in for secret.Keyring
files := secret.NewMemory(map[string]string{"default": "hunter2"}) // stands in for a *secret.FileStore
store := secret.Migrating(keyring, files)
value, _ := store.Get("default")
_, inFiles := files.Get("default")
moved, _ := keyring.Get("default")
fmt.Println(value, moved, errors.Is(inFiles, secret.ErrNotFound))
}
Output: hunter2 hunter2 true
func Unavailable ¶ added in v0.4.0
Unavailable returns a Store that is not there: every method fails with err, or with ErrUnavailable when err is nil. Use it in place of a store that could not be set up, such as a FileStore whose directory could not be located: a Fallback in front of it moves on, and err is reported once the store is needed. An err that wraps ErrNotFound makes the store look empty rather than missing.