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>
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
Reference in New Issue
Block a user