secrets

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package secrets stores secret values encrypted at rest (story #75, ADR 0024).

A secret is an opaque value of at most MaxValueBytes, stored once under a name in the secret table and referenced from configuration by a key ending in _ref. Values are sealed with AES-256-GCM under a data key derived with HKDF-SHA256 from a 32-byte master key read from a file (secrets.key_file) or from ANGELIA_SECRETS_KEY. The envelope carries a version byte, the key id and a random nonce, and its associated data binds it to the row's id and name, so a ciphertext copied into another row, or a row renamed in SQL, no longer opens.

Plaintext only ever lives in a Value, which prints, logs and encodes as [REDACTED]; Value.Reveal returns a copy of the bytes where a request is built. Errors never carry a value, a ciphertext or key material.

A Resolver turns a reference into a value, refusing a secret bound to hosts (ADR 0024 §2) for any other destination. CheckStartup refuses to start without a key while secrets are stored, and Rotate re-seals every row under the primary key.

Index

Constants

View Source
const (

	// KeySize is the size of a master key in bytes.
	KeySize = 32
	// MaxValueBytes is the largest secret value (64 KiB).
	MaxValueBytes = 64 << 10
)

Envelope layout (ADR 0024 §3): byte 0 the version, bytes 1-8 the key id, bytes 9-20 the nonce, then the GCM ciphertext and its 16-byte tag.

View Source
const MaxHosts = 32

MaxHosts bounds the hosts a secret is bound to.

View Source
const Redacted = "[REDACTED]"

Redacted is how a Value prints, logs and encodes.

Variables

View Source
var (
	// ErrDecrypt is wrapped by every failure to open an envelope: a wrong
	// key, a tampered or truncated envelope, or one moved to another row.
	// Its message names the secret and the key id only.
	ErrDecrypt = errors.New("secrets: cannot decrypt")
	// ErrUnknownKey is wrapped when an envelope names a key id that is not
	// configured, or has a version this build does not know.
	ErrUnknownKey = errors.New("secrets: unknown key")
)
View Source
var (
	// ErrNotFound is wrapped when a reference names a secret that does
	// not exist.
	ErrNotFound = errors.New("secrets: no such secret")
	// ErrKeyMissing is wrapped when a secret is read or written while no
	// key is configured.
	ErrKeyMissing = errors.New("secrets: no key configured")
	// ErrInvalidName is wrapped when a reference is not a valid secret
	// name.
	ErrInvalidName = errors.New("secrets: invalid secret name")
)
View Source
var ErrHostMismatch = errors.New("secrets: host not allowed")

ErrHostMismatch is wrapped when a secret bound to hosts is refused for a destination outside them.

View Source
var ErrRotateIncomplete = errors.New("secrets: rotation incomplete")

ErrRotateIncomplete is returned when some rows could not be re-sealed because concurrent writes kept winning; rerun the rotation.

View Source
var ErrStartup = errors.New("secrets")

ErrStartup is wrapped by the errors of CheckStartup.

Functions

func CheckCounts

func CheckCounts(counts map[string]int64, keys *Keyring) error

CheckCounts is CheckStartup on counts already read.

func CheckStartup

func CheckStartup(ctx context.Context, st Counter, keys *Keyring) error

CheckStartup is the startup check of every role (ADR 0024 §4): with stored secrets and no key, or with rows sealed by a key id that is not configured, the instance must not start. There is no plaintext fallback.

func Destination

func Destination(u *url.URL) (string, error)

Destination is the canonical "host:port" of an http(s) URL: the host lower-cased, the port explicit (443 for https, 80 for http). A host that is not ASCII must be written as punycode; it is refused, never converted.

func EnvelopeKeyID

func EnvelopeKeyID(envelope []byte) string

EnvelopeKeyID returns the hex key id an envelope names, or "" when it is too short to name one.

func Summary

func Summary(counts map[string]int64, keys *Keyring) string

Summary is the one-line report of `angelia config check`.

func ValidHost

func ValidHost(s string) bool

ValidHost reports whether s is a hosts entry (ADR 0024 §2), in the syntax of a plugin credential key: "host" (port 443) or "host:port", the host a lower-case hostname (IDNA as punycode) without a trailing dot, or a canonical IP literal ([addr]:port for IPv6 with a port). No wildcards.

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a valid secret name, the value of a *_ref key: ^[a-z0-9][a-z0-9._-]{0,62}$.

func WriteKeyFile

func WriteKeyFile(path string) error

WriteKeyFile creates path with mode 0600 and writes a new key to it. It refuses to overwrite an existing file.

Types

type Bound

type Bound struct {
	Name  string
	Value Value
	// Hosts is the secret's binding; empty means unbound.
	Hosts []string
}

Bound is a resolved secret with the hosts it may be sent to. Its error messages name the secret and the destination's scheme and host, never the value.

func (Bound) Allows

func (b Bound) Allows(u *url.URL) error

Allows checks that the secret may be sent to u: always when it is unbound, otherwise only when u's canonical host and port equal one entry of Hosts. A refusal wraps ErrHostMismatch.

func (Bound) CheckRedirect

func (b Bound) CheckRedirect(next func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error

CheckRedirect returns an http.Client CheckRedirect that refuses every redirect hop the secret may not follow, then applies next (nil: the default limit of 10 hops). A source that follows redirects with a bound secret uses it, so the secret never leaves its hosts.

type Counter

type Counter interface {
	CountSecretsByKeyID(ctx context.Context) (map[string]int64, error)
}

Counter counts the stored secrets per key id.

type KeyConfig

type KeyConfig struct {
	// KeyFile is secrets.key_file: the primary key, base64 in a file.
	KeyFile string
	// Key is the value of ANGELIA_SECRETS_KEY: the primary key inline.
	// Setting it together with KeyFile is an error.
	Key Value
	// PreviousKeyFiles are keys that only decrypt (rotation, restored
	// backups).
	PreviousKeyFiles []string
}

KeyConfig says where the master keys come from (ADR 0024 §4).

func (KeyConfig) Configured

func (c KeyConfig) Configured() bool

Configured reports whether any key is configured.

type KeyStatus

type KeyStatus struct {
	KeyID string
	Rows  int64
	// Role is "primary", "previous" or "" (not configured).
	Role string
}

KeyStatus is one line of `angelia secrets status`: a key id, how many rows it sealed, and whether it is configured.

func Status

func Status(counts map[string]int64, keys *Keyring) []KeyStatus

Status lists every configured key id and every key id that sealed a row, the primary first, then the previous keys, then the unknown ones.

type Keyring

type Keyring struct {
	// contains filtered or unexported fields
}

Keyring holds the primary key, which seals, and the previous keys, which only open (during a rotation, or to read a restored backup).

func LoadKeyring

func LoadKeyring(c KeyConfig) (*Keyring, []string, error)

LoadKeyring reads the configured keys. With no key configured it returns a nil Keyring and no error: an instance without stored secrets needs no key, and CheckStartup refuses to start one that has some. Warnings name a key file only group members can read. Errors never quote a file's content.

func NewKeyring

func NewKeyring(primary []byte, previous ...[]byte) (*Keyring, error)

NewKeyring builds a keyring from 32-byte master keys: primary seals, and every key opens. A previous key equal to the primary is ignored.

func (*Keyring) Has

func (k *Keyring) Has(id string) bool

Has reports whether id is a configured key id.

func (*Keyring) IDs

func (k *Keyring) IDs() []string

IDs lists the configured key ids, the primary first.

func (*Keyring) Open

func (k *Keyring) Open(id, name string, envelope []byte) (Value, error)

Open decrypts the envelope of the row (id, name). Every failure is an error naming the secret and the key id, never the bytes: ErrUnknownKey for a key id that is not configured or an unknown version, ErrDecrypt otherwise.

func (*Keyring) PrimaryID

func (k *Keyring) PrimaryID() string

PrimaryID is the hex id of the key that seals.

func (*Keyring) Seal

func (k *Keyring) Seal(id, name string, plaintext []byte) (envelope []byte, keyID string, err error)

Seal encrypts plaintext for the row (id, name) under the primary key and returns the envelope and the key id. Each call draws a fresh random nonce, so two seals of one plaintext differ.

type Lookup

type Lookup interface {
	SecretByName(ctx context.Context, name string) (store.Secret, error)
}

Lookup is the store read a Resolver needs.

type Resolver

type Resolver struct {
	Store Lookup
	// Keys opens the envelopes; nil means no key is configured.
	Keys *Keyring
}

Resolver turns a *_ref reference into the secret's value, for one destination. It reads the store on every call: values are not cached across attempts (ADR 0024 §6).

func (*Resolver) Resolve

func (r *Resolver) Resolve(ctx context.Context, name string, dest *url.URL) (Bound, error)

Resolve returns the secret named name for a request to dest. A secret bound to hosts is resolved only when dest's canonical host and port equal one of them, before anything is decrypted; with a nil dest a bound secret is refused. The caller re-checks every further request that carries the value (each redirect hop) with Bound.Allows or Bound.CheckRedirect. Errors name the secret and the host, never the value: ErrInvalidName, ErrNotFound, ErrKeyMissing, ErrHostMismatch, ErrUnknownKey or ErrDecrypt.

func (*Resolver) ResolveSelfAddressed

func (r *Resolver) ResolveSelfAddressed(ctx context.Context, name string) (Bound, error)

ResolveSelfAddressed returns the secret named name with its hosts, for a reference whose resolved value is itself the destination (a reference the kind's config_schema marks x-angelia-secret-destination, ADR 0026 §2). The destination is known only after decrypting, so nothing is checked against the hosts here: the caller derives the origins from the value and checks each with Bound.Allows before any byte of the value leaves the process. Errors are those of Resolve, without ErrHostMismatch.

type RotateOptions

type RotateOptions struct {
	// DryRun reports what would be re-sealed and writes nothing.
	DryRun bool
	// Batch is the number of rows per transaction; <= 0 means one
	// transaction for every row.
	Batch int
	// Logger receives the audit record of the run; nil discards it.
	Logger *slog.Logger
}

RotateOptions controls Rotate.

type RotateReport

type RotateReport struct {
	// From counts, per old key id, the rows re-sealed (or, in a dry run,
	// that would be).
	From map[string]int
	// Resealed is the number of rows re-sealed.
	Resealed int
	// Skipped names the rows that kept losing to concurrent writes.
	Skipped []string
	// PrimaryID is the key every row is sealed with afterwards.
	PrimaryID string
}

RotateReport says what a rotation did.

func Rotate

Rotate re-seals under the primary key every stored secret sealed with another configured key (ADR 0024 §5). Each batch is one transaction: a crash rolls it back and leaves every row under a configured key, and a rerun is idempotent. Every row update is fenced by the row's revision; a row that loses is read again and retried, at most three times, then left alone and reported. Values are never logged.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value holds a plaintext secret: a stored secret's value, or a token read from the environment. It prints as [REDACTED] under every fmt verb, in slog and in JSON or text encodings, so a struct holding one can be logged safely. The zero Value is empty.

func GenerateKey

func GenerateKey() (Value, error)

GenerateKey returns a new random master key in the key file format: the standard base64 encoding of 32 bytes and a newline.

func NewValue

func NewValue(b []byte) Value

NewValue returns a Value holding a copy of b.

func NewValueString

func NewValueString(s string) Value

NewValueString returns a Value holding s.

func (Value) Equal

func (v Value) Equal(b []byte) bool

Equal compares the plaintext with b in constant time (for equal lengths).

func (Value) Format

func (Value) Format(f fmt.State, _ rune)

Format implements fmt.Formatter: every verb prints [REDACTED].

func (Value) GoString

func (Value) GoString() string

GoString implements fmt.GoStringer: it never prints the value.

func (Value) IsZero

func (v Value) IsZero() bool

IsZero reports whether the value is empty.

func (Value) Len

func (v Value) Len() int

Len is the length of the plaintext in bytes.

func (Value) LogValue

func (Value) LogValue() slog.Value

LogValue implements slog.LogValuer: it never logs the value.

func (Value) MarshalJSON

func (Value) MarshalJSON() ([]byte, error)

MarshalJSON encodes the value as "[REDACTED]".

func (Value) MarshalText

func (Value) MarshalText() ([]byte, error)

MarshalText encodes the value as [REDACTED].

func (Value) Reveal

func (v Value) Reveal() []byte

Reveal returns a copy of the plaintext, so that a caller cannot change the held value. Call it only where a request is built.

func (Value) String

func (Value) String() string

String implements fmt.Stringer: it never prints the value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL