std.keychain

The operating system's credential store: the login Keychain on macOS, Credential Manager on Windows, and the Secret Service (GNOME Keyring or KWallet) on Linux. What it returns is already a secret. Package code needs the keychain capability.

import std.keychain

keychain.set("acme-api", "default", token)   # store; a string or a secret
key = keychain.get("acme-api", "default")    # a secret, or null if absent
keychain.delete("acme-api", "default")       # true if there was one to remove

Naming a credential

Every platform store names a credential by two strings, and so does this module: the service, which is your program or the API the credential is for, and the account, which is a user name or something like "default" when there is only one. Both must be non-empty. set replaces a value already stored under the same pair.

Values are text. set takes a string, or a secret holding one, so a value that arrived wrapped can be stored without a reveal.

get returns a secret

key = keychain.get("acme-api", "default")
if key == null {
    print("not logged in - run `acme login` first")
    os.exit(1)
}
print(key)                          # [secret]
client = acme.connect(token: reveal(key))

The value reads as [secret] in every print, log line and error message until reveal takes it out. null means there is no such entry - an expected answer for a credential nobody has stored yet, not an error.

When there is no keychain

When the store cannot be reached, or refuses, the call throws { kind: "os" }. The common case is a Linux server: the Secret Service runs inside a desktop session, and a server has none - no D-Bus session either - so the message says to keep the secret in the environment there. A keychain suits a tool that runs on someone's own machine, like a command-line client that remembers a login; a service reads os.env.

import std.keychain
import std.os

fn api_key() {
    try {
        found = keychain.get("acme-api", "default")
        if found != null { return found }
    } catch (e) {
        # no keychain on this machine - fall through to the environment
    }
    secret(os.env("ACME_API_KEY"))
}

A stored value that is not UTF-8 text is an os error too. A value is never part of an error message.

The keychain capability

A package needs keychain granted to read, write or delete an entry. It is a capability of its own, not part of env: granting a package the environment is common, while the keychain holds credentials other programs saved, and a write or delete there outlives your program. Root code - your own program - holds every capability.