Files
uptimesebi/internal/sealed/sealed.go
T
Sebastian UnterschützandClaude Opus 5.5 d20225982a refactor: follow the google go style guide
Document every package and exported identifier, return the log level
from NewLogger instead of keeping it in a package variable, and stop
tests from mutating the argon2 parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 00:18:02 +01:00

90 lines
2.5 KiB
Go

// 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
}