rotator

package
v1.22.10 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 22 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 rotator rotates the high-value secrets in tmi-secrets one idempotent phase at a time, recording progress in Secret annotations (#965).

Index

Constants

View Source
const (
	// #nosec G101 -- Secret data key name, not a credential
	RedisPasswordKey = "TMI_REDIS_PASSWORD"
	AnnRetire        = "tmi.dev/rotation-retire."
)
View Source
const (
	AnnRotatedAt  = "tmi.dev/rotated-at."
	AnnEvery      = "tmi.dev/rotate-every."
	AnnPhase      = "tmi.dev/rotation-phase."
	AnnGeneration = "tmi.dev/rotation-generation."

	DefaultRotateEvery = 90 * 24 * time.Hour
)

Annotation keys (suffix = Rotation.Name()).

View Source
const (
	SettingsKeyKey       = "TMI_SECRET_SETTINGS_ENCRYPTION_KEY"
	SettingsKeyIDKey     = "TMI_SECRET_SETTINGS_ENCRYPTION_CONTEXT_ID"
	SettingsPrevKeyKey   = "TMI_SECRET_SETTINGS_ENCRYPTION_PREVIOUS_KEY"
	SettingsPrevKeyIDKey = "TMI_SECRET_SETTINGS_ENCRYPTION_PREVIOUS_CONTEXT_ID"
	AnnPromotedAt        = "tmi.dev/rotation-promoted-at."
)

Variables

View Source
var ErrConflict = errors.New("secret changed since it was read")

ErrConflict is returned by SecretStore.Update when the Secret changed after it was read.

Functions

func AgeDays

func AgeDays(s *Secret, name string, now time.Time) int

AgeDays returns whole days since the last rotation, or -1 if never rotated.

func IsDue

func IsDue(s *Secret, name string, now time.Time) bool

IsDue reports whether the named rotation should start now: never rotated, an unreadable rotated-at, or older than rotate-every (default 90d; an unparsable interval is logged and falls back to the default, never to "now").

func NewHexKey

func NewHexKey() (string, error)

NewHexKey returns 32 random bytes as 64 hex characters (AES-256 key).

func NewPassword

func NewPassword() (string, error)

NewPassword returns a 32-character alphanumeric password (URL- and shell-safe, so it needs no escaping in TMI_DATABASE_URL or redis-cli). int(b)%62 biases the first 8 letters by 4/256; acceptable for ~190 bits and simpler than rejection sampling.

func ParseRotateEvery

func ParseRotateEvery(v string) (time.Duration, error)

ParseRotateEvery accepts "<n>d" or any Go duration; zero or negative is an error.

func RedisPasswordFromSecret

func RedisPasswordFromSecret(store SecretStore, secretName string) func(context.Context) (string, error)

RedisPasswordFromSecret returns a go-redis credentials func that reads the current password from the Secret on every (re)connect, so a Redis restart mid-rotation reconnects with whatever the Secret holds now. Redis accepts the Secret's password in every phase: OLD before the swap, then OLD+NEW (and finally only NEW) once the Secret holds NEW.

func RegionFromSecretARN

func RegionFromSecretARN(arn string) (string, error)

RegionFromSecretARN returns the region field of a Secrets Manager secret ARN.

func Run

func Run(ctx context.Context, env *Env, rotations []Rotation, force string) error

Run evaluates every rotation: forced, in progress (phase annotation set), or due. Each rotation runs even if an earlier one failed; the first error is returned.

Types

type Env

type Env struct {
	Secrets          SecretStore
	Rollouts         RolloutWaiter
	SecretName       string        // "tmi-secrets"
	ServerDeployment string        // "tmi-server"
	RolloutTimeout   time.Duration // 10m
	Now              func() time.Time
}

Env is everything a Rotation needs from the cluster.

func (*Env) Transition

func (e *Env) Transition(ctx context.Context, name, fromPhase, nextPhase string, mutate func(s *Secret)) error

Transition reads the Secret, applies mutate, records the phase (or, for nextPhase == "", clears it and stamps rotated-at) together with the server Deployment's generation before the write, and writes everything in one Update. It is a compare-and-swap on the phase: if the recorded phase (missing == "") is not fromPhase, another run advanced it, so nothing is written and the error wraps ErrConflict. A stale resourceVersion conflict is likewise not retried.

func (*Env) WaitServerRolled

func (e *Env) WaitServerRolled(ctx context.Context, s *Secret, name string) error

WaitServerRolled waits for the server rollout caused by the last Transition of name.

type Escrow

type Escrow interface {
	Put(ctx context.Context, payload []byte) error
}

Escrow stores an off-cluster copy of key material before a rotation makes it the only live copy (#1009). Implementations must never echo the payload in errors or logs.

type FakeRolloutWaiter

type FakeRolloutWaiter struct {
	Waits int
	// contains filtered or unexported fields
}

FakeRolloutWaiter reports a generation equal to the store's data-write count, so every data write "rolls" the server immediately.

func NewFakeRolloutWaiter

func NewFakeRolloutWaiter(store *MemorySecretStore, deployment string) *FakeRolloutWaiter

NewFakeRolloutWaiter binds a fake waiter to a MemorySecretStore.

func (*FakeRolloutWaiter) Generation

func (f *FakeRolloutWaiter) Generation(_ context.Context, deployment string) (int64, error)

Generation reports the fake Deployment generation.

func (*FakeRolloutWaiter) WaitRolled

func (f *FakeRolloutWaiter) WaitRolled(ctx context.Context, deployment string, since int64, _ time.Duration) error

WaitRolled succeeds when a data write happened after since.

type GoRedisACL

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

GoRedisACL implements RedisACL with ACL SETUSER.

func NewGoRedisACL

func NewGoRedisACL(client *redis.Client) *GoRedisACL

func (*GoRedisACL) AddPassword

func (a *GoRedisACL) AddPassword(ctx context.Context, pw string) error

func (*GoRedisACL) SetOnlyPassword

func (a *GoRedisACL) SetOnlyPassword(ctx context.Context, pw string) error

SetOnlyPassword makes pw the default user's only password in one atomic ACL SETUSER (resetpass clears the password list; flags and permissions stay). Idempotent: unlike "!hash", it does not fail when an old password is already gone.

type GormSettingsStore

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

GormSettingsStore runs the real SettingsService against the database.

func NewGormSettingsStore

func NewGormSettingsStore(gormDB *gorm.DB, redis *db.RedisDB) *GormSettingsStore

func (*GormSettingsStore) CountWithID

func (g *GormSettingsStore) CountWithID(ctx context.Context, kr Keyring, id int) (int64, error)

func (*GormSettingsStore) ReEncrypt

func (g *GormSettingsStore) ReEncrypt(ctx context.Context, kr Keyring) (int, error)

type Keyring

type Keyring struct {
	CurrentKeyHex  string
	CurrentID      int
	PreviousKeyHex string
	PreviousID     int
}

Keyring is the settings-encryption key material held in tmi-secrets.

func KeyringFromSecret

func KeyringFromSecret(s *Secret) (Keyring, error)

KeyringFromSecret reads and validates the keyring; a missing context id is 1 (the id every pre-rotation value carries).

func (Keyring) Encryptor

func (k Keyring) Encryptor() (*crypto.SettingsEncryptor, error)

Encryptor builds the crypto keyring for this Keyring.

type KubeRolloutWaiter

type KubeRolloutWaiter struct {
	Poll time.Duration
	// contains filtered or unexported fields
}

KubeRolloutWaiter polls a Deployment until Reloader's rollout completes.

func NewKubeRolloutWaiter

func NewKubeRolloutWaiter(cs kubernetes.Interface, namespace string) *KubeRolloutWaiter

NewKubeRolloutWaiter builds a waiter polling every 5s.

func (*KubeRolloutWaiter) Generation

func (w *KubeRolloutWaiter) Generation(ctx context.Context, deployment string) (int64, error)

Generation reads a Deployment's metadata.generation.

func (*KubeRolloutWaiter) WaitRolled

func (w *KubeRolloutWaiter) WaitRolled(ctx context.Context, deployment string, since int64, timeout time.Duration) error

WaitRolled first waits for the generation to pass since (Reloader has patched the pod template), then for the rollout to complete. A Recreate Deployment dips to zero available replicas in between; that is progress, not failure.

type KubeSecretStore

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

KubeSecretStore is the SecretStore for a real cluster.

func NewKubeSecretStore

func NewKubeSecretStore(cs kubernetes.Interface, namespace string) *KubeSecretStore

NewKubeSecretStore builds a KubeSecretStore for one namespace.

func (*KubeSecretStore) Get

func (k *KubeSecretStore) Get(ctx context.Context, name string) (*Secret, error)

Get fetches a Secret and decodes its data into strings.

func (*KubeSecretStore) Update

func (k *KubeSecretStore) Update(ctx context.Context, s *Secret) error

Update writes data and annotations back; a stale resourceVersion or a 409 is ErrConflict.

type MemorySecretStore

type MemorySecretStore struct {
	DataWrites int
	// contains filtered or unexported fields
}

MemorySecretStore is an in-memory SecretStore for tests. It bumps resourceVersion on every Update and counts data writes so a FakeRolloutWaiter can imitate Reloader (which rolls on data changes only).

func NewMemorySecretStore

func NewMemorySecretStore(seed ...*Secret) *MemorySecretStore

NewMemorySecretStore builds a store seeded with the given Secrets.

func (*MemorySecretStore) Get

func (m *MemorySecretStore) Get(_ context.Context, name string) (*Secret, error)

Get returns a copy of the named Secret.

func (*MemorySecretStore) Update

func (m *MemorySecretStore) Update(_ context.Context, s *Secret) error

Update stores s if its resourceVersion is current.

type NoopEscrow

type NoopEscrow struct{}

NoopEscrow is used when no escrow is configured (dev clusters).

func (NoopEscrow) Put

type RedisACL

type RedisACL interface {
	AddPassword(ctx context.Context, pw string) error
	SetOnlyPassword(ctx context.Context, pw string) error
}

RedisACL manages the passwords accepted for the default Redis user. Returned errors must never contain a password (Redis echoes ACL modifiers).

type RedisPasswordRotation

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

RedisPasswordRotation rotates TMI_REDIS_PASSWORD without a Redis restart.

func NewRedisPasswordRotation

func NewRedisPasswordRotation(acl RedisACL) *RedisPasswordRotation

func (*RedisPasswordRotation) Name

func (r *RedisPasswordRotation) Name() string

func (*RedisPasswordRotation) Run

func (r *RedisPasswordRotation) Run(ctx context.Context, env *Env) error

type RolloutWaiter

type RolloutWaiter interface {
	Generation(ctx context.Context, deployment string) (int64, error)
	// WaitRolled returns once the Deployment's generation exceeds since and its rollout is complete.
	WaitRolled(ctx context.Context, deployment string, since int64, timeout time.Duration) error
}

RolloutWaiter observes Deployment rollouts triggered by Secret changes (Reloader).

type Rotation

type Rotation interface {
	Name() string
	// Run resumes from the phase recorded on the Secret and returns when the
	// rotation is complete or parked (waiting on a later run). Idempotent.
	// Returned errors must never contain secret values: implementations wrap
	// credential-bearing errors (e.g. Redis echoing an ACL password) with fixed messages.
	Run(ctx context.Context, env *Env) error
}

Rotation is one secret's phased, resumable rotation.

type Secret

type Secret struct {
	Name            string
	Data            map[string]string
	Annotations     map[string]string
	ResourceVersion string
}

Secret is a snapshot of one Kubernetes Secret with decoded data.

func (*Secret) Clone

func (s *Secret) Clone() *Secret

Clone returns a deep copy so a store can hand out independent snapshots.

type SecretStore

type SecretStore interface {
	Get(ctx context.Context, name string) (*Secret, error)
	// Update replaces data and annotations; returns ErrConflict when s.ResourceVersion is stale.
	Update(ctx context.Context, s *Secret) error
}

SecretStore reads and writes whole Secrets with optimistic concurrency.

type SecretsManagerEscrow

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

SecretsManagerEscrow writes each payload as a new version of one secret.

func NewSecretsManagerEscrow

func NewSecretsManagerEscrow(client SecretsManagerPutter, secretARN string) *SecretsManagerEscrow

func (*SecretsManagerEscrow) Put

func (e *SecretsManagerEscrow) Put(ctx context.Context, payload []byte) error

type SecretsManagerPutter

type SecretsManagerPutter interface {
	PutSecretValue(ctx context.Context, in *secretsmanager.PutSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.PutSecretValueOutput, error)
}

SecretsManagerPutter is the slice of the Secrets Manager client the escrow uses.

type SettingsKeyRotation

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

SettingsKeyRotation rotates the settings-encryption key: stage, promote, re-encrypt, and (after previousGrace, once nothing references the old id) drop.

func NewSettingsKeyRotation

func NewSettingsKeyRotation(store SettingsStore, previousGrace time.Duration, escrow Escrow) *SettingsKeyRotation

func (*SettingsKeyRotation) Name

func (r *SettingsKeyRotation) Name() string

func (*SettingsKeyRotation) Run

func (r *SettingsKeyRotation) Run(ctx context.Context, env *Env) error

type SettingsStore

type SettingsStore interface {
	ReEncrypt(ctx context.Context, kr Keyring) (int, error)
	CountWithID(ctx context.Context, kr Keyring, id int) (int64, error)
}

SettingsStore is the database side of the settings-key rotation.

Jump to

Keyboard shortcuts

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