keyring

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: AGPL-3.0 Imports: 26 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 keyring holds the master keys of ADR-0011: the Keyring loaded through a key provider, each key's id derived from its material, the sub-keys derived per purpose, AES-256-GCM encryption of secret fields, the active key and the key canary in keyring_state, and the replica key records in replicas. Key material never leaves this package: it is not stored, logged or returned, and no error carries it; the Keyring keeps only the derived sub-keys, and the process memory stays as sensitive as the keys (ADR-0011).

Index

Constants

View Source
const (
	SecretKeysVar     = "MUSTER_SECRET_KEYS"
	SecretKeysFileVar = "MUSTER_SECRET_KEYS_FILE"
)

The variables of the master keys.

View Source
const (
	// KeyRecordRefresh is replica.key_record_refresh: how often a replica refreshes its record.
	KeyRecordRefresh = 30 * time.Second
	// LiveExpiry is replica.live_expiry: a replica is live while its record is younger.
	LiveExpiry = 2 * time.Minute
	// PruneAfter is replica.prune_after: the Leader removes a record not refreshed for this long.
	PruneAfter = time.Hour
	// ReregisterAfter is leader.absence_notice: a replica that could not refresh its record for longer, because it
	// lost the database, re-registers with a new start time, so that it does not count as having run across the
	// outage and the next Leader records the downtime. internal/leader checks that the two agree.
	ReregisterAfter = 2 * time.Minute
)
View Source
const (
	ActionKeyActivated = "keyring.key_activated"
	ResourceKeyring    = "keyring"
)

ActionKeyActivated is the Audit log action of `muster secrets rotate-key`, and ResourceKeyring its resource type.

View Source
const Channel = "muster_keyring"

Channel is the LISTEN/NOTIFY channel of key activations: every replica switches to the active key when it hears it, and the Leader re-renders the open Root messages whose buttons another key signed.

View Source
const DevelopmentKey = "bXVzdGVyLWRldi1vbmx5LWtleS1ub3QtYS1zZWNyZXQ="

DevelopmentKey is the published master key of `muster dev`, the base64 of "muster-dev-only-key-not-a-secret". Development mode accepts it; the server command refuses it outside development mode.

View Source
const KeySize = 32

KeySize is the size of a master key and of each sub-key, in bytes.

View Source
const MinSignaturePrefix = 16

MinSignaturePrefix is the shortest signature VerifyPrefix accepts: 128 bits.

View Source
const Placeholder = "REPLACE-ME-with-openssl-rand-base64-32"

Placeholder is the value of MUSTER_SECRET_KEYS in the compose example, refused until it is replaced.

Variables

View Source
var (
	// ErrNoActiveKey is returned by Encrypt and Sign before the canary check has set the active key.
	ErrNoActiveKey = errors.New("the keyring has no active key yet")
	// ErrKeyNotHeld is wrapped when a ciphertext or a signature names a key that is not in the Keyring.
	ErrKeyNotHeld = errors.New("the key is not in the keyring")
	// ErrDecrypt is wrapped when a ciphertext does not open: another field, another key or altered bytes.
	ErrDecrypt = errors.New("cannot decrypt")
)
View Source
var Clear = SecretInput{Given: true, Null: true}

Clear is the input of a Secret field set to null.

View Source
var ErrEmptySecret = errors.New("a secret value is empty; send null to clear it")

ErrEmptySecret refuses an empty value: a Secret is cleared with null, never with "".

View Source
var ErrKeyMismatch = errors.New("master key does not match the database")

ErrKeyMismatch is the canary error: the Keyring cannot decrypt the key canary, or a running replica sees an active key it does not hold. The replica stops.

View Source
var Keep = SecretInput{}

Keep is the input of an omitted Secret field.

Functions

func EncryptedFields

func EncryptedFields() []string

EncryptedFields are the fields rotation re-encrypts, in its order: every field of the encrypted_values view.

func KeyID

func KeyID(material []byte) string

KeyID is the id of a key: "k-" and the first 64 bits of the SHA-256 of its material, in hex. It is the same on every replica and after every restart, and does not reveal the material.

func NewReplicaID

func NewReplicaID(hostname string) string

NewReplicaID is the id of a replica, chosen at process start: the host name and a random suffix.

func PruneReplicas

func PruneReplicas(ctx context.Context, p Pruner, log *logging.Logger, now time.Time) error

