// Package sealed encrypts small secrets (TOTP seeds, integration credentials) // before they are written to the database. package sealed import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "errors" "fmt" "strings" ) // ErrUnknownKey is returned for values sealed with a key that was removed // from the keyring. var ErrUnknownKey = errors.New("sealed: unknown key id") // Keyring holds one active key for sealing and any number of retired keys // that can still open old values, so keys can be rotated without downtime. type Keyring struct { active string aeads map[string]cipher.AEAD } // Parse reads "id:base64key,id2:base64key2"; the first entry is active. func Parse(spec string) (*Keyring, error) { kr := &Keyring{aeads: map[string]cipher.AEAD{}} for i, part := range strings.Split(spec, ",") { id, b64, ok := strings.Cut(strings.TrimSpace(part), ":") if !ok || id == "" { return nil, fmt.Errorf("sealed: entry %d must be id:base64", i+1) } raw, err := base64.StdEncoding.DecodeString(b64) if err != nil || len(raw) != 32 { return nil, fmt.Errorf("sealed: key %q must be 32 bytes, base64 encoded", id) } block, err := aes.NewCipher(raw) if err != nil { return nil, err } aead, err := cipher.NewGCM(block) if err != nil { return nil, err } if _, dup := kr.aeads[id]; dup { return nil, fmt.Errorf("sealed: duplicate key id %q", id) } kr.aeads[id] = aead if i == 0 { kr.active = id } } return kr, nil } // Seal binds the ciphertext to aad (e.g. the owning row id) so a sealed value // cannot be copied onto another row. func (k *Keyring) Seal(plain, aad []byte) []byte { aead := k.aeads[k.active] nonce := make([]byte, aead.NonceSize()) _, _ = rand.Read(nonce) out := append([]byte(k.active+":"), nonce...) return aead.Seal(out, nonce, plain, aad) } // Open decrypts a value produced by Seal with the same aad. func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) { id, rest, ok := strings.Cut(string(sealed), ":") if !ok { return nil, errors.New("sealed: malformed value") } aead, ok := k.aeads[id] if !ok { return nil, ErrUnknownKey } body := []byte(rest) if len(body) < aead.NonceSize() { return nil, errors.New("sealed: malformed value") } return aead.Open(nil, body[:aead.NonceSize()], body[aead.NonceSize():], aad) } // NeedsReseal reports whether sealed was produced with a retired key and // should be rewritten. func (k *Keyring) NeedsReseal(sealed []byte) bool { id, _, _ := strings.Cut(string(sealed), ":") return id != k.active }