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

97 lines
3.4 KiB
Go

package db
import (
"fmt"
"regexp"
"strings"
)
// Migration is a change to the schema from schema 30 on, for both
// databases. It's written once, in SQLite's SQL; Postgres gets the same
// statements with SQLite's types and defaults translated (see PostgresSQL).
// A migration that changes data with SQL only SQLite has gives Postgres
// its own.
//
// Never edit or reorder one that has shipped: add a new one instead.
type Migration struct {
Note string // what it does, for the record (Postgres' schema_migrations)
SQLite string
Postgres string // empty: PostgresSQL(SQLite)
}
// 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{
// 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:<base64 of the nonce and the sealed value>, 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) }
// sqliteStep is the SQL that takes SQLite from schema i to i+1.
func sqliteStep(i int) string {
if i < len(migrations) {
return migrations[i]
}
return both[i-len(migrations)].SQLite
}
// postgresStep is the migration that takes Postgres from schema i to i+1
// (i is pgBaseline or later).
func postgresStep(i int) (Migration, string) {
m := both[i-pgBaseline]
if m.Postgres != "" {
return m, m.Postgres
}
return m, PostgresSQL(m.SQLite)
}
var (
ddlIntegerKey = regexp.MustCompile(`(?i)\bINTEGER\s+PRIMARY\s+KEY\b`)
ddlInteger = regexp.MustCompile(`(?i)\bINTEGER\b`)
ddlReal = regexp.MustCompile(`(?i)\bREAL\b`)
ddlBlob = regexp.MustCompile(`(?i)\bBLOB\b`)
ddlNow = regexp.MustCompile(`(?i)strftime\('%Y-%m-%dT%H:%M:%SZ',\s*'now'\)`)
// A column whose COLLATE comes after its constraints: Postgres wants it
// right after the type.
ddlCollateLate = regexp.MustCompile(`(?i)\bTEXT((?:\s+(?:NOT\s+NULL|UNIQUE|PRIMARY\s+KEY|DEFAULT\s+(?:'(?:[^']|'')*'|\([^)]*\)|[^\s,]+)))+)\s+COLLATE\s+NOCASE\b`)
ddlCollate = regexp.MustCompile(`(?i)\bCOLLATE\s+NOCASE\b`)
)
// PostgresSQL translates SQLite's DDL (CREATE TABLE, CREATE INDEX, ALTER
// TABLE … ADD COLUMN) to Postgres': 64-bit integers, identity keys,
// doubles, the nocase collation in its place, and timestamps from now().
func PostgresSQL(sqlite string) string {
s := ddlIntegerKey.ReplaceAllString(sqlite, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY")
s = ddlInteger.ReplaceAllString(s, "BIGINT")
s = ddlReal.ReplaceAllString(s, "DOUBLE PRECISION")
s = ddlBlob.ReplaceAllString(s, "BYTEA")
s = ddlNow.ReplaceAllString(s, `to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`)
s = ddlCollateLate.ReplaceAllString(s, "TEXT COLLATE nocase$1")
s = ddlCollate.ReplaceAllString(s, "COLLATE nocase")
return s
}
// checkMigrations catches a mistake in the list before it reaches a
// database: an empty step.
func checkMigrations() error {
for i, m := range both {
if strings.TrimSpace(m.SQLite) == "" || strings.TrimSpace(m.Note) == "" {
return fmt.Errorf("migration %d needs its SQLite SQL and a note", len(migrations)+i+1)
}
}
return nil
}