PruneReplicas is the Leader task that removes the records not refreshed for PruneAfter at now, on the real clock, and logs replicas_pruned when it removed any. Running it twice removes nothing more.

Types

type EncryptedValue

type EncryptedValue struct {
	Row        RowKey
	Ciphertext []byte
	KeyID      string
}

EncryptedValue is one stored value of an encrypted field, with the key that encrypted it.

type Env

type Env struct {
	// Keys is the value of the variable, or the content of the file.
	Keys logging.Secret
	// Source is the variable that was set: SecretKeysVar or SecretKeysFileVar; empty when neither was.
	Source string
}

Env is the key provider of the environment: MUSTER_SECRET_KEYS holds base64 keys separated by commas, and the file that MUSTER_SECRET_KEYS_FILE names holds one key per line. Errors name the variable and the position of a key in the list, never a value.

func (Env) MasterKeys

func (e Env) MasterKeys(context.Context) ([][]byte, error)

type KeyState

type KeyState string

KeyState is what the Keyring status says of a key (C-20.FR-6).

const (
	KeyActive       KeyState = "active"
	KeyNeeded       KeyState = "needed"
	KeyRemovable    KeyState = "removable"
	KeyNotActiveYet KeyState = "not_active_yet"
)

The states of a key, in the order they are decided: the active key; else a key a Secret or an open Root message still depends on; else a key that was active before and can be removed; else a key never active, such as one added for a rotation that has not run yet, which is activated, never removed.

type KeyStatus

type KeyStatus struct {
	ID        string
	Active    bool
	HeldBy    []string
	MissingOn []string
	Needed    bool
	Removable bool
	State     KeyState
	// EncryptedValues are the rows of encrypted_values the key encrypted, and OpenMessages the Root messages of open
	// Alert Groups, not deleted in the messenger, retired or withheld, whose buttons it signed, the older ones a
	// republication past a bridge's edit window replaced included.
	EncryptedValues int64
	OpenMessages    int64
}

KeyStatus is one key of the Keyring status: the live replicas that hold it and those that lack it, by replica id, what still depends on it and its state.

type Keyring

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

Keyring is the master keys of the process, in the order of the provider, and the active key.

func Load

func Load(ctx context.Context, p Provider, allowDevelopmentKey bool) (*Keyring, error)

Load makes the Keyring from the keys of p; see New for allowDevelopmentKey.

func New

func New(keys [][]byte, allowDevelopmentKey bool) (*Keyring, error)

New makes a Keyring of keys, each KeySize bytes; it derives the ids and sub-keys and clears the material. A key given twice is refused. With allowDevelopmentKey false, the published development key is refused.

func (*Keyring) ActiveKeyID

func (k *Keyring) ActiveKeyID() string

ActiveKeyID is the id of the active key, empty before the canary check.

func (*Keyring) ApplySecret

func (k *Keyring) ApplySecret(field string, stored StoredSecret, in SecretInput, now time.Time) (StoredSecret, bool,
	error)

ApplySecret applies in to the field as stored, encrypting a new value for field with the active key at now. It returns the field to store and whether it changed: keeping never changes it, clearing changes a field that is set, and a replacement always does, even with the same value, because only the ciphertext is known.

func (*Keyring) Decrypt

func (k *Keyring) Decrypt(field, keyID string, ciphertext []byte) ([]byte, error)

Decrypt opens a ciphertext of field written with the key keyID, which may be any key of the Keyring. The error names the field and the key id, never the plaintext.

func (*Keyring) Encrypt

func (k *Keyring) Encrypt(field string, plaintext []byte) (ciphertext []byte, keyID string, err error)

Encrypt encrypts a secret field with the active key: a random nonce and AES-256-GCM, with the field name bound as associated data, so that the ciphertext opens only for that field. It returns the ciphertext and the key id to store next to it.

func (*Keyring) Establish

func (k *Keyring) Establish(ctx context.Context, s Store, now time.Time) (State, error)

Establish returns the keyring state, writing it first on a new database: the first key of the Keyring becomes active and the canary is encrypted with it. The caller holds the migration lock, so replicas starting together write one canary. now is the business time of the activation.

func (*Keyring) Holds

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

Holds reports whether the key with id is in the Keyring.

func (*Keyring) KeyIDs

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

