diff --git a/PLAN.md b/PLAN.md index 80f8faf..425cdf9 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1926,6 +1926,27 @@ than planned: rather than helpers in every query, the SQL stays as it is case-insensitivity and named indexes. Checked by feeding it drift on purpose: a type, a missing index, a missing `nocase`. +**Part 4 built 2026-11-25** on `phase9`. +- `secrets.Store` has a second home: the `secrets` table (schema 30, the + first migration for both databases), used by the server and + multi-tenant editions. The local edition keeps `secrets.json`; the table + stays empty there. Callers don't change. +- Each value is sealed with AES-256-GCM under a key derived (HKDF) from + `SUPERMARKET_SECRET_KEY`, with a new nonce each time, and bound to its + name, so a value moved to another name doesn't open. +- Each row records the key's fingerprint, never the key. Starting with the + wrong key stops the app with a message saying so, rather than looking + as if every connection were lost. Every value is opened at start-up, so + a changed one is caught then too. +- Changing keys: give the old one in `SUPERMARKET_SECRET_KEY_OLD`, and the + new one in `SUPERMARKET_SECRET_KEY`. At start, everything is sealed again + in one transaction; then unset the old key. +- The database store reads each secret when it's asked for, not from + memory, so several copies of the app see a token one of them refreshed + (X's refresh tokens work once). If the database can't be read just then, + the value last read is used. +- On Postgres, the web tests run with this store. + Nothing changes for the local user; this makes the rest possible. A commit after each part; the whole test suite runs against both SQLite and Postgres from part 2 on. diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index ed2b871..edc1ece 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -179,7 +179,17 @@ func run(log *slog.Logger) error { log.Error("writing the CRM state file", "err", err) } - sec, err := secrets.Open(filepath.Join(dataDir, "secrets.json")) + // The local edition keeps its keys and tokens in a file beside the + // database; the others, in the database, encrypted. + var sec *secrets.Store + if cfg.Edition == config.Local { + sec, err = secrets.Open(filepath.Join(dataDir, "secrets.json")) + } else { + sec, err = secrets.OpenDB(database, cfg.SecretKey, cfg.OldKey) + if err == nil && cfg.OldKey != nil { + log.Warn("secrets: encrypted with the new key; unset " + config.EnvOldKey) + } + } if err != nil { return err } diff --git a/internal/config/config.go b/internal/config/config.go index 8a37c42..e2a3fc9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -91,6 +91,7 @@ type Config struct { DatabaseURL string // postgres://…; empty on the local edition SecretKey []byte // 32 bytes that encrypt secrets in the database; nil if not set + OldKey []byte // the key being replaced: secrets under it are encrypted again with SecretKey Storage Storage Mail *Mail // nil if not set } @@ -106,6 +107,7 @@ const ( EnvHostData = "SUPERMARKET_HOST_DATA" EnvDatabaseURL = "SUPERMARKET_DATABASE_URL" EnvSecretKey = "SUPERMARKET_SECRET_KEY" + EnvOldKey = "SUPERMARKET_SECRET_KEY_OLD" EnvStorage = "SUPERMARKET_STORAGE" EnvS3Endpoint = "SUPERMARKET_S3_ENDPOINT" EnvS3Region = "SUPERMARKET_S3_REGION" @@ -173,6 +175,18 @@ func Load(getenv func(string) string) (*Config, error) { } else if shared { bad("%s is needed on the %s edition: it encrypts the keys and tokens kept in the database. Run supermarket secret-key to make one, and keep a copy somewhere safe", EnvSecretKey, c.Edition.Name()) } + if k := get(EnvOldKey, ""); k != "" { + key, err := ParseKey(k) + switch { + case err != nil: + bad("%s: %v", EnvOldKey, err) + case c.SecretKey == nil: + bad("%s is set without %s: give the new key too", EnvOldKey, EnvSecretKey) + case string(key) == string(c.SecretKey): + bad("%s is the same key as %s", EnvOldKey, EnvSecretKey) + } + c.OldKey = key + } // Files. c.Storage = loadStorage(get, bad, c.DataDir) @@ -326,10 +340,14 @@ func (c *Config) Summary() []Item { } items = append(items, files) switch { - case c.SecretKey != nil: - items = append(items, Item{"Secrets", "Encrypted in the database", "With the key in " + EnvSecretKey + "."}) case c.Edition == Local: items = append(items, Item{"Secrets", filepath.Join(c.HostData, "secrets.json"), "Readable only by you; never in backups unless you ask."}) + case c.SecretKey != nil: + help := "With the key in " + EnvSecretKey + "." + if c.OldKey != nil { + help = "Moving from the key in " + EnvOldKey + " to the one in " + EnvSecretKey + ": unset " + EnvOldKey + " once Supermarket has started." + } + items = append(items, Item{"Secrets", "Encrypted in the database", help}) } if c.Mail != nil { items = append(items, Item{"Mail", c.Mail.From + " through " + c.Mail.Host, "The app's own mail: invitations and password resets (" + EnvMailURL + ")."}) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index acc69c8..9948b2e 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -145,3 +145,28 @@ func TestKeys(t *testing.T) { t.Fatal("relative folder accepted") } } + +func TestOldKey(t *testing.T) { + env := server() + env[EnvOldKey] = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + c, err := Load(envOf(env)) + if err != nil || len(c.OldKey) != 32 { + t.Fatal(c.OldKey, err) + } + found := false + for _, it := range c.Summary() { + if it.Name == "Secrets" && strings.Contains(it.Help, "unset "+EnvOldKey) { + found = true + } + } + if !found { + t.Error("the summary doesn't say a key change is under way") + } + env[EnvOldKey] = key + if _, err := Load(envOf(env)); err == nil || !strings.Contains(err.Error(), "same key") { + t.Error(err) + } + if _, err := Load(envOf(map[string]string{EnvOldKey: key})); err == nil || !strings.Contains(err.Error(), "without") { + t.Error(err) + } +} diff --git a/internal/db/migrations.go b/internal/db/migrations.go index a1feb7c..50ae580 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -22,7 +22,20 @@ type Migration struct { // both are the migrations after schema 29, on both databases: schema 30 // is both[0]. (migrations, before them, are SQLite's own; Postgres starts // from postgres.sql, which is schema 29 as a whole.) -var both = []Migration{} +var both = []Migration{ + // 30 + { + Note: "secrets kept in the database, encrypted (server and multi-tenant editions)", + SQLite: ` +CREATE TABLE secrets ( + name TEXT PRIMARY KEY, + value TEXT NOT NULL, -- v1:, AES-256-GCM + key_id TEXT NOT NULL, -- which key sealed it: a fingerprint, never the key + updated_at TEXT NOT NULL +); +`, + }, +} // Schema is the schema version this build migrates databases to. func Schema() int { return len(migrations) + len(both) } diff --git a/internal/secrets/database.go b/internal/secrets/database.go new file mode 100644 index 0000000..996d8d5 --- /dev/null +++ b/internal/secrets/database.go @@ -0,0 +1,279 @@ +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 +} diff --git a/internal/secrets/database_test.go b/internal/secrets/database_test.go new file mode 100644 index 0000000..153c736 --- /dev/null +++ b/internal/secrets/database_test.go @@ -0,0 +1,106 @@ +package secrets + +import ( + "path/filepath" + "strings" + "testing" + + "supermarket/internal/db" +) + +var ( + keyA = []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + keyB = []byte("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") +) + +func openDB(t *testing.T) *db.DB { + t.Helper() + d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.Close() }) + return d +} + +func TestDatabaseStore(t *testing.T) { + d := openDB(t) + s, err := OpenDB(d, keyA, nil) + if err != nil { + t.Fatal(err) + } + if err := s.Set(map[string]string{StripeAPIKey: "rk_live_123", GiteaToken: "gt-456"}); err != nil { + t.Fatal(err) + } + if s.Get(StripeAPIKey) != "rk_live_123" || !s.Has(GiteaToken) || s.Has(BingAPIKey) { + t.Fatal("not stored") + } + if got := s.Names(); strings.Join(got, ",") != GiteaToken+","+StripeAPIKey { + t.Errorf("names: %v", got) + } + // Encrypted: the database holds no value, only sealed ones, each + // different even for the same text. + var raw string + d.QueryRow(`SELECT group_concat(value, ' ') FROM secrets`).Scan(&raw) + if d.Dialect == db.Postgres { + d.QueryRow(`SELECT string_agg(value, ' ') FROM secrets`).Scan(&raw) + } + if strings.Contains(raw, "rk_live") || strings.Contains(raw, "gt-456") || !strings.HasPrefix(raw, "v1:") { + t.Fatalf("stored as %q", raw) + } + s.Set(map[string]string{BingAPIKey: "same", PlausibleAPIKey: "same"}) + var a, b string + d.QueryRow(`SELECT value FROM secrets WHERE name = ?`, BingAPIKey).Scan(&a) + d.QueryRow(`SELECT value FROM secrets WHERE name = ?`, PlausibleAPIKey).Scan(&b) + if a == b { + t.Error("the same value sealed the same way twice") + } + // A value moved to another name doesn't open. + d.Exec(`UPDATE secrets SET value = ? WHERE name = ?`, a, PlausibleAPIKey) + if _, err := OpenDB(d, keyA, nil); err == nil || !strings.Contains(err.Error(), PlausibleAPIKey) { + t.Errorf("a swapped value was accepted: %v", err) + } + s.Set(map[string]string{PlausibleAPIKey: ""}) // removed + if s.Has(PlausibleAPIKey) { + t.Error("not removed") + } + + // Another copy of the app sees a token this one refreshed. + other, err := OpenDB(d, keyA, nil) + if err != nil { + t.Fatal(err) + } + other.Get(GiteaToken) + s.Set(map[string]string{GiteaToken: "gt-789"}) + if other.Get(GiteaToken) != "gt-789" { + t.Error("the other copy kept the old token") + } +} + +func TestDatabaseStoreKeys(t *testing.T) { + d := openDB(t) + s, _ := OpenDB(d, keyA, nil) + s.Set(map[string]string{XAccessToken: "x-1", XRefreshToken: "x-2"}) + + // The wrong key: refused at the start, saying so. + if _, err := OpenDB(d, keyB, nil); err == nil || !strings.Contains(err.Error(), "another key") { + t.Fatalf("wrong key: %v", err) + } + // Changing keys: the old one given, every secret is sealed again. + s, err := OpenDB(d, keyB, keyA) + if err != nil { + t.Fatal(err) + } + if s.Get(XAccessToken) != "x-1" || s.Get(XRefreshToken) != "x-2" { + t.Fatal("lost in the change") + } + if _, err := OpenDB(d, keyB, nil); err != nil { + t.Errorf("after the change, the new key alone: %v", err) + } + if _, err := OpenDB(d, keyA, nil); err == nil { + t.Error("the old key still opens them") + } + if _, err := OpenDB(d, []byte("short"), nil); err == nil { + t.Error("a short key was accepted") + } +} diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index c30ef21..c3cd2a9 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -1,5 +1,7 @@ -// Package secrets keeps API keys and tokens in one file, readable only by the -// user, outside the database so a copy of the database holds no credentials. +// Package secrets keeps API keys and tokens. The local edition keeps them +// in one file, readable only by the user, outside the database so a copy +// of the database holds no credentials. The server and multi-tenant +// editions keep them in the database, encrypted (database.go). package secrets import ( @@ -10,6 +12,7 @@ import ( "sort" "sync" + "supermarket/internal/db" "supermarket/internal/fileutil" ) @@ -62,11 +65,19 @@ const ( RedditUsername = "reddit.username" ) -// Store is the secrets file. It is safe for concurrent use. +// Store is the secrets: a file, or the database. It is safe for +// concurrent use. type Store struct { + mu sync.Mutex + + // The file (local edition) path string - mu sync.Mutex vals map[string]string + + // The database (server and multi-tenant editions) + d *db.DB + key *sealer + cache map[string]string // the values last read, for when the database can't be } // Open loads the secrets file at path, or starts empty if there is none. An @@ -91,6 +102,9 @@ func Open(path string) (*Store, error) { // Get returns the secret name, or "" if it isn't set. func (s *Store) Get(name string) string { + if s.d != nil { + return s.dbGet(name) + } s.mu.Lock() defer s.mu.Unlock() return s.vals[name] @@ -104,6 +118,9 @@ func (s *Store) Has(name string) bool { // Set stores the given secrets (an empty value removes one) and saves the // file. On a failed save nothing changes in memory either. func (s *Store) Set(updates map[string]string) error { + if s.d != nil { + return s.dbSet(updates) + } s.mu.Lock() defer s.mu.Unlock() next := make(map[string]string, len(s.vals)+len(updates)) @@ -131,6 +148,9 @@ func (s *Store) Set(updates map[string]string) error { // Names lists the secrets that are set, for status pages. It never returns // values. func (s *Store) Names() []string { + if s.d != nil { + return s.dbNames() + } s.mu.Lock() defer s.mu.Unlock() names := make([]string, 0, len(s.vals)) diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 7cbcc86..abfc810 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -41,6 +41,9 @@ func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) { } t.Cleanup(func() { d.Close() }) sec, err := secrets.Open(filepath.Join(dir, "secrets.json")) + if db.OnPostgres() { // as the server edition keeps them + sec, err = secrets.OpenDB(d, []byte("0123456789abcdef0123456789abcdef"), nil) + } if err != nil { t.Fatal(err) }