Files
davidandClaude Opus 5.5 c76a7791ee Phase 9, part 4: secrets in the database, encrypted
The server and multi-tenant editions keep keys and tokens in a secrets
table (schema 30, the first migration for both databases), each sealed
with AES-256-GCM under a key derived from SUPERMARKET_SECRET_KEY and bound
to its name. A wrong key stops the start with a clear message;
SUPERMARKET_SECRET_KEY_OLD reseals everything under a new key. Values are
read when asked for, so several copies of the app agree on a refreshed
token. The local edition keeps secrets.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:31:41 -07:00

280 lines
7.2 KiB
Go

package secrets
import (
"crypto/aes"
"crypto/cipher"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"sort"
"strings"
"time"
"supermarket/internal/db"
)
// The server and multi-tenant editions keep secrets in the database's
// secrets table, each value sealed with AES-256-GCM under a key derived
// from SUPERMARKET_SECRET_KEY, and bound to its name (so a value can't be
// moved to another name). A copy of the database without the key holds
// no usable credentials. Each row records a fingerprint of its key, so a
// wrong key is caught when the app starts, not when a post fails.
// sealer seals and opens values under one key.
type sealer struct {
aead cipher.AEAD
id string // the key's fingerprint
}
func newSealer(key []byte) (*sealer, error) {
if len(key) != 32 {
return nil, errors.New("the secret key must be 32 bytes")
}
enc, err := hkdf.Key(sha256.New, key, nil, "supermarket secrets v1: AES-256-GCM", 32)
if err != nil {
return nil, err
}
fp, err := hkdf.Key(sha256.New, key, nil, "supermarket secrets v1: key fingerprint", 8)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(enc)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &sealer{aead: aead, id: hex.EncodeToString(fp)}, nil
}
const sealedPrefix = "v1:"
func (k *sealer) seal(name, value string) (string, error) {
nonce := make([]byte, k.aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return "", err
}
out := k.aead.Seal(nonce, nonce, []byte(value), []byte(name))
return sealedPrefix + base64.StdEncoding.EncodeToString(out), nil
}
func (k *sealer) open(name, sealed string) (string, error) {
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, sealedPrefix))
if err != nil || !strings.HasPrefix(sealed, sealedPrefix) || len(raw) < k.aead.NonceSize() {
return "", fmt.Errorf("the secret %s isn't in a form this version reads", name)
}
n := k.aead.NonceSize()
plain, err := k.aead.Open(nil, raw[:n], raw[n:], []byte(name))
if err != nil {
return "", fmt.Errorf("the secret %s doesn't open with this key (or was changed)", name)
}
return string(plain), nil
}
// OpenDB opens the secrets kept in the database, sealed with key. With
// oldKey (SUPERMARKET_SECRET_KEY_OLD), secrets sealed with it are sealed
// again with key. A secret sealed with any other key is an error: the
// key is wrong, and starting anyway would look as if every connection
// had been lost.
func OpenDB(d *db.DB, key, oldKey []byte) (*Store, error) {
cur, err := newSealer(key)
if err != nil {
return nil, err
}
var old *sealer
if oldKey != nil {
if old, err = newSealer(oldKey); err != nil {
return nil, err
}
}
rows, err := d.Query(`SELECT key_id, count(*) FROM secrets GROUP BY key_id`)
if err != nil {
return nil, err
}
counts := map[string]int{}
for rows.Next() {
var id string
var n int
if err := rows.Scan(&id, &n); err != nil {
rows.Close()
return nil, err
}
counts[id] = n
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
for id, n := range counts {
if id != cur.id && (old == nil || id != old.id) {
return nil, fmt.Errorf("%d of the secrets in the database were encrypted with another key than SUPERMARKET_SECRET_KEY (key %s, not %s). Set the key they were made with; to change keys, give the old one in SUPERMARKET_SECRET_KEY_OLD", n, id, cur.id)
}
}
s := &Store{d: d, key: cur, cache: map[string]string{}}
if old != nil && counts[old.id] > 0 {
if err := s.reseal(old); err != nil {
return nil, fmt.Errorf("encrypting the secrets with the new key: %w", err)
}
}
// Every secret opens: a value changed in the database is caught now.
if _, err := s.all(); err != nil {
return nil, err
}
return s, nil
}
// reseal seals every secret under old again with the store's key, in one
// transaction.
func (s *Store) reseal(old *sealer) error {
tx, err := s.d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
rows, err := tx.Query(`SELECT name, value FROM secrets WHERE key_id = ?`, old.id)
if err != nil {
return err
}
type row struct{ name, value string }
var todo []row
for rows.Next() {
var r row
if err := rows.Scan(&r.name, &r.value); err != nil {
rows.Close()
return err
}
todo = append(todo, r)
}
rows.Close()
now := time.Now().UTC().Format(time.RFC3339)
for _, r := range todo {
plain, err := old.open(r.name, r.value)
if err != nil {
return err
}
sealed, err := s.key.seal(r.name, plain)
if err != nil {
return err
}
if _, err := tx.Exec(`UPDATE secrets SET value = ?, key_id = ?, updated_at = ? WHERE name = ?`, sealed, s.key.id, now, r.name); err != nil {
return err
}
}
return tx.Commit()
}
// dbGet reads one secret. It's read each time, not kept, so several copies
// of the app see a token one of them refreshed. If the database can't be
// read just then, the value last read is used.
func (s *Store) dbGet(name string) string {
var sealed string
err := s.d.QueryRow(`SELECT value FROM secrets WHERE name = ?`, name).Scan(&sealed)
s.mu.Lock()
defer s.mu.Unlock()
if errors.Is(err, sql.ErrNoRows) {
delete(s.cache, name)
return ""
}
if err == nil {
if v, oerr := s.key.open(name, sealed); oerr == nil {
s.cache[name] = v
return v
}
}
return s.cache[name]
}
// all reads and opens every secret.
func (s *Store) all() (map[string]string, error) {
rows, err := s.d.Query(`SELECT name, value FROM secrets`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]string{}
for rows.Next() {
var name, sealed string
if err := rows.Scan(&name, &sealed); err != nil {
return nil, err
}
v, err := s.key.open(name, sealed)
if err != nil {
return nil, err
}
out[name] = v
}
return out, rows.Err()
}
// dbSet stores the updates in one transaction (an empty value removes
// one).
func (s *Store) dbSet(updates map[string]string) error {
tx, err := s.d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
now := time.Now().UTC().Format(time.RFC3339)
for name, v := range updates {
if v == "" {
if _, err := tx.Exec(`DELETE FROM secrets WHERE name = ?`, name); err != nil {
return err
}
continue
}
sealed, err := s.key.seal(name, v)
if err != nil {
return err
}
if _, err := tx.Exec(`INSERT INTO secrets (name, value, key_id, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT (name) DO UPDATE SET value = excluded.value, key_id = excluded.key_id, updated_at = excluded.updated_at`,
name, sealed, s.key.id, now); err != nil {
return err
}
}
if err := tx.Commit(); err != nil {
return err
}
s.mu.Lock()
for name, v := range updates {
if v == "" {
delete(s.cache, name)
} else {
s.cache[name] = v
}
}
s.mu.Unlock()
return nil
}
// dbNames lists the secrets that are set.
func (s *Store) dbNames() []string {
rows, err := s.d.Query(`SELECT name FROM secrets ORDER BY name`)
if err != nil {
s.mu.Lock()
defer s.mu.Unlock()
names := make([]string, 0, len(s.cache))
for k := range s.cache {
names = append(names, k)
}
sort.Strings(names)
return names
}
defer rows.Close()
var names []string
for rows.Next() {
var n string
if rows.Scan(&n) == nil {
names = append(names, n)
}
}
return names
}