KeyIDs are the ids of the keys, in the order of the provider.

func (*Keyring) Open

func (k *Keyring) Open(ctx context.Context, log *logging.Logger, st State) error

Open decrypts the canary of st. On success the active key of st becomes the Keyring's and keyring_loaded is logged; otherwise key_canary_failed is logged and ErrKeyMismatch returned.

func (*Keyring) OpenSecret

func (k *Keyring) OpenSecret(field string, s StoredSecret) (logging.Secret, error)

OpenSecret decrypts the field; a field that is not set is the empty Secret.

func (*Keyring) Sign

func (k *Keyring) Sign(p Purpose, msg []byte) (mac []byte, keyID string, err error)

Sign returns an HMAC-SHA256 of msg with the active key's sub-key for p, which is a signature purpose, and the id of that key.

func (*Keyring) Verify

func (k *Keyring) Verify(p Purpose, keyID string, msg, mac []byte) (bool, error)

Verify checks a signature made by Sign with the key keyID, which may be any key of the Keyring.

func (*Keyring) VerifyPrefix

func (k *Keyring) VerifyPrefix(p Purpose, keyID string, msg, prefix []byte) (bool, error)

VerifyPrefix checks a signature made by Sign with the key keyID, which may be any key of the Keyring, and cut to its first bytes, at least MinSignaturePrefix of them, as a button action id carries it.

type Provider

type Provider interface {
	MasterKeys(ctx context.Context) ([][]byte, error)
}

Provider returns the master keys, KeySize bytes each, in their order: on a new database the first one becomes active. Env reads the environment; an external key service would be another Provider (ADR-0011).

type Pruner

type Pruner interface {
	PruneReplicas(ctx context.Context, refreshedBefore time.Time) (int64, error)
}

Pruner deletes old replica records; *dbgen.Queries implements it.

type Purpose

type Purpose string

Purpose names a sub-key; material derived for one purpose never serves another.

const (
	PurposeEncryption      Purpose = "encryption"
	PurposeButtonSignature Purpose = "button-signature"
	PurposeCSRF            Purpose = "csrf"
)

type Recorder

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

Recorder keeps the record of this replica in replicas, on the real clock, so that the development clock never makes a replica look gone, and stops the replica when the active key is one it does not hold.

func NewRecorder

func NewRecorder(k *Keyring, s Store, realClock clock.Clock, log *logging.Logger, id, hostname, version string,
) *Recorder

NewRecorder prepares the record of the replica id; Start writes it.

func (*Recorder) ID

func (r *Recorder) ID() string

ID is the replica id.

func (*Recorder) Refresh

func (r *Recorder) Refresh(ctx context.Context) error

Refresh refreshes the record, then switches to the active key (Switch).

func (*Recorder) Run

func (r *Recorder) Run(ctx context.Context, ticks <-chan time.Time) error

Run refreshes the record at every tick and whenever woken until ctx ends, when it returns nil, or until the active key is one this replica does not hold, when it returns ErrKeyMismatch. A failed refresh is logged and retried at the next tick.

func (*Recorder) Start

func (r *Recorder) Start(ctx context.Context) error

Start writes the record with the start time.

func (*Recorder) Stop

func (r *Recorder) Stop(ctx context.Context) error

Stop deletes the record, at a graceful shutdown.

func (*Recorder) Switch

func (r *Recorder) Switch(ctx context.Context) error

Switch compares the active key with the keys held: a key that is not held logs active_key_not_held and returns ErrKeyMismatch; another held key becomes the Keyring's active key without a restart, and key_switched is logged once per switch, whoever calls it.

func (*Recorder) Wake

func (r *Recorder) Wake()

Wake makes Run refresh the record and switch keys at once: a key was activated, maybe on another replica, or the LISTEN that would have told is back. Wakes that come meanwhile are merged.

type Replica

type Replica struct {
	ID          string
	Hostname    string
	Version     string
	KeyIDs      []string
	StartedAt   time.Time
	RefreshedAt time.Time
}

Replica is the record of a running replica: the ids of the keys it holds.

func LiveReplicas

func LiveReplicas(ctx context.Context, s Store, now time.Time) ([]Replica, error)

LiveReplicas are the replicas whose record is younger than LiveExpiry at now, on the real clock.

type ReplicasLackKeyError

type ReplicasLackKeyError struct {
	KeyID    string
	Replicas []string
}

