Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions cmd/kynotes-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
122 changes: 122 additions & 0 deletions cmd/kynotes-server/postgres_backup.go
Original file line number Diff line number Diff line change
@@ -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
}
68 changes: 68 additions & 0 deletions cmd/kynotes-server/postgres_backup_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
37 changes: 36 additions & 1 deletion docs/RESTORE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
42 changes: 41 additions & 1 deletion docs/superpowers/specs/2026-11-23-tenancy-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions internal/app/replica_schedules.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) })
Expand Down
Loading