From 6310b8e30eeee219340a45354ed7d612672dec77 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Tue, 24 Nov 2026 23:44:40 -0500 Subject: [PATCH 1/2] feat(tenancy): PostgreSQL backup and restore with a replay gate pg-backup streams every table by COPY from one REPEATABLE READ snapshot into an archive sealed in 1 MiB AES-256-GCM frames under an operator key file. The blob rows in it are the object references of the same instant. pg-restore loads it into a just-created database in one transaction, user triggers off and foreign keys on, with the restore fence. Every restore now writes a replay gate. OrgServes refuses each customer org until the elected worker has read the org and erased feeds from zero and found nothing more, so erasures and org deletions since the backup are applied before anyone is served. Multi startup stays refused. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 +- AGENTS.md | 11 + DESIGN.md | 10 + cmd/kynotes-server/main.go | 6 + cmd/kynotes-server/postgres_backup.go | 122 ++++++ cmd/kynotes-server/postgres_backup_test.go | 68 +++ docs/RESTORE.md | 37 +- .../specs/2026-11-23-tenancy-design.md | 42 +- internal/app/replica_schedules.go | 5 +- internal/backup/AGENTS.md | 3 + internal/backup/pg_archive.go | 210 +++++++++ internal/backup/pg_archive_test.go | 117 +++++ internal/backup/postgres_restore.go | 42 +- internal/httpapi/erased_feed.go | 47 ++ internal/httpapi/restore_replay_test.go | 139 ++++++ internal/httpapi/tenancy_status_test.go | 9 + internal/storage/orgs.go | 9 +- internal/storage/pg_archive.go | 402 ++++++++++++++++++ internal/storage/pg_archive_test.go | 191 +++++++++ internal/storage/pgdialect/driver.go | 9 + internal/storage/restore_tenancy.go | 1 + 21 files changed, 1456 insertions(+), 26 deletions(-) create mode 100644 cmd/kynotes-server/postgres_backup.go create mode 100644 cmd/kynotes-server/postgres_backup_test.go create mode 100644 internal/backup/pg_archive.go create mode 100644 internal/backup/pg_archive_test.go create mode 100644 internal/httpapi/restore_replay_test.go create mode 100644 internal/storage/pg_archive.go create mode 100644 internal/storage/pg_archive_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14dadc42..79d66ddb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -131,7 +131,7 @@ jobs: - name: PostgreSQL restored-target and staff safety env: KYNOTES_TEST_DATABASE_URL: postgres://postgres@localhost:5432/postgres?sslmode=disable - run: go test -race -count=1 -timeout 20m -p 2 ./internal/backup ./cmd/kynotes-server -run '^(TestPostgresRestore|TestStaffUserCommand)' + run: go test -race -count=1 -timeout 20m -p 2 ./internal/backup ./cmd/kynotes-server -run '^(TestPostgresRestore|TestPostgresBackup|TestStaffUserCommand)' checks: if: github.event.pull_request.draft != true diff --git a/AGENTS.md b/AGENTS.md index 050f0e79..c3831ea1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -349,6 +349,17 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che the original surface. No UI choice grants access or changes the startup refusal. Verify `TestStaff*`, N6, route classification, quota regressions, cross-org matrix and golden; `staffAPI.test.ts` and `staff-console.e2e.ts` exercise parsing, scope changes and late responses. +- PostgreSQL backup transport (multi mode): `pg-backup --out` / `pg-restore --in --confirm-stopped`, + DSN and key file (`KYNOTES_PG_BACKUP_KEY_FILE`, 64 hex) from the environment only. + `storage.BackupPostgres` streams every table by COPY from one REPEATABLE READ snapshot, in + foreign-key order, with row counts and sequences in a trailer; `backup` seals it in 1 MiB + AES-256-GCM frames whose associated data binds salt, index and the final flag. Restore loads + only into a just-created target, with user triggers off (usage counters must not count twice) + and foreign keys on, then commits the restore fence in the same transaction. + `storage.RestoreReplayKey` keeps every customer org unserved (`OrgServes`) until + `httpapi.FinishRestoreReplay` sees both suite feeds empty past their cursors. Verify + `TestPostgresArchive*`, `TestSealedArchiveRefusesEveryChange`, `TestPostgresBackupRestoresFencedAndGated` + and `TestRestoreAfterPurgeReplaysBeforeServing`; a new table must be seeded in the round trip. - Native PostgreSQL restored-target preparation: `prepare-postgres-restore --confirm-restored` reads `KYNOTES_DB_DSN` only from the environment, opens the exact existing schema without migrating and refuses recorded single mode. Stop every replica before targeting a separately diff --git a/DESIGN.md b/DESIGN.md index f2bfa695..7384053a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -982,6 +982,16 @@ in their writer operation. `TestErasedFeedFenceRejectsRacingSessionMint` proves whose earlier lookup already ran cannot mint a session past a newer durable fence. +### PostgreSQL backup transport (multi mode) + +`pg-backup` streams every table by COPY from one REPEATABLE READ snapshot into an archive +sealed in AES-256-GCM frames under an operator key file; the blob rows in it are the object +references of the same instant. `pg-restore` loads it into a just-created database in one +transaction (user triggers off, foreign keys on) with the restore fence below, plus a replay +gate: `OrgServes` refuses every customer org until the elected worker has read both suite +feeds from zero to empty. Objects are not copied; GC retention bounds how old a restorable +archive may be. + ### Native PostgreSQL restored-target safety `OpenPostgresCurrent` opens only an existing, exact-release schema without migrating or diff --git a/cmd/kynotes-server/main.go b/cmd/kynotes-server/main.go index 93f41ab3..63f2eaf4 100644 --- a/cmd/kynotes-server/main.go +++ b/cmd/kynotes-server/main.go @@ -66,6 +66,12 @@ func main() { os.Exit(1) } return + case "pg-backup", "pg-restore": + if e := postgresArchiveCommand(os.Args[1], os.Args[2:], os.Stdout); e != nil { + fmt.Fprintln(os.Stderr, e) + os.Exit(1) + } + return case "prepare-postgres-restore": if e := preparePostgresRestoreCommand(os.Args[2:], os.Stdout); e != nil { fmt.Fprintln(os.Stderr, e) diff --git a/cmd/kynotes-server/postgres_backup.go b/cmd/kynotes-server/postgres_backup.go new file mode 100644 index 00000000..b5d3d20b --- /dev/null +++ b/cmd/kynotes-server/postgres_backup.go @@ -0,0 +1,122 @@ +package main + +import ( + "context" + "encoding/hex" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + + "github.com/Busnes-app/kynotes-server/internal/backup" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +// pg-backup and pg-restore are the multi-mode PostgreSQL backup transport. The DSN and the +// backup key stay out of argv: KYNOTES_DB_DSN and KYNOTES_PG_BACKUP_KEY_FILE. +// +// pg-backup --out FILE sealed archive of the live database, created new +// pg-restore --in FILE --confirm-stopped load into a new, empty database, fenced and gated +func postgresArchiveCommand(name string, args []string, stdout io.Writer) error { + flags := flag.NewFlagSet(name, flag.ContinueOnError) + flags.SetOutput(io.Discard) + out := flags.String("out", "", "new archive file") + in := flags.String("in", "", "archive file") + confirm := flags.Bool("confirm-stopped", false, "every replica is stopped") + usage := errors.New("usage: pg-backup --out FILE | pg-restore --in FILE --confirm-stopped (KYNOTES_DB_DSN and KYNOTES_PG_BACKUP_KEY_FILE in the environment)") + if err := flags.Parse(args); err != nil || flags.NArg() != 0 { + return usage + } + if name == "pg-backup" && (*out == "" || *in != "" || *confirm) || name == "pg-restore" && (*in == "" || *out != "" || !*confirm) { + return usage + } + dsn := os.Getenv("KYNOTES_DB_DSN") + if dsn == "" { + return errors.New(name + " requires KYNOTES_DB_DSN in the environment") + } + key, err := readBackupKey() + if err != nil { + return err + } + ctx := context.Background() + if name == "pg-backup" { + return postgresBackup(ctx, dsn, key, *out, stdout) + } + return postgresRestore(ctx, dsn, key, *in, stdout) +} + +func postgresBackup(ctx context.Context, dsn string, key []byte, path string, stdout io.Writer) error { + store, err := storage.OpenPostgresCurrent(ctx, dsn) + if err != nil { + return errors.New("pg-backup cannot open the current PostgreSQL schema; run the release that owns it") + } + defer store.Close() + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return errors.New("pg-backup cannot create the archive file; it must not exist yet") + } + sum, err := backup.BackupPostgres(ctx, store.DB(), key, f) + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(path) + return fmt.Errorf("pg-backup failed and removed the partial archive: %w", err) + } + _, err = fmt.Fprintf(stdout, "PostgreSQL backup written: schema %d, snapshot %s, %d tables. Keep the backup key apart from the archive.\n", sum.Schema, sum.TakenAt, len(sum.Rows)) + return err +} + +func postgresRestore(ctx context.Context, dsn string, key []byte, path string, stdout io.Writer) error { + store, err := storage.OpenPostgresCurrent(ctx, dsn) + if err != nil && !errors.Is(err, storage.ErrSchemaOlder) && !errors.Is(err, storage.ErrSchemaNewer) { + store, err = storage.OpenPostgres(dsn) // a new database: create this release's schema + } + if err != nil { + return errors.New("pg-restore needs a new, empty database for this release") + } + defer store.Close() + f, err := os.Open(path) + if err != nil { + return errors.New("pg-restore cannot open the archive file") + } + defer f.Close() + sum, err := backup.RestorePostgres(ctx, store.DB(), key, f) + if err != nil { + return fmt.Errorf("pg-restore loaded nothing: %w", err) + } + _, err = fmt.Fprintf(stdout, "Restored PostgreSQL snapshot %s (schema %d): credentials revoked, deposits off, customer orgs stale and unserved until the elected worker replays the org and erased feeds from zero. Verify blob coverage before serving. This command does not enable multi startup.\n", sum.TakenAt, sum.Schema) + return err +} + +// The key file holds 64 hex characters (32 bytes), optionally followed by one newline. +func readBackupKey() ([]byte, error) { + bad := errors.New("KYNOTES_PG_BACKUP_KEY_FILE must name a regular file holding 64 hex characters") + path := os.Getenv("KYNOTES_PG_BACKUP_KEY_FILE") + if path == "" { + return nil, bad + } + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() { + return nil, bad + } + f, err := os.Open(path) + if err != nil { + return nil, bad + } + defer f.Close() + raw, err := io.ReadAll(io.LimitReader(f, 2*backup.BackupKeyBytes+3)) + if err != nil { + return nil, bad + } + key, err := hex.DecodeString(strings.TrimSuffix(strings.TrimSuffix(string(raw), "\n"), "\r")) + if err != nil || len(key) != backup.BackupKeyBytes { + return nil, bad + } + return key, nil +} diff --git a/cmd/kynotes-server/postgres_backup_test.go b/cmd/kynotes-server/postgres_backup_test.go new file mode 100644 index 00000000..fccd130d --- /dev/null +++ b/cmd/kynotes-server/postgres_backup_test.go @@ -0,0 +1,68 @@ +package main + +import ( + "io" + "os" + "path/filepath" + "strings" + "syscall" + "testing" +) + +// pg-backup and pg-restore take no DSN or key in argv, refuse every other flag shape before +// any database or file work, and accept only a regular file of 64 hex characters as the key. +func TestPostgresArchiveCommandRefusesBadInput(t *testing.T) { + dir := t.TempDir() + key := filepath.Join(dir, "key") + if err := os.WriteFile(key, []byte(strings.Repeat("ab", 32)+"\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("KYNOTES_PG_BACKUP_KEY_FILE", key) + t.Setenv("KYNOTES_DB_DSN", "") + for _, c := range []struct { + name, want string + args []string + }{ + {"pg-backup", "usage", nil}, + {"pg-backup", "usage", []string{"--out", "x", "--confirm-stopped"}}, + {"pg-backup", "usage", []string{"--out", "x", "postgres://u:p@h/db"}}, + {"pg-restore", "usage", []string{"--in", "x"}}, + {"pg-restore", "usage", []string{"--in", "x", "--out", "y", "--confirm-stopped"}}, + {"pg-restore", "usage", []string{"--dsn", "postgres://u:p@h/db", "--in", "x", "--confirm-stopped"}}, + {"pg-backup", "KYNOTES_DB_DSN", []string{"--out", filepath.Join(dir, "a.pgb")}}, + {"pg-restore", "KYNOTES_DB_DSN", []string{"--in", "x", "--confirm-stopped"}}, + } { + err := postgresArchiveCommand(c.name, c.args, io.Discard) + if err == nil || !strings.Contains(err.Error(), c.want) || strings.Contains(err.Error(), "u:p@") { + t.Errorf("%s %v: %v", c.name, c.args, err) + } + } + if _, err := os.Stat(filepath.Join(dir, "a.pgb")); !os.IsNotExist(err) { + t.Fatal("a refused backup created its file") + } + + fifo := filepath.Join(dir, "fifo") + if err := syscall.Mkfifo(fifo, 0o600); err != nil { + t.Fatal(err) + } + for name, content := range map[string]string{"short": strings.Repeat("ab", 31), "long": strings.Repeat("ab", 33), "not hex": strings.Repeat("zz", 32), "two lines": strings.Repeat("ab", 32) + "\n\n"} { + path := filepath.Join(dir, strings.ReplaceAll(name, " ", "-")) + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("KYNOTES_PG_BACKUP_KEY_FILE", path) + if _, err := readBackupKey(); err == nil { + t.Errorf("%s key accepted", name) + } + } + for _, path := range []string{"", dir, fifo, filepath.Join(dir, "missing")} { + t.Setenv("KYNOTES_PG_BACKUP_KEY_FILE", path) + if _, err := readBackupKey(); err == nil { + t.Errorf("key file %q accepted", path) + } + } + t.Setenv("KYNOTES_PG_BACKUP_KEY_FILE", key) + if k, err := readBackupKey(); err != nil || len(k) != 32 || k[0] != 0xab { + t.Fatalf("valid key: %v", err) + } +} diff --git a/docs/RESTORE.md b/docs/RESTORE.md index 9cc7671b..ae00ba55 100644 --- a/docs/RESTORE.md +++ b/docs/RESTORE.md @@ -130,6 +130,41 @@ that wrote the capsule. Ordinary startup refusal leaves the original instance's credentials and schedule unchanged. +## Back up and restore PostgreSQL in multi mode (tenancy preparation) + +Hosted startup is still refused in this release. `pg-backup` and `pg-restore` are the +multi-mode database transport (tenancy open question 3). They have no 256 MiB capsule limit. +Both read the database URL from `KYNOTES_DB_DSN` and the backup key from +`KYNOTES_PG_BACKUP_KEY_FILE`, a regular file holding 64 hex characters (32 random bytes, e.g. +`openssl rand -hex 32`). Keep the key apart from the archives: without it no archive opens, +and with it every archive does. + +```bash +kynotes-server pg-backup --out /backups/kynotes-2026-11-25.pgb +``` + +The backup reads every table in one `REPEATABLE READ` snapshot of the live database, so the +`blobs` rows (the org-qualified object references) agree with the notes that use them. The +archive is sealed in AES-256-GCM frames; a changed, reordered, cut or extended archive does +not open. The file must not exist yet and is removed if the backup fails. Ciphertext objects +are not copied: GC deletes an object only after `gc.retention` with no reference, so keep no +archive you mean to restore longer than that retention (default 168 h). No command checks +blob coverage yet; confirm the referenced objects exist before a hosted release serves. + +To restore, stop **every** replica, create a new, empty database and run the release that +wrote the archive: + +```bash +kynotes-server pg-restore --in /backups/kynotes-2026-11-25.pgb --confirm-stopped +``` + +It creates this release's schema, refuses a target that holds any data or another schema +version, and loads every row in one transaction together with the restore fence described +below (revocations, deposits off, orgs stale). It also writes the replay gate: until the elected worker +has read the org and erased-subject feeds from zero and found nothing more, no customer org +serves, so every erasure and org deletion since the backup is applied again before anyone is +served. The worker then purges the deleted orgs again. If anything fails, nothing is loaded. + ## Prepare a native PostgreSQL restored target (tenancy preparation) Hosted startup is still refused in this release. This command prepares a database restored @@ -151,7 +186,7 @@ The command refuses an uninitialized, older/newer or single-mode target without One transaction revokes web sessions, paired devices, share/sealed links and pending invitations; keeps encryption identities; turns scheduled deposits off; makes customer orgs stale at revision zero; clears old grants, directory cursors, replica ephemeral state and probe pointers; and -records a platform audit. Erasure fences, permanent store ID, keys and sealed recovery pairing +records a platform audit. It also writes the replay gate described above. Erasure fences, permanent store ID, keys and sealed recovery pairing remain. A schedule/audit/reset failure rolls everything back: keep the target stopped, fix the cause and repeat with its matching release. diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index c4d2090e..967f9f6b 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1392,6 +1392,45 @@ Tests cover both schema-version refusals, explicit target/secret boundaries, ato and rollback, and single-mode no-change. The command does not recover PG backup bytes, choose open question 3's large-database transport or enable multi startup. Those remain prerequisites. +### PostgreSQL backup transport as built (startup still refused) + +Open question 3 is answered for KyNotes with a logical archive, not base backup plus WAL: +it needs no PostgreSQL tooling or superuser on the host, round-trips in CI, and has no capsule +limit. A host that also runs PostgreSQL's own PITR still restores through +`prepare-postgres-restore`, which now writes the same replay gate. + +- `pg-backup --out` (`storage.BackupPostgres`): one REPEATABLE READ READ ONLY transaction, a + JSON header (format, schema version, database time, tables and columns in foreign-key + order), each table's COPY text rows ended by `\.`, and a trailer of row counts and sequence + values. The `blobs`, `blob_containers` and version rows are the object references, from the + same snapshot as the notes. Objects themselves are not copied: GC retention (168 h by + default) bounds how old a restorable archive may be. +- Sealing (`backup.BackupPostgres`): `KYNOTES_PG_BACKUP_KEY_FILE` (32 bytes, hex), HKDF-SHA256 + per archive salt, 1 MiB AES-256-GCM frames with random nonces (FIPS), associated data binding + magic, salt, frame index and final flag. +- `pg-restore --in --confirm-stopped`: a just-created database of the archive's schema version + only. One transaction deletes the migration and `ensureOrgs` seed rows, turns user triggers + off (usage and org-seeding triggers must not run twice), loads every table with foreign keys + checked, checks the trailer's counts, sets sequences, turns triggers back on and commits the + restore fence (`fenceRestoredTx`, shared with `prepare-postgres-restore`). +- **Replay before serving.** `ResetTenancyAfterRestore` writes `restore_replay`. While it + exists `OrgServes` refuses every customer org (the staff org still serves), so sessions, + devices, share links, reminders, GC and the orphan sweep all wait. The elected worker's + `httpapi.FinishRestoreReplay` runs after the org and erased polls and deletes it only when + both feeds, read from the stored cursors, list nothing more and the cursors did not move. + So every erasure since the backup is fenced, and every deleted org is marked deleted, before + any customer org serves. The purge then deletes the restored deleted org again. +- Tests (PostgreSQL): every table round-trips byte for byte, including COPY escapes, NULLs and + sequences, with triggers back on; damaged, truncated, extended, wrong-schema or wrong-count + archives, a failing fence and a target holding data load nothing; the snapshot excludes a + write committed during the backup; every change to a sealed archive fails to open; + `TestRestoreAfterPurgeReplaysBeforeServing` restores a backup taken before an org purge and + an erasure and shows the org unserved after the org poll until the erasure is replayed. +- Not built: object storage as the archive's destination and its schedule binding (startup + binding), a blob-coverage check, and the KyIdentity "deleted orgs stay listed" trigger the + replay relies on (Downstream contract). Cells (C5) give the archive a cell-scoped object + prefix when the destination lands. + ### Staff surface as built (startup still refused) The prepared multi-mode admin surface requires one org for the users read, filters the audit @@ -1454,7 +1493,8 @@ multi startup or complete the native backup/object/runtime prerequisites. snapshots PostgreSQL into a capsule. A shared install will pass that. Recommend PostgreSQL's own backups (base backup plus WAL, encrypted, to object storage) for multi mode, with capsules kept for single-tenant installs and Enterprise. The restore reset (Lifecycle) then runs after a - PostgreSQL restore too. KyIdentity, KyCalendar and KyDrive face the same limit (unverified for + PostgreSQL restore too. **Built** as a logical COPY archive instead ("PostgreSQL backup + transport as built"). KyIdentity, KyCalendar and KyDrive face the same limit (unverified for their sizes). 4. **Answered (owner decision 12): (a), with tombstoned comments.** An erased owner's team notebooks with other members. Delete everything deletes the clicker's data, and a team notebook is shared. diff --git a/internal/app/replica_schedules.go b/internal/app/replica_schedules.go index 5fd64d72..b1ef71a7 100644 --- a/internal/app/replica_schedules.go +++ b/internal/app/replica_schedules.go @@ -18,8 +18,8 @@ import ( ) // replicaSchedules is the application adapter, not another scheduler. The eventual multi -// startup binds gc to storage.RunObjectGC and purge to the org's blobstore.Objects.Purge, and -// supplies PostgreSQL backup once it exists. +// startup binds gc to storage.RunObjectGC, purge to the org's blobstore.Objects.Purge and +// backup to backup.BackupPostgres with its object-storage destination. // Until then config.Load refuses multi; the single-mode loops stay unchanged. type replicaSchedules struct { db *sql.DB @@ -52,6 +52,7 @@ func (s *replicaSchedules) tick(owned context.Context, now time.Time) { s.minute = now.Add(time.Minute) // count attempts, including failures run("org_poll", func() error { return s.orgs.Poll(owned) }) run("erased_poll", func() error { return httpapi.PollErased(owned, s.db, s.directory) }) + run("restore_replay", func() error { return httpapi.FinishRestoreReplay(owned, s.db, s.directory) }) run("org_purge", func() error { return storage.PurgeDeletedOrgs(owned, s.db, s.purge) }) run("member_erase", func() error { return storage.EraseMembers(owned, s.db) }) run("shared_state", func() error { return storage.SweepSharedState(owned, s.db) }) diff --git a/internal/backup/AGENTS.md b/internal/backup/AGENTS.md index 53665492..42c2b531 100644 --- a/internal/backup/AGENTS.md +++ b/internal/backup/AGENTS.md @@ -57,6 +57,9 @@ service operations, blob mirror orchestration, and audit. Shared transport and c never re-pins a key, and sets the interval only when no admin setting exists. Dir and keep are env-fixed and only compared. +- `BackupPostgres`/`RestorePostgres` seal storage's PostgreSQL archive (1 MiB AES-256-GCM + frames, HKDF per-archive key, AAD = magic, salt, index, final flag; random nonces, so FIPS). + The restore commits `fenceRestoredTx` with the rows. Never add a path that loads rows without it. - `PreparePostgresRestore` is an offline, exact-schema multi-mode target fence. Credential revocation, deposit schedule off, tenancy reset and audit share one transaction. No pin, token, encryption identity or permanent blob-store ID is replaced. Keep all replicas stopped diff --git a/internal/backup/pg_archive.go b/internal/backup/pg_archive.go new file mode 100644 index 00000000..3d0de31b --- /dev/null +++ b/internal/backup/pg_archive.go @@ -0,0 +1,210 @@ +package backup + +import ( + "bufio" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/hkdf" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/binary" + "errors" + "io" + + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +// The native PostgreSQL backup for multi mode (tenancy open question 3): storage's archive, +// sealed in 1 MiB AES-256-GCM frames under a key derived per archive from the operator's +// 32-byte backup key. Each frame's associated data binds the archive salt, its index and the +// final flag, so a reordered, dropped, truncated or extended archive fails to open. +const ( + archiveMagic = "KYNOTES-PGB1\n" + frameBytes = 1 << 20 + saltBytes = 32 + // BackupKeyBytes is the operator's backup key length. + BackupKeyBytes = 32 +) + +var errArchiveSealed = errors.New("postgres backup: the archive does not open with this key or is damaged") + +// BackupPostgres writes the sealed archive of store to w. +func BackupPostgres(ctx context.Context, db *sql.DB, key []byte, w io.Writer) (storage.ArchiveSummary, error) { + sw, err := newSealWriter(w, key) + if err != nil { + return storage.ArchiveSummary{}, err + } + bw := bufio.NewWriterSize(sw, frameBytes) + sum, err := storage.BackupPostgres(ctx, db, bw) + if err == nil { + err = bw.Flush() + } + if err == nil { + err = sw.Close() + } + return sum, err +} + +// RestorePostgres loads a sealed archive into a new, empty target and commits the restore +// fence with it, so the target never holds restored rows without the fence and replay gate. +func RestorePostgres(ctx context.Context, db *sql.DB, key []byte, r io.Reader) (storage.ArchiveSummary, error) { + or, err := newOpenReader(r, key) + if err != nil { + return storage.ArchiveSummary{}, err + } + return storage.RestorePostgres(ctx, db, or, func(tx *sql.Tx) error { return fenceRestoredTx(ctx, tx) }) +} + +func archiveAEAD(key, salt []byte) (cipher.AEAD, error) { + if len(key) != BackupKeyBytes { + return nil, errors.New("postgres backup: the backup key must be 32 bytes") + } + k, err := hkdf.Key(sha256.New, key, salt, "kynotes pg archive v1", 32) + if err != nil { + return nil, err + } + block, err := aes.NewCipher(k) + if err != nil { + return nil, err + } + return cipher.NewGCMWithRandomNonce(block) +} + +func frameAAD(salt []byte, index uint64, final bool) []byte { + aad := append([]byte(archiveMagic), salt...) + aad = binary.BigEndian.AppendUint64(aad, index) + if final { + return append(aad, 1) + } + return append(aad, 0) +} + +type sealWriter struct { + w io.Writer + aead cipher.AEAD + salt []byte + index uint64 + buf []byte +} + +func newSealWriter(w io.Writer, key []byte) (*sealWriter, error) { + salt := make([]byte, saltBytes) + if _, err := rand.Read(salt); err != nil { + return nil, err + } + aead, err := archiveAEAD(key, salt) + if err != nil { + return nil, err + } + if _, err := io.WriteString(w, archiveMagic); err != nil { + return nil, err + } + if _, err := w.Write(salt); err != nil { + return nil, err + } + return &sealWriter{w: w, aead: aead, salt: salt}, nil +} + +func (s *sealWriter) Write(p []byte) (int, error) { + n := len(p) + for len(p) > 0 { + take := min(frameBytes-len(s.buf), len(p)) + s.buf = append(s.buf, p[:take]...) + p = p[take:] + if len(s.buf) == frameBytes { + if err := s.frame(false); err != nil { + return 0, err + } + } + } + return n, nil +} + +// Close writes the final frame (possibly empty); without it the archive does not open. +func (s *sealWriter) Close() error { return s.frame(true) } + +func (s *sealWriter) frame(final bool) error { + sealed := s.aead.Seal(nil, nil, s.buf, frameAAD(s.salt, s.index, final)) + head := []byte{0} + if final { + head[0] = 1 + } + head = binary.BigEndian.AppendUint32(head, uint32(len(sealed))) + if _, err := s.w.Write(head); err != nil { + return err + } + if _, err := s.w.Write(sealed); err != nil { + return err + } + s.index++ + s.buf = s.buf[:0] + return nil +} + +type openReader struct { + r io.Reader + aead cipher.AEAD + salt []byte + index uint64 + plain []byte + done bool +} + +func newOpenReader(r io.Reader, key []byte) (*openReader, error) { + head := make([]byte, len(archiveMagic)+saltBytes) + if _, err := io.ReadFull(r, head); err != nil || string(head[:len(archiveMagic)]) != archiveMagic { + return nil, errors.New("postgres backup: not a KyNotes PostgreSQL backup") + } + salt := head[len(archiveMagic):] + aead, err := archiveAEAD(key, salt) + if err != nil { + return nil, err + } + return &openReader{r: r, aead: aead, salt: salt}, nil +} + +func (o *openReader) Read(p []byte) (int, error) { + for len(o.plain) == 0 { + if o.done { + return 0, io.EOF + } + if err := o.next(); err != nil { + return 0, err + } + } + n := copy(p, o.plain) + o.plain = o.plain[n:] + return n, nil +} + +func (o *openReader) next() error { + var head [5]byte + if _, err := io.ReadFull(o.r, head[:]); err != nil { + return errArchiveSealed + } + final := head[0] == 1 + size := binary.BigEndian.Uint32(head[1:]) + if head[0] > 1 || size < uint32(o.aead.Overhead()) || size > frameBytes+uint32(o.aead.Overhead()) { + return errArchiveSealed + } + sealed := make([]byte, size) + if _, err := io.ReadFull(o.r, sealed); err != nil { + return errArchiveSealed + } + plain, err := o.aead.Open(nil, nil, sealed, frameAAD(o.salt, o.index, final)) + if err != nil { + return errArchiveSealed + } + if final { + var extra [1]byte + if _, err := io.ReadFull(o.r, extra[:]); err != io.EOF { + return errArchiveSealed + } + o.done = true + } + o.index++ + o.plain = plain + return nil +} diff --git a/internal/backup/pg_archive_test.go b/internal/backup/pg_archive_test.go new file mode 100644 index 00000000..61e38034 --- /dev/null +++ b/internal/backup/pg_archive_test.go @@ -0,0 +1,117 @@ +package backup + +import ( + "bytes" + "io" + "path/filepath" + "testing" + + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +func sealed(t *testing.T, key, plain []byte) []byte { + t.Helper() + var buf bytes.Buffer + w, err := newSealWriter(&buf, key) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write(plain); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func opened(key, archive []byte) ([]byte, error) { + r, err := newOpenReader(bytes.NewReader(archive), key) + if err != nil { + return nil, err + } + return io.ReadAll(r) +} + +// A sealed archive opens only whole, in order, under its key. +func TestSealedArchiveRefusesEveryChange(t *testing.T) { + key := bytes.Repeat([]byte{7}, BackupKeyBytes) + plain := bytes.Repeat([]byte("row\n"), frameBytes/2+10) // three frames: two full and the final one + archive := sealed(t, key, plain) + if got, err := opened(key, archive); err != nil || !bytes.Equal(got, plain) { + t.Fatalf("round trip: %v", err) + } + if got, err := opened(key, sealed(t, key, nil)); err != nil || len(got) != 0 { + t.Fatalf("empty archive: %v", err) + } + head := len(archiveMagic) + saltBytes + frame := 5 + frameBytes + 28 + flip := append([]byte{}, archive...) + flip[head+frame+100] ^= 1 + swapped := append(append(append([]byte{}, archive[:head]...), archive[head+frame:head+2*frame]...), archive[head:head+frame]...) + swapped = append(swapped, archive[head+2*frame:]...) + early := append([]byte{}, archive[:head+frame]...) // the first frame relabelled final + early[head] = 1 + cases := map[string]struct { + key, archive []byte + }{ + "wrong key": {bytes.Repeat([]byte{8}, BackupKeyBytes), archive}, + "flipped bit": {key, flip}, + "frames swapped": {key, swapped}, + "frame dropped": {key, append(append([]byte{}, archive[:head]...), archive[head+frame:]...)}, + "final dropped": {key, archive[:head+2*frame]}, + "cut in a frame": {key, archive[:len(archive)-3]}, + "data after": {key, append(append([]byte{}, archive...), 0)}, + "other magic": {key, append([]byte("KYNOTES-PGB2\n"), archive[len(archiveMagic):]...)}, + "early final": {key, early}, + "final flag lost": {key, append(append([]byte{}, archive[:head+2*frame]...), append([]byte{0}, archive[head+2*frame+1:]...)...)}, + } + for name, c := range cases { + if got, err := opened(c.key, c.archive); err == nil { + t.Errorf("%s: opened %d bytes", name, len(got)) + } + } + if _, err := newSealWriter(io.Discard, key[:16]); err == nil { + t.Fatal("a short key sealed") + } +} + +// The sealed PostgreSQL backup restores into a new database with the restore fence and +// the replay gate committed in the same transaction as the rows. +func TestPostgresBackupRestoresFencedAndGated(t *testing.T) { + src := postgresRestoreFixture(t) + key := bytes.Repeat([]byte{3}, BackupKeyBytes) + var buf bytes.Buffer + if _, err := BackupPostgres(t.Context(), src.DB(), key, &buf); err != nil { + t.Fatal(err) + } + if bytes.Contains(buf.Bytes(), []byte("sealed-token-to-retain")) || bytes.Contains(buf.Bytes(), []byte("usr_restore")) { + t.Fatal("the archive holds plaintext") + } + dst, err := storage.Open(filepath.Join(t.TempDir(), "target.db")) + if err != nil { + t.Fatal(err) + } + defer dst.Close() + if _, err := RestorePostgres(t.Context(), dst.DB(), bytes.Repeat([]byte{4}, BackupKeyBytes), bytes.NewReader(buf.Bytes())); err == nil { + t.Fatal("restored under the wrong key") + } + if _, err := RestorePostgres(t.Context(), dst.DB(), key, bytes.NewReader(buf.Bytes())); err != nil { + t.Fatal(err) + } + for _, q := range []string{ + `SELECT count(*) FROM users WHERE id='usr_restore'`, + `SELECT count(*) FROM objects WHERE id='obj_restore'`, + `SELECT count(*) FROM sessions WHERE revoked_at<>''`, + `SELECT count(*) FROM devices WHERE id='dev_restore' AND revoked_at<>''`, + `SELECT count(*) FROM orgs WHERE id='00000000-0000-0000-0000-000000000001' AND status='stale' AND revision=0`, + `SELECT count(*) FROM erased_subjects WHERE subject='already-erased'`, + `SELECT count(*) FROM server_settings WHERE key='kyrecovery_token' AND value='sealed-token-to-retain'`, + `SELECT count(*) FROM server_settings WHERE key='` + storage.RestoreReplayKey + `'`, + `SELECT count(*) FROM audit_events WHERE event='platform.restore_prepared'`, + } { + if restoreCount(t, dst, q) != 1 { + t.Fatalf("restored target: %s", q) + } + } +} diff --git a/internal/backup/postgres_restore.go b/internal/backup/postgres_restore.go index 6e715c0b..63666bf8 100644 --- a/internal/backup/postgres_restore.go +++ b/internal/backup/postgres_restore.go @@ -16,25 +16,29 @@ func PreparePostgresRestore(ctx context.Context, store *storage.Store) error { if !store.Postgres() { return errors.New("restore preparation requires PostgreSQL") } - return store.WithTx(ctx, func(tx *sql.Tx) error { - tenancy, err := storage.TenancyOfContext(ctx, tx) - if err != nil { - return err - } - if !tenancy.Multi() { - return errors.New("restore preparation requires recorded multi tenancy") - } - if err := storage.RevokeRestoredCredentials(ctx, tx); err != nil { - return err - } - if err := storage.ResetTenancyAfterRestore(ctx, tx); err != nil { - return err - } - if err := recoveryclient.SetInterval(restoreSettings{ctx, tx}, 0); err != nil { - return err - } - return storage.RecordAuditOutcomeTx(tx, "", "platform.restore_prepared", "", "", "success", "credentials_revoked,schedule_off,orgs_stale", "pg-restore") - }) + return store.WithTx(ctx, func(tx *sql.Tx) error { return fenceRestoredTx(ctx, tx) }) +} + +// fenceRestoredTx is the restore fence both PostgreSQL restore paths commit with: credentials +// revoked, orgs stale behind the replay gate, deposits off, audited. +func fenceRestoredTx(ctx context.Context, tx *sql.Tx) error { + tenancy, err := storage.TenancyOfContext(ctx, tx) + if err != nil { + return err + } + if !tenancy.Multi() { + return errors.New("restore preparation requires recorded multi tenancy") + } + if err := storage.RevokeRestoredCredentials(ctx, tx); err != nil { + return err + } + if err := storage.ResetTenancyAfterRestore(ctx, tx); err != nil { + return err + } + if err := recoveryclient.SetInterval(restoreSettings{ctx, tx}, 0); err != nil { + return err + } + return storage.RecordAuditOutcomeTx(tx, "", "platform.restore_prepared", "", "", "success", "credentials_revoked,schedule_off,orgs_stale,replay_gated", "pg-restore") } // Keep the library's schedule key/validation inside its API while committing with the reset. diff --git a/internal/httpapi/erased_feed.go b/internal/httpapi/erased_feed.go index ddd8df99..d8245421 100644 --- a/internal/httpapi/erased_feed.go +++ b/internal/httpapi/erased_feed.go @@ -107,3 +107,50 @@ func eraseSubjectTx(ctx context.Context, tx *sql.Tx, issuer, subject, org string } return eraseMemberTx(tx, user) } + +// FinishRestoreReplay lifts a restore's replay gate (storage.RestoreReplayKey) once the org +// and erased feeds, read from zero, list nothing past the stored cursors: every deleted org is +// marked again and every erased subject fenced before any customer org serves. The elected +// worker runs it after both polls; the gate stays while either feed fails or has more. +func FinishRestoreReplay(ctx context.Context, db *sql.DB, dir suitedir.Client) error { + var gated bool + if err := db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM server_settings WHERE key=?)`, storage.RestoreReplayKey).Scan(&gated); err != nil || !gated { + return err + } + cursors := func(q interface { + QueryRowContext(context.Context, string, ...any) *sql.Row + }) (orgs, erased int64, err error) { + err = q.QueryRowContext(ctx, `SELECT COALESCE(MAX(CASE WHEN key='org_poll_revision' THEN CAST(value AS BIGINT) END),0),COALESCE(MAX(CASE WHEN key=? THEN CAST(value AS BIGINT) END),0) FROM server_settings WHERE key IN ('org_poll_revision',?)`, erasedCursor, erasedCursor).Scan(&orgs, &erased) + return orgs, erased, err + } + orgCursor, erasedAt, err := cursors(db) + if err != nil { + return err + } + if orgs, _, err := dir.Orgs(ctx, orgCursor); err != nil || len(orgs) > 0 { + return err + } + if notices, _, err := dir.Erased(ctx, erasedAt); err != nil || len(notices) > 0 { + return err + } + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + o, e, err := cursors(tx) + if err != nil || o != orgCursor || e != erasedAt { + return err + } // A poll committed meanwhile; check again next tick. + res, err := tx.ExecContext(ctx, `DELETE FROM server_settings WHERE key=?`, storage.RestoreReplayKey) + if err != nil { + return err + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return err + } + if err := storage.RecordAuditOutcomeTx(tx, "", "platform.restore_replayed", "", "", "success", "orgs_and_erasures_replayed", "restore-replay"); err != nil { + return err + } + return tx.Commit() +} diff --git a/internal/httpapi/restore_replay_test.go b/internal/httpapi/restore_replay_test.go new file mode 100644 index 00000000..1afb2cc5 --- /dev/null +++ b/internal/httpapi/restore_replay_test.go @@ -0,0 +1,139 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/Busnes-app/ky-primitives/suitedir" + "github.com/Busnes-app/kynotes-server/internal/backup" + "github.com/Busnes-app/kynotes-server/internal/orgsync" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +// A backup taken before an org purge and a member's erasure is restored: no customer org +// serves until both suite feeds were replayed from zero, the erased member is fenced before +// their org serves again, and the deleted org is purged again. +func TestRestoreAfterPurgeReplaysBeforeServing(t *testing.T) { + if !storage.OnPostgresTest() { + t.Skip("PostgreSQL backup and restore") + } + ctx := t.Context() + var srv *httptest.Server + srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + since := r.URL.Query().Get("since") + switch r.URL.Path { + case "/api/suite/orgs": + orgs := []map[string]any{} + if since == "0" { + orgs = append(orgs, + map[string]any{"id": storage.DefaultOrgID, "status": "active", "revision": 15, "home_region": "local", "enabled": true, "quotas": map[string]any{}}, + map[string]any{"id": "org_gone", "status": "deleted", "revision": 16, "home_region": "local", "enabled": true, "quotas": map[string]any{}}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"orgs": orgs, "next": ""}) + case "/api/suite/erased": + if since == "0" { + feedNotice(w, "erased-person", storage.DefaultOrgID, 14) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"subjects": []suitedir.ErasedSubject{}}) + default: + w.WriteHeader(404) + } + })) + t.Cleanup(srv.Close) + dir := suitedir.Client{Issuer: srv.URL, ClientID: "notes", ClientSecret: "test-client-secret", HTTP: srv.Client()} + + p := newPairClient(t, strings.Repeat("p", 32)) + seedContainer(t, p, "workbook", "", map[string]string{pairUser: "owner"}) + bindErasedSubject(t, p.db, dir.Issuer) + toMultiMode(t, p.db, "org_staff") + for _, q := range []string{ + `INSERT INTO orgs(id,status,home_region,revision) VALUES('org_gone','active','local',3)`, + `INSERT INTO users(id,username,auth_secret_hash,login_salt,login_iterations,created_at,updated_at,org_id) VALUES('usr_gone','gone','x','x',1,'t','t','org_gone')`, + `INSERT INTO containers(id,kind,owner_user_id,created_at,updated_at,org_id) VALUES('ctr_gone','workbook','usr_gone','t','t','org_gone')`, + } { + if _, err := p.db.Exec(q); err != nil { + t.Fatal(err) + } + } + key := bytes.Repeat([]byte{5}, backup.BackupKeyBytes) + var archive bytes.Buffer + if _, err := backup.BackupPostgres(ctx, p.db, key, &archive); err != nil { + t.Fatal(err) + } + noObjects := func(context.Context, string) error { return nil } + if _, err := p.db.Exec(`UPDATE orgs SET status='deleted' WHERE id='org_gone'`); err != nil { + t.Fatal(err) + } + if err := storage.PurgeDeletedOrgs(ctx, p.db, noObjects); err != nil { + t.Fatal(err) + } + if erasedCount(t, p.db, `SELECT count(*) FROM users WHERE org_id='org_gone'`) != 0 { + t.Fatal("the source purge left the org's account") + } + + target, err := storage.Open(filepath.Join(t.TempDir(), "target.db")) + if err != nil { + t.Fatal(err) + } + defer target.Close() + db := target.DB() + if _, err := backup.RestorePostgres(ctx, db, key, &archive); err != nil { + t.Fatal(err) + } + served := func() bool { + return erasedCount(t, db, `SELECT count(*) FROM orgs o WHERE o.id=? AND `+storage.OrgServes("o.id"), storage.DefaultOrgID) == 1 + } + gated := func() bool { + return erasedCount(t, db, `SELECT count(*) FROM server_settings WHERE key=?`, storage.RestoreReplayKey) == 1 + } + if served() || !gated() || erasedCount(t, db, `SELECT count(*) FROM users WHERE org_id='org_gone'`) != 1 { + t.Fatal("the restored target is not stale, gated and holding the purged org") + } + if err := FinishRestoreReplay(ctx, db, dir); err != nil || !gated() { + t.Fatalf("gate lifted before any poll: %v", err) + } + if err := orgsync.New(db, dir.Orgs).Poll(ctx); err != nil { + t.Fatal(err) + } + if served() { + t.Fatal("the org serves before its erasures were replayed") + } + if err := FinishRestoreReplay(ctx, db, dir); err != nil || !gated() { + t.Fatalf("gate lifted with erasures pending: %v", err) + } + if err := PollErased(ctx, db, dir); err != nil { + t.Fatal(err) + } + if err := FinishRestoreReplay(ctx, db, dir); err != nil || gated() { + t.Fatalf("gate kept after both feeds were replayed: %v", err) + } + if !served() || erasedCount(t, db, `SELECT count(*) FROM users WHERE id=? AND status='erased'`, pairUser) != 1 { + t.Fatal("after the replay the org must serve and the member stay erased") + } + if erasedCount(t, db, `SELECT count(*) FROM audit_events WHERE event='platform.restore_replayed' AND org_id IS NULL`) != 1 { + t.Fatal("replay not audited") + } + if err := storage.PurgeDeletedOrgs(ctx, db, noObjects); err != nil { + t.Fatal(err) + } + if erasedCount(t, db, `SELECT count(*) FROM users WHERE org_id='org_gone'`)+erasedCount(t, db, `SELECT count(*) FROM containers WHERE org_id='org_gone'`) != 0 { + t.Fatal("the restored deleted org was not purged again") + } + // The org feed alone still listing changes keeps the gate as well. + if _, err := db.Exec(`INSERT INTO server_settings(key,value,updated_at) VALUES(?,'pending','t')`, storage.RestoreReplayKey); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`DELETE FROM server_settings WHERE key='org_poll_revision'`); err != nil { + t.Fatal(err) + } + if err := FinishRestoreReplay(ctx, db, dir); err != nil || !gated() { + t.Fatalf("gate lifted with org changes pending: %v", err) + } +} diff --git a/internal/httpapi/tenancy_status_test.go b/internal/httpapi/tenancy_status_test.go index 0d201ac6..c189bbe2 100644 --- a/internal/httpapi/tenancy_status_test.go +++ b/internal/httpapi/tenancy_status_test.go @@ -72,6 +72,15 @@ func TestStoppedOrgIsRefusedOnEveryCredential(t *testing.T) { if got := answers(); got != serving { t.Fatalf("after resuming: %v", got) } + // A restore's replay gate stops every customer org until the feeds are replayed. + set(`INSERT INTO server_settings(key,value,updated_at) SELECT '` + storage.RestoreReplayKey + `','pending',?`) + if got := answers(); got != stopped { + t.Fatalf("during the restore replay: %v, want %v", got, stopped) + } + set(`DELETE FROM server_settings WHERE key='` + storage.RestoreReplayKey + `' AND ?<>''`) + if got := answers(); got != serving { + t.Fatalf("after the restore replay: %v", got) + } } // A stopped org's reminders wait: none is pushed, and none is lost, until it serves again. diff --git a/internal/storage/orgs.go b/internal/storage/orgs.go index 646c14f1..e97f8751 100644 --- a/internal/storage/orgs.go +++ b/internal/storage/orgs.go @@ -76,11 +76,16 @@ func TenancyOf(q interface { // OrgServes is SQL that is true when the org named by the column expression col may be served: // always in single mode; in multi mode only an active, enabled org in this install's region // (tenancy N9, N13). Credential checks and the workers carry it, so a stopped org is refused on -// the next request and its reminders and blobs wait. +// the next request and its reminders and blobs wait. After a restore no customer org serves +// until both suite feeds were replayed from zero (RestoreReplayKey). func OrgServes(col string) string { - return `(COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')<>'multi' OR EXISTS(SELECT 1 FROM orgs so WHERE so.id=` + col + ` AND so.status='active' AND so.enabled=1 AND so.home_region=(SELECT value FROM server_settings WHERE key='region')))` + return `(COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')<>'multi' OR EXISTS(SELECT 1 FROM orgs so WHERE so.id=` + col + ` AND so.status='active' AND so.enabled=1 AND so.home_region=(SELECT value FROM server_settings WHERE key='region') AND (so.id=(SELECT value FROM server_settings WHERE key='staff_org_id') OR NOT EXISTS(SELECT 1 FROM server_settings WHERE key='` + RestoreReplayKey + `'))))` } +// RestoreReplayKey is the server_settings row a restore writes and the elected worker deletes +// once the org and erased feeds, read from zero, have nothing more (httpapi.FinishRestoreReplay). +const RestoreReplayKey = "restore_replay" + const tenancyQuery = `SELECT COALESCE(MAX(CASE WHEN key='tenancy_mode' THEN value END),'single'),COALESCE(MAX(CASE WHEN key='staff_org_id' THEN value END),''),COALESCE(MAX(CASE WHEN key='region' THEN value END),'') FROM server_settings WHERE key IN ('tenancy_mode','staff_org_id','region')` // TenancyOfContext is the same recorded-mode read for cancellable request/worker paths. diff --git a/internal/storage/pg_archive.go b/internal/storage/pg_archive.go new file mode 100644 index 00000000..09555f27 --- /dev/null +++ b/internal/storage/pg_archive.go @@ -0,0 +1,402 @@ +package storage + +import ( + "bufio" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "io" + "slices" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "github.com/Busnes-app/kynotes-server/internal/storage/pgdialect" +) + +// The PostgreSQL archive (tenancy open question 3): a JSON header line, every table's COPY +// text rows in foreign-key order each ended by a `\.` line, then a JSON trailer line. One +// REPEATABLE READ snapshot yields every row, so the blob rows (the org-qualified object +// references) agree with the notes that use them. Encryption belongs to the caller. +const archiveFormat = "kynotes-pg-archive/1" + +// ArchiveSummary is what a backup wrote or a restore loaded. +type ArchiveSummary struct { + Schema int + TakenAt string // database clock, RFC 3339 + Rows map[string]int64 +} + +type archiveHeader struct { + Format string `json:"format"` + Schema int `json:"schema"` + TakenAt string `json:"taken_at"` + Tables []archiveTable `json:"tables"` +} + +type archiveTable struct { + Name string `json:"name"` + Columns []string `json:"columns"` +} + +type archiveTrailer struct { + Rows map[string]int64 `json:"rows"` + Sequences map[string]int64 `json:"sequences"` // next value to hand out +} + +// BackupPostgres writes the archive of the whole database db (multi mode) to w. +func BackupPostgres(ctx context.Context, db *sql.DB, w io.Writer) (ArchiveSummary, error) { + var sum ArchiveSummary + if !IsPostgres(db) { + return sum, errors.New("postgres archive: PostgreSQL only") + } + conn, err := db.Conn(ctx) + if err != nil { + return sum, err + } + defer conn.Close() + err = conn.Raw(func(dc any) error { + pc := pgdialect.PgxConn(dc) + if _, err := pc.Exec(ctx, `BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`); err != nil { + return err + } + defer pc.Exec(context.WithoutCancel(ctx), `ROLLBACK`) + var mode string + if err := pc.QueryRow(ctx, `SELECT COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')`).Scan(&mode); err != nil { + return err + } + if mode != "multi" { + return errors.New("postgres archive: recorded multi tenancy only") + } + var taken time.Time + if err := pc.QueryRow(ctx, `SELECT COALESCE(MAX(version),0), now() FROM schema_migrations`).Scan(&sum.Schema, &taken); err != nil { + return err + } + sum.TakenAt = taken.UTC().Format(time.RFC3339) + tables, err := archiveTables(ctx, pc) + if err != nil { + return err + } + head, _ := json.Marshal(archiveHeader{archiveFormat, sum.Schema, sum.TakenAt, tables}) + if _, err := w.Write(append(head, '\n')); err != nil { + return err + } + sum.Rows = map[string]int64{} + for _, t := range tables { + tag, err := pc.PgConn().CopyTo(ctx, w, `COPY `+copyTarget(t)+` TO STDOUT`) + if err != nil { + return fmt.Errorf("postgres archive: %s: %w", t.Name, err) + } + sum.Rows[t.Name] = tag.RowsAffected() + if _, err := io.WriteString(w, "\\.\n"); err != nil { + return err + } + } + seqs, err := archiveSequences(ctx, pc) + if err != nil { + return err + } + tail, _ := json.Marshal(archiveTrailer{sum.Rows, seqs}) + _, err = w.Write(append(tail, '\n')) + return err + }) + return sum, err +} + +// RestorePostgres loads an archive into db, a fresh target of the same schema, in one +// transaction with user triggers off (the rows were valid where they were written; usage +// counters must not count twice) and foreign keys checked. fence runs in that transaction +// after the triggers are back on; if anything fails nothing is loaded. +func RestorePostgres(ctx context.Context, db *sql.DB, r io.Reader, fence func(*sql.Tx) error) (ArchiveSummary, error) { + var sum ArchiveSummary + if !IsPostgres(db) { + return sum, errors.New("postgres archive: PostgreSQL only") + } + in := bufio.NewReaderSize(r, 1<<20) + var head archiveHeader + if err := readArchiveLine(in, &head); err != nil || head.Format != archiveFormat { + return sum, errors.New("postgres archive: not a KyNotes PostgreSQL archive") + } + sum.Schema, sum.TakenAt, sum.Rows = head.Schema, head.TakenAt, map[string]int64{} + conn, err := db.Conn(ctx) + if err != nil { + return sum, err + } + defer conn.Close() + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return sum, err + } + defer tx.Rollback() + var schema int + if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(version),0) FROM schema_migrations`).Scan(&schema); err != nil { + return sum, err + } + if schema != head.Schema { + return sum, fmt.Errorf("postgres archive: archive schema %d, target schema %d; restore with the release that wrote it", head.Schema, schema) + } + err = conn.Raw(func(dc any) error { + pc := pgdialect.PgxConn(dc) + tables, err := archiveTables(ctx, pc) + if err != nil { + return err + } + if !slices.EqualFunc(tables, head.Tables, func(a, b archiveTable) bool { return a.Name == b.Name && slices.Equal(a.Columns, b.Columns) }) { + return errors.New("postgres archive: the archive's tables differ from the target schema") + } + if err := clearFreshTarget(ctx, pc, tables); err != nil { + return err + } + for _, t := range tables { + if _, err := pc.Exec(ctx, `ALTER TABLE `+pgx.Identifier{t.Name}.Sanitize()+` DISABLE TRIGGER USER`); err != nil { + return err + } + } + for _, t := range tables { + tag, err := pc.PgConn().CopyFrom(ctx, ©Section{in: in}, `COPY `+copyTarget(t)+` FROM STDIN`) + if err != nil { + return fmt.Errorf("postgres archive: %s: %w", t.Name, err) + } + sum.Rows[t.Name] = tag.RowsAffected() + } + var tail archiveTrailer + if err := readArchiveLine(in, &tail); err != nil { + return errors.New("postgres archive: missing trailer") + } + if _, err := in.ReadByte(); err != io.EOF { + return errors.New("postgres archive: data after the trailer") + } + if len(tail.Rows) != len(sum.Rows) { + return errors.New("postgres archive: row counts differ from the trailer") + } + for name, n := range sum.Rows { + if tail.Rows[name] != n { + return fmt.Errorf("postgres archive: %s loaded %d rows, the archive lists %d", name, n, tail.Rows[name]) + } + } + seqs, err := archiveSequences(ctx, pc) + if err != nil { + return err + } + if len(seqs) != len(tail.Sequences) { + return errors.New("postgres archive: the archive's sequences differ from the target schema") + } + for name := range seqs { + next, ok := tail.Sequences[name] + if !ok { + return errors.New("postgres archive: the archive's sequences differ from the target schema") + } + if _, err := pc.Exec(ctx, `SELECT setval($1::regclass, $2, false)`, pgx.Identifier{name}.Sanitize(), next); err != nil { + return err + } + } + for _, t := range tables { + if _, err := pc.Exec(ctx, `ALTER TABLE `+pgx.Identifier{t.Name}.Sanitize()+` ENABLE TRIGGER USER`); err != nil { + return err + } + } + return nil + }) + if err != nil { + return sum, err + } + if err := fence(tx); err != nil { + return sum, err + } + return sum, tx.Commit() +} + +// clearFreshTarget refuses any target but a just-created one: only the rows the migrations and +// ensureOrgs write (the default theme, the single-mode record, the default org and its usage +// row). It deletes those, +// so the archive's own rows replace them. +func clearFreshTarget(ctx context.Context, pc *pgx.Conn, tables []archiveTable) error { + seeded := map[string]string{ + "server_settings": `SELECT count(*)=count(*) FILTER (WHERE key='tenancy_mode' AND value='single' OR key='default_theme') FROM server_settings`, + "orgs": `SELECT count(*)=count(*) FILTER (WHERE id='` + DefaultOrgID + `') FROM orgs`, + "org_usage": `SELECT count(*)=count(*) FILTER (WHERE org_id='` + DefaultOrgID + `' AND bytes=0) FROM org_usage`, + } + for _, t := range tables { + q, ok := seeded[t.Name] + if !ok { + q = `SELECT NOT EXISTS(SELECT 1 FROM ` + pgx.Identifier{t.Name}.Sanitize() + `)` + } + var fresh bool + if err := pc.QueryRow(ctx, q).Scan(&fresh); err != nil { + return err + } + if !fresh { + return fmt.Errorf("postgres archive: the target holds data (%s); restore only into a new, empty database", t.Name) + } + } + for _, q := range []string{`DELETE FROM org_usage`, `DELETE FROM server_settings`, `DELETE FROM orgs`} { + if _, err := pc.Exec(ctx, q); err != nil { + return err + } + } + return nil +} + +// archiveTables lists the schema's tables, parents before children, with their columns. +func archiveTables(ctx context.Context, pc *pgx.Conn) ([]archiveTable, error) { + rows, err := pc.Query(ctx, `SELECT c.relname, array_agg(a.attname ORDER BY a.attnum)::text[] +FROM pg_class c JOIN pg_attribute a ON a.attrelid=c.oid AND a.attnum>0 AND NOT a.attisdropped AND a.attgenerated='' +WHERE c.relnamespace=current_schema()::regnamespace AND c.relkind='r' AND c.relname<>'schema_migrations' +GROUP BY c.relname ORDER BY c.relname`) + if err != nil { + return nil, err + } + byName := map[string]archiveTable{} + var names []string + for rows.Next() { + var t archiveTable + if err := rows.Scan(&t.Name, &t.Columns); err != nil { + rows.Close() + return nil, err + } + byName[t.Name] = t + names = append(names, t.Name) + } + if rows.Close(); rows.Err() != nil { + return nil, rows.Err() + } + parents := map[string][]string{} + rows, err = pc.Query(ctx, `SELECT c.relname, p.relname FROM pg_constraint k +JOIN pg_class c ON c.oid=k.conrelid JOIN pg_class p ON p.oid=k.confrelid +WHERE k.contype='f' AND c.relnamespace=current_schema()::regnamespace`) + if err != nil { + return nil, err + } + for rows.Next() { + var child, parent string + if err := rows.Scan(&child, &parent); err != nil { + rows.Close() + return nil, err + } + if child == parent { + rows.Close() + return nil, fmt.Errorf("postgres archive: %s references itself; its rows need an order", child) + } + parents[child] = append(parents[child], parent) + } + if rows.Close(); rows.Err() != nil { + return nil, rows.Err() + } + var out []archiveTable + state := map[string]int{} // 1 visiting, 2 done + var visit func(string) error + visit = func(n string) error { + switch state[n] { + case 1: + return fmt.Errorf("postgres archive: foreign keys form a cycle at %s", n) + case 2: + return nil + } + state[n] = 1 + for _, p := range parents[n] { + if err := visit(p); err != nil { + return err + } + } + state[n] = 2 + out = append(out, byName[n]) + return nil + } + for _, n := range names { + if err := visit(n); err != nil { + return nil, err + } + } + return out, nil +} + +// archiveSequences reads each sequence's next value. Sequences are not transactional, so +// this is at least the snapshot's value, which keeps them increasing after a restore. +func archiveSequences(ctx context.Context, pc *pgx.Conn) (map[string]int64, error) { + rows, err := pc.Query(ctx, `SELECT c.relname FROM pg_class c WHERE c.relnamespace=current_schema()::regnamespace AND c.relkind='S' ORDER BY 1`) + if err != nil { + return nil, err + } + names, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + return nil, err + } + out := map[string]int64{} + for _, n := range names { + var last int64 + var called bool + if err := pc.QueryRow(ctx, `SELECT last_value, is_called FROM `+pgx.Identifier{n}.Sanitize()).Scan(&last, &called); err != nil { + return nil, err + } + if called { + last++ + } + out[n] = last + } + return out, nil +} + +func copyTarget(t archiveTable) string { + cols := make([]string, len(t.Columns)) + for i, c := range t.Columns { + cols[i] = pgx.Identifier{c}.Sanitize() + } + return pgx.Identifier{t.Name}.Sanitize() + ` (` + strings.Join(cols, ",") + `)` +} + +// readArchiveLine decodes one JSON line of at most 1 MiB. +func readArchiveLine(in *bufio.Reader, v any) error { + line, err := in.ReadSlice('\n') + if err != nil { + return errors.New("postgres archive: truncated") + } + dec := json.NewDecoder(strings.NewReader(string(line))) + dec.DisallowUnknownFields() + return dec.Decode(v) +} + +// copySection reads one table's COPY text rows, up to and without its `\.` line. COPY text +// escapes every backslash in data, so no row is that line. +type copySection struct { + in *bufio.Reader + pending []byte // the rest of the last chunk that did not fit + midLine bool + done bool +} + +func (c *copySection) Read(p []byte) (int, error) { + if len(c.pending) > 0 { + n := copy(p, c.pending) + c.pending = c.pending[n:] + return n, nil + } + if c.done { + return 0, io.EOF + } + if !c.midLine { + peek, err := c.in.Peek(3) + if err == nil && string(peek) == "\\.\n" { + c.in.Discard(3) + c.done = true + return 0, io.EOF + } + if err != nil { // the trailer always follows a section + return 0, errors.New("postgres archive: truncated") + } + } + chunk, err := c.in.ReadSlice('\n') + switch { + case errors.Is(err, bufio.ErrBufferFull): + c.midLine = true + case err != nil: + return 0, errors.New("postgres archive: truncated") + default: + c.midLine = false + } + n := copy(p, chunk) + c.pending = append([]byte(nil), chunk[n:]...) // ReadSlice's bytes die at the next read + return n, nil +} diff --git a/internal/storage/pg_archive_test.go b/internal/storage/pg_archive_test.go new file mode 100644 index 00000000..de8bee36 --- /dev/null +++ b/internal/storage/pg_archive_test.go @@ -0,0 +1,191 @@ +package storage + +import ( + "bytes" + "context" + "database/sql" + "errors" + "slices" + "strings" + "testing" +) + +func archiveFixture(t *testing.T) (*Store, []byte) { + t.Helper() + if !OnPostgresTest() { + t.Skip("PostgreSQL archive") + } + src, _, _ := purgeFixture(t) + // A value with every COPY escape, including a line that reads `\.` before escaping. + odd := "tab\there\nline\n\\.\n\\.\r\\N é \x01 '\"" + for _, q := range []string{`INSERT INTO server_settings(key,value,updated_at) VALUES('odd',?,'t')`, `SELECT nextval('org_storage_report_seq')`, `SELECT nextval('org_storage_report_seq')`} { + var args []any + if strings.Contains(q, "?") { + args = []any{odd} + } + if _, err := src.db.Exec(q, args...); err != nil { + t.Fatal(err) + } + } + if _, err := src.db.Exec(`INSERT INTO org_pool(org_id,seq,expires_at,over_since) VALUES('org_null',2,'x',NULL); INSERT INTO erased_subjects(subject,org_id,revision) VALUES('erased-fence','org_a',4)`); err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + sum, err := BackupPostgres(t.Context(), src.db, &buf) + if err != nil { + t.Fatal(err) + } + if sum.Schema == 0 || sum.TakenAt == "" || sum.Rows["blobs"] != 2 || sum.Rows["users"] != 4 { + t.Fatalf("summary %+v", sum) + } + return src, buf.Bytes() +} + +// tableDigests is every table's row count and content digest, schema names aside. +func tableDigests(t *testing.T, s *Store) map[string]string { + t.Helper() + out := map[string]string{} + for _, table := range catalogTables(t, s) { + if table == "schema_migrations" { + continue + } + var n int + var digest string + if err := s.db.QueryRow(`SELECT count(*), COALESCE(md5(string_agg(x::text, chr(10) ORDER BY x::text)),'') FROM "`+table+`" x`).Scan(&n, &digest); err != nil { + t.Fatal(err) + } + out[table] = digest + } + return out +} + +func noFence(*sql.Tx) error { return nil } + +// A backup restored into a new database holds every row of every table, byte for byte, with +// sequences carried over and every trigger back on. +func TestPostgresArchiveRoundTripsEveryRow(t *testing.T) { + src, archive := archiveFixture(t) + dst := openFresh(t) + sum, err := RestorePostgres(t.Context(), dst.db, bytes.NewReader(archive), noFence) + if err != nil { + t.Fatal(err) + } + want, got := tableDigests(t, src), tableDigests(t, dst) + var empty []string + for table, d := range want { + if got[table] != d { + t.Errorf("%s differs after the round trip", table) + } + if sum.Rows[table] == 0 { + empty = append(empty, table) + } + } + slices.Sort(empty) + if len(got) != len(want) || strings.Join(empty, ",") != "idempotency,idempotency_keys,replica_lockouts,replica_logins,replica_rates,sso_logout_events,sso_sync_events" { + t.Fatalf("tables %d/%d; empty %v: seed the new table in purgeFixture or archiveFixture", len(got), len(want), empty) + } + var odd string + if err := dst.db.QueryRow(`SELECT value FROM server_settings WHERE key='odd'`).Scan(&odd); err != nil || !strings.Contains(odd, "\n\\.\n") { + t.Fatalf("escaped value %q: %v", odd, err) + } + var next int64 + if err := dst.db.QueryRow(`SELECT nextval('org_storage_report_seq')`).Scan(&next); err != nil || next != 3 { + t.Fatalf("sequence next=%d: %v", next, err) + } + var off int + if err := dst.db.QueryRow(`SELECT count(*) FROM pg_trigger g JOIN pg_class c ON c.oid=g.tgrelid WHERE c.relnamespace=current_schema()::regnamespace AND NOT g.tgisinternal AND g.tgenabled<>'O'`).Scan(&off); err != nil || off != 0 { + t.Fatalf("%d triggers left off: %v", off, err) + } + // Usage triggers count again once the load is done. + var before, after int64 + dst.db.QueryRow(`SELECT bytes FROM org_usage WHERE org_id='org_a'`).Scan(&before) + if _, err := dst.db.Exec(`UPDATE object_versions SET ciphertext_bytes=ciphertext_bytes+5 WHERE org_id='org_a'`); err != nil { + t.Fatal(err) + } + dst.db.QueryRow(`SELECT bytes FROM org_usage WHERE org_id='org_a'`).Scan(&after) + if after != before+5 { + t.Fatalf("usage %d -> %d: triggers are not back on", before, after) + } +} + +// A restore loads all or nothing: a damaged archive, a failing fence or a target that holds +// data leave the target as it was, and a fresh target still takes the archive afterwards. +func TestPostgresArchiveRestoreIsAllOrNothing(t *testing.T) { + src, archive := archiveFixture(t) + head := bytes.IndexByte(archive, '\n') + cases := map[string]struct { + archive []byte + fence func(*sql.Tx) error + }{ + "truncated": {archive[:len(archive)/2], noFence}, + "no trailer": {archive[:bytes.LastIndexByte(archive[:len(archive)-1], '\n')+1], noFence}, + "extra data": {append(append([]byte{}, archive...), "x\n"...), noFence}, + "other schema": {append([]byte(strings.Replace(string(archive[:head]), `"schema":`, `"schema":9`, 1)), archive[head:]...), noFence}, + "failing fence": {archive, func(*sql.Tx) error { return errors.New("fence failed") }}, + "wrong row count": {[]byte(strings.Replace(string(archive), `"blobs":2`, `"blobs":3`, 1)), noFence}, + } + dst := openFresh(t) + fresh := tableDigests(t, dst) + for name, c := range cases { + if _, err := RestorePostgres(t.Context(), dst.db, bytes.NewReader(c.archive), c.fence); err == nil { + t.Fatalf("%s: restore succeeded", name) + } + for table, d := range tableDigests(t, dst) { + if fresh[table] != d { + t.Fatalf("%s: %s changed", name, table) + } + } + } + srcBefore := tableDigests(t, src) + if _, err := RestorePostgres(t.Context(), src.db, bytes.NewReader(archive), noFence); err == nil || !strings.Contains(err.Error(), "holds data") { + t.Fatalf("restore over data: %v", err) + } + for table, d := range tableDigests(t, src) { + if srcBefore[table] != d { + t.Fatalf("a refused restore changed %s", table) + } + } + if _, err := RestorePostgres(t.Context(), dst.db, bytes.NewReader(archive), noFence); err != nil { + t.Fatalf("after the failures: %v", err) + } +} + +// The archive's snapshot is one transaction: a write committed while the backup runs is +// either wholly in it or wholly out (here: blocked behind the first table, so out). +func TestPostgresArchiveIsOneSnapshot(t *testing.T) { + src, _ := archiveFixture(t) + w := &hookWriter{hook: func() { + if _, err := src.db.Exec(`INSERT INTO server_settings(key,value,updated_at) VALUES('late','x','t')`); err != nil { + t.Error(err) + } + if _, err := src.db.Exec(`DELETE FROM blob_containers`); err != nil { + t.Error(err) + } + }} + if _, err := BackupPostgres(context.Background(), src.db, w); err != nil { + t.Fatal(err) + } + dst := openFresh(t) + if _, err := RestorePostgres(t.Context(), dst.db, bytes.NewReader(w.buf.Bytes()), noFence); err != nil { + t.Fatal(err) + } + var late, refs int + dst.db.QueryRow(`SELECT count(*) FROM server_settings WHERE key='late'`).Scan(&late) + dst.db.QueryRow(`SELECT count(*) FROM blob_containers`).Scan(&refs) + if late != 0 || refs != 2 { + t.Fatalf("late=%d refs=%d: the archive mixed two states", late, refs) + } +} + +type hookWriter struct { + buf bytes.Buffer + hook func() +} + +func (h *hookWriter) Write(p []byte) (int, error) { + if h.hook != nil && h.buf.Len() > 0 { // after the header line: the snapshot is taken + h.hook() + h.hook = nil + } + return h.buf.Write(p) +} diff --git a/internal/storage/pgdialect/driver.go b/internal/storage/pgdialect/driver.go index 9606f3d0..c10551f8 100644 --- a/internal/storage/pgdialect/driver.go +++ b/internal/storage/pgdialect/driver.go @@ -392,3 +392,12 @@ func named(args []driver.Value) []driver.NamedValue { } return out } + +// PgxConn returns the pgx connection under a driver connection from sql.Conn.Raw, for the +// COPY protocol, or nil for any other driver. +func PgxConn(driverConn any) *pgx.Conn { + if c, ok := driverConn.(*conn); ok { + return c.inner.Conn() + } + return nil +} diff --git a/internal/storage/restore_tenancy.go b/internal/storage/restore_tenancy.go index 989f5a00..83d396d3 100644 --- a/internal/storage/restore_tenancy.go +++ b/internal/storage/restore_tenancy.go @@ -23,6 +23,7 @@ func ResetTenancyAfterRestore(ctx context.Context, tx *sql.Tx) error { `DELETE FROM replica_presence`, `UPDATE reminders SET claimed_until=0,claim_token=''`, `DELETE FROM server_settings WHERE key IN ('org_poll_revision','erased_poll_revision','replica_config_fingerprint','blob_probe','blob_probe_prev')`, + `INSERT INTO server_settings(key,value,updated_at) VALUES('` + RestoreReplayKey + `','pending',to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"')) ON CONFLICT(key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at`, } { if _, err := tx.ExecContext(ctx, q); err != nil { return err From 3d174e585c6bf4d6259eb1c9d705fc1090b2562f Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 01:02:06 -0500 Subject: [PATCH 2/2] fix(tenancy): order archive tables by schema alone The foreign-key query had no ORDER BY, so a table with several parents could be laid out in another valid order on the target than on the source, and the restore, which compares table lists position by position, would refuse a good archive. Names and parent lists are now sorted before the topological walk. Co-Authored-By: Claude Opus 5.5 --- internal/storage/pg_archive.go | 12 +++++++++-- internal/storage/pg_archive_test.go | 31 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/internal/storage/pg_archive.go b/internal/storage/pg_archive.go index 09555f27..8e388644 100644 --- a/internal/storage/pg_archive.go +++ b/internal/storage/pg_archive.go @@ -266,7 +266,7 @@ GROUP BY c.relname ORDER BY c.relname`) parents := map[string][]string{} rows, err = pc.Query(ctx, `SELECT c.relname, p.relname FROM pg_constraint k JOIN pg_class c ON c.oid=k.conrelid JOIN pg_class p ON p.oid=k.confrelid -WHERE k.contype='f' AND c.relnamespace=current_schema()::regnamespace`) +WHERE k.contype='f' AND c.relnamespace=current_schema()::regnamespace ORDER BY 1,2`) if err != nil { return nil, err } @@ -285,6 +285,14 @@ WHERE k.contype='f' AND c.relnamespace=current_schema()::regnamespace`) if rows.Close(); rows.Err() != nil { return nil, rows.Err() } + return orderTables(names, byName, parents) +} + +// orderTables puts parents before children. Names and each parent list are sorted first, so +// the order depends on the schema alone, never on catalog scan order: restore compares the +// archive's table list with the target's position by position. +func orderTables(names []string, byName map[string]archiveTable, parents map[string][]string) ([]archiveTable, error) { + names = slices.Sorted(slices.Values(names)) var out []archiveTable state := map[string]int{} // 1 visiting, 2 done var visit func(string) error @@ -296,7 +304,7 @@ WHERE k.contype='f' AND c.relnamespace=current_schema()::regnamespace`) return nil } state[n] = 1 - for _, p := range parents[n] { + for _, p := range slices.Sorted(slices.Values(parents[n])) { if err := visit(p); err != nil { return err } diff --git a/internal/storage/pg_archive_test.go b/internal/storage/pg_archive_test.go index de8bee36..ee7e7e8e 100644 --- a/internal/storage/pg_archive_test.go +++ b/internal/storage/pg_archive_test.go @@ -189,3 +189,34 @@ func (h *hookWriter) Write(p []byte) (int, error) { } return h.buf.Write(p) } + +// The table order depends only on the schema: the same foreign keys listed in any catalog +// order give the same archive layout, so a restore never refuses an identical schema. +func TestArchiveTableOrderIgnoresCatalogOrder(t *testing.T) { + names := []string{"y", "child", "x", "a"} + byName := map[string]archiveTable{} + for _, n := range names { + byName[n] = archiveTable{Name: n} + } + order := func(names []string, parents map[string][]string) string { + t.Helper() + got, err := orderTables(names, byName, parents) + if err != nil { + t.Fatal(err) + } + var s []string + for _, tb := range got { + s = append(s, tb.Name) + } + return strings.Join(s, ",") + } + // child sorts before its parents, so its parent list decides their order. + one := order(names, map[string][]string{"child": {"y", "x"}}) + two := order([]string{"x", "a", "child", "y"}, map[string][]string{"child": {"x", "y"}}) + if one != two || one != "a,x,y,child" { + t.Fatalf("orders %q and %q", one, two) + } + if _, err := orderTables([]string{"a", "b"}, byName, map[string][]string{"a": {"b"}, "b": {"a"}}); err == nil { + t.Fatal("a cycle was ordered") + } +}