ReplicasLackKeyError refuses an activation while live replicas do not hold the key (C-20.FR-7, ADR-0011).

func (*ReplicasLackKeyError) Error

func (e *ReplicasLackKeyError) Error() string

type Rotated

type Rotated struct {
	KeyID         string
	Previous      string
	AlreadyActive bool
	Reencrypted   int64
	ToResign      int64
}

Rotated is what an activation did: the key, the key that was active before it, whether it was active already, how many encrypted values it re-encrypted and how many deliveries of open Alert Groups the Leader re-renders.

type Rotation

type Rotation struct {
	Store RotationStore
	// Keys is this process's Keyring: it decrypts with the key each value names and encrypts with the new key.
	Keys  *Keyring
	Audit *audit.Writer
	Log   *logging.Logger
	// Business dates the activation and its Audit entries; Real decides which replica records are live.
	Business clock.Clock
	Real     clock.Clock
}

Rotation is `muster secrets rotate-key` (C-20.FR-7, ADR-0011): the activation of a key every live replica holds.

func (Rotation) Activate

func (r Rotation) Activate(ctx context.Context, keyID, actor string) (Rotated, error)

Activate makes the key keyID active. The caller holds the migration lock, so that a replica that starts meanwhile checks the canary after it. Refused, with ErrKeyNotHeld, when this process does not hold the key, and with a *ReplicasLackKeyError while a live replica lacks it. Otherwise, in one transaction: the active key and its time change and the key canary is encrypted with it; every value of every encrypted field that another key encrypted is decrypted with that key and encrypted with this one, keeping the time it last changed; keyring.key_activated is recorded per Organization with the actor cli, the name, the diff of /active_key_id and the counts; and the organization and system-status hints and the keyring notification are sent, delivered when it commits. A value that does not decrypt rolls everything back.

A key that is active already changes nothing but values another key still encrypted, which a replica that had not switched yet may have written: they are re-encrypted, without an Audit entry.

type RotationQueries

type RotationQueries interface {
	LockKeyringState(ctx context.Context) (string, error)
	ActivateKey(ctx context.Context, arg dbgen.ActivateKeyParams) (int64, error)
	ListLiveReplicas(ctx context.Context, liveSince time.Time) ([]dbgen.Replica, error)
	ListOrganizationIDs(ctx context.Context) ([]int64, error)
	CountOpenDeliveriesSignedByOtherKey(ctx context.Context, arg dbgen.CountOpenDeliveriesSignedByOtherKeyParams) (
		int64, error)
	NotifyKeyring(ctx context.Context, arg dbgen.NotifyKeyringParams) error
	// Notify sends a live-update hint, delivered when the transaction commits.
	Notify(ctx context.Context, h db.Hint) error
	// EncryptedValues lists, locked, the values of field in the Organization that a key other than keyID encrypted;
	// Reencrypt replaces one of them with ciphertext under keyID while it is still under previous, keeping the time
	// the field last changed, and returns the rows it changed.
	EncryptedValues(ctx context.Context, field string, orgID int64, keyID string) ([]EncryptedValue, error)
	Reencrypt(ctx context.Context, field string, orgID int64, row RowKey, ciphertext []byte, keyID, previous string) (
		int64, error)
	audit.Store
}

RotationQueries are the queries of an activation, in its transaction, with the insert of the Audit log.

type RotationStore

type RotationStore interface {
	InTx(ctx context.Context, f func(RotationQueries) error) error
}

RotationStore runs an activation in one transaction.

func NewRotationStore

func NewRotationStore(pool *pgxpool.Pool) RotationStore

NewRotationStore is the RotationStore over the main pool.

type RowKey

type RowKey struct {
	ID   int64
	Hash []byte
	Name string
}

RowKey names a row of a table with an encrypted field: its id, the state hash of an OIDC redirect, or the Destination and name of a Destination Secret.

func (RowKey) String

func (r RowKey) String() string

String is the row_key of the encrypted_values view.

type SecretInput

type SecretInput struct {
	Given bool
	Null  bool
	Value logging.Secret
}

SecretInput is a Secret field of an update (C-03.FR-21): an omitted value keeps the stored one, null clears it, and a value replaces it.

func Replace

func Replace(value logging.Secret) SecretInput

Replace is the input of a Secret field set to value.

