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
- Variables
- func EncryptedFields() []string
- func KeyID(material []byte) string
- func NewReplicaID(hostname string) string
- func PruneReplicas(ctx context.Context, p Pruner, log *logging.Logger, now time.Time) error
- type EncryptedValue
- type Env
- type KeyState
- type KeyStatus
- type Keyring
- func (k *Keyring) ActiveKeyID() string
- func (k *Keyring) ApplySecret(field string, stored StoredSecret, in SecretInput, now time.Time) (StoredSecret, bool, error)
- func (k *Keyring) Decrypt(field, keyID string, ciphertext []byte) ([]byte, error)
- func (k *Keyring) Encrypt(field string, plaintext []byte) (ciphertext []byte, keyID string, err error)
- func (k *Keyring) Establish(ctx context.Context, s Store, now time.Time) (State, error)
- func (k *Keyring) Holds(id string) bool
- func (k *Keyring) KeyIDs() []string
- func (k *Keyring) Open(ctx context.Context, log *logging.Logger, st State) error
- func (k *Keyring) OpenSecret(field string, s StoredSecret) (logging.Secret, error)
- func (k *Keyring) Sign(p Purpose, msg []byte) (mac []byte, keyID string, err error)
- func (k *Keyring) Verify(p Purpose, keyID string, msg, mac []byte) (bool, error)
- func (k *Keyring) VerifyPrefix(p Purpose, keyID string, msg, prefix []byte) (bool, error)
- type Provider
- type Pruner
- type Purpose
- type Recorder
- func (r *Recorder) ID() string
- func (r *Recorder) Refresh(ctx context.Context) error
- func (r *Recorder) Run(ctx context.Context, ticks <-chan time.Time) error
- func (r *Recorder) Start(ctx context.Context) error
- func (r *Recorder) Stop(ctx context.Context) error
- func (r *Recorder) Switch(ctx context.Context) error
- func (r *Recorder) Wake()
- type Replica
- type ReplicasLackKeyError
- type Rotated
- type Rotation
- type RotationQueries
- type RotationStore
- type RowKey
- type SecretInput
- type SecretStatus
- type State
- type Status
- type StatusQueries
- type StatusReader
- type Store
- type StoredSecret
Constants ¶
const ( SecretKeysVar = "MUSTER_SECRET_KEYS" SecretKeysFileVar = "MUSTER_SECRET_KEYS_FILE" )
The variables of the master keys.
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 )
const ( ActionKeyActivated = "keyring.key_activated" ResourceKeyring = "keyring" )
ActionKeyActivated is the Audit log action of `muster secrets rotate-key`, and ResourceKeyring its resource type.
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.
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.
const KeySize = 32
KeySize is the size of a master key and of each sub-key, in bytes.
const MinSignaturePrefix = 16
MinSignaturePrefix is the shortest signature VerifyPrefix accepts: 128 bits.
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 ¶
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") )
var Clear = SecretInput{Given: true, Null: true}
Clear is the input of a Secret field set to null.
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 "".
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.
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 ¶
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 ¶
NewReplicaID is the id of a replica, chosen at process start: the host name and a random suffix.
func PruneReplicas ¶
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 ¶
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.
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 New ¶
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 ¶
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 ¶
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 ¶
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) Open ¶
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 ¶
OpenSecret decrypts the field; a field that is not set is the empty Secret.
func (*Keyring) Sign ¶
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 ¶
Verify checks a signature made by Sign with the key keyID, which may be any key of the Keyring.
func (*Keyring) VerifyPrefix ¶
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 ¶
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.
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) Run ¶
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.
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.
type ReplicasLackKeyError ¶
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 ¶
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 ¶
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.
type SecretInput ¶
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 ¶
SecretStatus is what a read shows instead of a Secret: whether it is set and when it last changed.
type Status ¶
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 ¶
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.
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.
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.
type StoredSecret ¶
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.