type SecretStatus

type SecretStatus struct {
	Set       bool
	UpdatedAt *time.Time
}

SecretStatus is what a read shows instead of a Secret: whether it is set and when it last changed.

type State

type State struct {
	ActiveKeyID string
	CanaryKeyID string
	Canary      []byte
}

State is the row of keyring_state.

type Status

type Status struct {
	ActiveKeyID string
	Keys        []KeyStatus
}

Status is the Keyring status: the active key and every key held by this process or a live replica, the active key first, then by id.

func ReadStatus

func ReadStatus(ctx context.Context, q StatusQueries, held []string, now time.Time) (Status, error)

ReadStatus reads the Keyring status (C-20.FR-6) with held, the key ids of this process, at now on the real clock, against which replica records are live. Keys are installation-wide, so what depends on them is counted over every Organization.

A key is needed when a row of encrypted_values carries its id or a delivery of an open Alert Group that is not deleted in the messenger, retired or withheld has it as actual_button_key_id or among superseded_button_key_ids, the keys of the older Root messages a republication past a bridge's edit window replaced, whose buttons still work (C-22.FR-9). The re-render after a rotation never re-signs a delivery deleted in the messenger, retired or withheld, so such a delivery must not keep a key needed; nor does it re-sign an older Root message, whose key stays needed until its Alert Group resolves. It was active before when it is the active key, when it is the before or after value of /active_key_id in a keyring.key_activated Audit entry, or when it is needed: only the active key encrypts or signs. It is removable when it was active before and is neither active nor needed.

func (Status) Key

func (s Status) Key(id string) (KeyStatus, bool)

Key is the status of the key id, false when the status does not list it.

type StatusQueries

type StatusQueries interface {
	GetActiveKeyID(ctx context.Context) (string, error)
	ListLiveReplicas(ctx context.Context, liveSince time.Time) ([]dbgen.Replica, error)
	ListOrganizationIDs(ctx context.Context) ([]int64, error)
	CountEncryptedValuesByKey(ctx context.Context, orgID int64) ([]dbgen.CountEncryptedValuesByKeyRow, error)
	CountOpenButtonKeys(ctx context.Context, orgID int64) ([]dbgen.CountOpenButtonKeysRow, error)
	ListActivatedKeys(ctx context.Context, orgID int64) ([]dbgen.ListActivatedKeysRow, error)
}

StatusQueries are the reads of the Keyring status; *dbgen.Queries implements them.

func NewStatusQueries

func NewStatusQueries(db dbgen.DBTX) StatusQueries

NewStatusQueries are the StatusQueries over a pool, a connection or a transaction.

type StatusReader

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

StatusReader reads the Keyring status of this process for the API.

func NewStatusReader

func NewStatusReader(q StatusQueries, k *Keyring, realClock clock.Clock) *StatusReader

NewStatusReader is the StatusReader over q with the keys of k, at the time of the real clock.

func (*StatusReader) Status

func (r *StatusReader) Status(ctx context.Context) (Status, error)

Status reads the Keyring status.

type Store

type Store interface {
	GetKeyringState(ctx context.Context) (dbgen.GetKeyringStateRow, error)
	CreateKeyringState(ctx context.Context, arg dbgen.CreateKeyringStateParams) (int64, error)
	GetActiveKeyID(ctx context.Context) (string, error)
	RecordReplica(ctx context.Context, arg dbgen.RecordReplicaParams) error
	DeleteReplica(ctx context.Context, replicaID string) error
	ListLiveReplicas(ctx context.Context, liveSince time.Time) ([]dbgen.Replica, error)
}

Store is the keyring's part of the database: keyring_state and replicas. *dbgen.Queries implements it.

func NewStore

func NewStore(db dbgen.DBTX) Store

NewStore is the Store over a pool, a connection or a transaction.

type StoredSecret

type StoredSecret struct {
	Ciphertext []byte
	KeyID      string
	UpdatedAt  *time.Time
}

StoredSecret is a Secret field as a row stores it: the ciphertext, the id of the key that wrote it and when it last changed. An empty ciphertext is a field that is not set.

func (StoredSecret) Set

func (s StoredSecret) Set() bool

Set reports whether the field holds a value.

func (StoredSecret) Status

func (s StoredSecret) Status() SecretStatus

Status is the read of the field; the value never leaves the server.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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