diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3374f0ce..99825ad2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,10 +90,10 @@ jobs: KYNOTES_TEST_DATABASE_URL: postgres://postgres@localhost:5432/postgres?sslmode=disable run: go test -race -count=1 -timeout 20m -p 2 ./internal/storage/... ./internal/httpapi/... ./internal/auth/... ./internal/app/... ./internal/sso/... ./internal/orgsync/... ./internal/worker/... ./internal/blobstore/... ./cmd/kynotes-mcp/... - - name: PostgreSQL restored-target safety + - 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' + run: go test -race -count=1 -timeout 20m -p 2 ./internal/backup ./cmd/kynotes-server -run '^(TestPostgresRestore|TestStaffUserCommand)' checks: if: github.event.pull_request.draft != true diff --git a/AGENTS.md b/AGENTS.md index fceda8fd..3c3cbccf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -301,6 +301,19 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che It does not yet implement the complete Backend/Temporary adapter or runtime selection. Preserve single volume behavior; exclusive marker creation/provider age metadata, GC, provider qualification and hosted startup remain prerequisites. See blobstore's child DOX. + +- Host-only tenancy maintenance uses the exact existing PG schema without migrations. + `user add --admin --username` in multi mode accepts bounded derived credentials on stdin, + validates the recorded staff org/region from environment and commits the account/audit together. + No customer/everyday account or password/DSN argv path exists there. Startup bootstrap + preparation seeds only staff accounts, rechecks under N3, refuses everyday variables and + audits; the single bootstrap/CLI paths retain their original behavior. + `accept-replica-config --confirm-stopped` loads the complete app-owned field map through a + separate read-only maintenance loader, requires the retained salt key and fixed mode/staff/ + region, and atomically audits changed names only. Stop every replica first. Normal config + loaders and multi startup remain refused; maintenance never mints local keys or recovers bytes. + Verify `TestStaffUserCommand*`, `TestStaffBootstrap*`, `TestReplicaMaintenance*`, + `TestReplicaAccept*`, existing bootstrap/user/golden tests and both backend race profiles. - 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 55b0a112..c5d12b70 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1030,3 +1030,20 @@ issued remote PUT after lock loss. Complete GC/purge/runtime integration require and qualified delayed-writer erasure fence before deletion/readiness claims. The shared conditional API does not choose a product ledger/protocol. Store controls/age and selected provider proof, native-PG recovery transport and final assembly remain launch prerequisites. + +### Host staff and replica maintenance preparation + +Recorded multi-mode host account creation targets only the retained staff org on an exact +existing PostgreSQL schema. Derived proof/salt/iterations enter through bounded stdin JSON; +DSN and install identity enter through environment. The account and platform audit commit +before emitting a recovery code. Customer/everyday creation and raw password argv are refused. +The future startup bootstrap adapter creates one dedicated staff administrator across replicas, +with password work before N3 and an in-lock emptiness/binding recheck; it refuses everyday +bootstrap variables. Single-mode account creation remains unchanged. + +Explicit `accept-replica-config --confirm-stopped` reads deployment settings without local +key reads/minting, then derives the complete existing application fingerprint map. Normal +config loading still refuses multi. Acceptance requires the retained server salt (also the +sealed recovery-token key) and immutable mode/staff/region; changed field names and the new +fingerprint commit together. The operator stops every replica before this offline command. +No automatic mismatch acceptance, schema migration, backup transport or startup enablement. diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index b7c2a1b3..ba80f183 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -2319,8 +2319,8 @@ regular credential files may end with one LF/CRLF; bounded reads, source/type fa client validation errors disclose setting names only. Construction makes no network request, local key/store or SQL write. No normal config loader or startup path invokes it. -The base shared client is pinned to merged #77 (`79823f9`); published #78's exclusive-create, -ETag and age additions remain unmerged and are not consumed. Complete Backend/Temporary, +The base shared client is pinned to merged #77 (`79823f9`); #78's exclusive-create, +ETag and age additions are merged as `b55ca6d` but are not consumed by this pin. Complete Backend/Temporary, store-ID/probes, request/GC/purge integration and provider evidence remain unbuilt. Before binding GC/purge/runtime, qualify the fate of an already-issued remote PUT after the @@ -2330,3 +2330,24 @@ must be recorded here before erasure-readiness claims; consuming wire-only condi does not select Messages' ledger/protocol. Preserve access fences while this is unresolved. Native encrypted PG base-backup/WAL tool/transport, destination/retention and restore/drill remain spec open question 3. Startup remains refused; existing single-mode behavior stays. + +### Phase 6 host maintenance preparation + +Built host-only PG staff creation with bounded stdin derived credentials and environment-only +target/identity, atomic platform audit and recovery-code output after commit. Existing single +CLI remains unchanged. Staff bootstrap preparation is staff-only, audited and one-create across +independent pools; everyday bootstrap variables refuse. N6 also governs the no-admin warning. +Built explicit stopped-replica configuration acceptance over the full app field map, read-only +maintenance config loading, retained salt and fixed install bindings, audit/name-only output, +and exact-schema/no-migration PG opens. Ordinary startup loaders still refuse multi. + +Tests cover real password verification/wrong proof, duplicate/invalid input, wrong org/region, +output/error secret boundaries, audit rollback, concurrent bootstrap, full fingerprint acceptance, +retained-key/immutable-binding refusal and untouched single-mode workflows. PG CI includes the +native staff-command cases without moving SQLite capsule tests to PG. Required race/FIPS, +full PG, golden, build/vet, web/dist and docs checks remain gates. + +Unbuilt: hosted startup/SSO/runtime assembly and complete lifecycle E2E, primary object/part/ +GC/purge/provider evidence through the exported shared S3 client, and native PostgreSQL backup +transport/retention/drill after open question 3 is selected. Host maintenance alone does not +qualify a deployment; owner interface approval remains required for its operator surface. diff --git a/README.md b/README.md index 2625f01b..2cecbc03 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ the database and deployment secrets, while ciphertext blobs require separate rec Read the [restore runbook](docs/RESTORE.md) before relying on a backup. Native PostgreSQL restored-target safety preparation is documented there for tenancy rehearsals; it does not enable hosted startup or provide a PostgreSQL backup transport. +[Offline host maintenance preparation](docs/DEPLOYMENT.md#offline-host-maintenance-preparation) +covers staff account creation and explicit configuration acceptance for tenancy rehearsals; +these commands do not enable hosted startup. To check that a release image came from this repository's release workflow, and to rebuild its binary to the same bytes, see [verifying releases](docs/VERIFYING-RELEASES.md). The security diff --git a/cmd/kynotes-server/main.go b/cmd/kynotes-server/main.go index 31e27c13..9e827985 100644 --- a/cmd/kynotes-server/main.go +++ b/cmd/kynotes-server/main.go @@ -51,6 +51,12 @@ func main() { os.Exit(1) } return + case "accept-replica-config": + if e := acceptReplicaConfigCommand(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) @@ -540,6 +546,12 @@ func checkCommand(kind string, args []string) error { var errUserAddUsage = errors.New("usage: user add --username [--password ] [--admin | --everyday] (default --everyday; --admin creates an administrator account, which cannot open notes)") func userCommand(args []string) error { + if os.Getenv("KYNOTES_TENANCY") == "multi" { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + return staffUserCommand(ctx, args, os.Stdin, os.Stdout) + } + if len(args) < 1 || args[0] != "add" { return errUserAddUsage } diff --git a/cmd/kynotes-server/replica_accept.go b/cmd/kynotes-server/replica_accept.go new file mode 100644 index 00000000..d142d9d5 --- /dev/null +++ b/cmd/kynotes-server/replica_accept.go @@ -0,0 +1,29 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "time" + + "github.com/Busnes-app/kynotes-server/internal/app" +) + +func acceptReplicaConfigCommand(args []string, stdout io.Writer) error { + flags := flag.NewFlagSet("accept-replica-config", flag.ContinueOnError) + flags.SetOutput(io.Discard) + confirm := flags.Bool("confirm-stopped", false, "every replica has been stopped") + path := flags.String("config", "/data/kynotes.yaml", "deployment configuration") + if err := flags.Parse(args); err != nil || flags.NArg() != 0 || !*confirm { + return errors.New("usage: accept-replica-config --confirm-stopped [--config ]; stop every replica first") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + if err := app.AcceptReplicaConfiguration(ctx, *path); err != nil { + return err + } + _, err := fmt.Fprintln(stdout, "Accepted shared configuration; changed field names audited. Start only replicas with the accepted settings when every hosted prerequisite is satisfied. This command does not enable multi startup.") + return err +} diff --git a/cmd/kynotes-server/replica_accept_test.go b/cmd/kynotes-server/replica_accept_test.go new file mode 100644 index 00000000..b9d3f54b --- /dev/null +++ b/cmd/kynotes-server/replica_accept_test.go @@ -0,0 +1,18 @@ +package main + +import ( + "bytes" + "strings" + "testing" +) + +func TestReplicaMaintenanceCommandRequiresStoppedAcknowledgment(t *testing.T) { + t.Setenv("KYNOTES_DB_DSN", "postgres://operator:private-dsn-secret@%zz/invalid") + var out bytes.Buffer + for _, args := range [][]string{nil, {"--config", "missing.yaml"}, {"--confirm-stopped", "extra"}, {"--confirm-stopped", "--password", "private-flag-secret"}} { + err := acceptReplicaConfigCommand(args, &out) + if err == nil || out.Len() != 0 || strings.Contains(err.Error(), "private-") { + t.Fatalf("command boundary: %v", err) + } + } +} diff --git a/cmd/kynotes-server/staff_user.go b/cmd/kynotes-server/staff_user.go new file mode 100644 index 00000000..a4af14a9 --- /dev/null +++ b/cmd/kynotes-server/staff_user.go @@ -0,0 +1,123 @@ +package main + +import ( + "bytes" + "context" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + "unicode" + + "github.com/Busnes-app/kynotes-server/internal/auth" + "github.com/Busnes-app/kynotes-server/internal/ids" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +// Multi mode's host-only break-glass path never opens a data directory or mints server keys. +// The existing single-mode command remains responsible for its original flags and behavior. +func staffUserCommand(ctx context.Context, args []string, stdin io.Reader, stdout io.Writer) error { + usage := errors.New("multi mode: user add --admin --username ; derived {authSecret,loginSalt,iterations} on stdin, target/shared identity in environment") + if len(args) == 0 || args[0] != "add" { + return usage + } + flags := flag.NewFlagSet("user add", flag.ContinueOnError) + flags.SetOutput(io.Discard) + admin := flags.Bool("admin", false, "create a staff administrator") + name := flags.String("username", "", "dedicated administrator username") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 || !*admin { + return usage + } + username := strings.ToLower(strings.TrimSpace(*name)) + if username == "" || len(username) > 128 || strings.IndexFunc(username, unicode.IsControl) >= 0 { + return usage + } + dsn, staffOrg, region := os.Getenv("KYNOTES_DB_DSN"), os.Getenv("KYNOTES_STAFF_ORG_ID"), os.Getenv("KYNOTES_REGION") + if dsn == "" || staffOrg == "" || region == "" { + return errors.New("staff creation requires KYNOTES_DB_DSN, KYNOTES_STAFF_ORG_ID and KYNOTES_REGION in the environment") + } + if file, ok := stdin.(*os.File); ok { + if state, err := file.Stat(); err == nil && state.Mode()&os.ModeCharDevice != 0 { + fmt.Fprintln(os.Stderr, "Reading JSON {authSecret, loginSalt, iterations} from stdin; end it with Ctrl-D.") + } + } + raw, err := io.ReadAll(io.LimitReader(stdin, 4097)) + if err != nil || len(raw) == 0 || len(raw) > 4096 { + return errors.New("stdin must contain bounded derived credentials JSON") + } + var in struct { + AuthSecret string `json:"authSecret"` + LoginSalt string `json:"loginSalt"` + Iterations int `json:"iterations"` + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + if decoder.Decode(&in) != nil || decoder.Decode(&struct{}{}) != io.EOF { + return errors.New("stdin must contain only derived authSecret, loginSalt and iterations") + } + secret, err := hex.DecodeString(in.AuthSecret) + if err != nil || len(secret) != 32 || in.AuthSecret != strings.ToLower(in.AuthSecret) { + return errors.New("derived authSecret must be 32 bytes in lowercase hexadecimal") + } + salt, err := base64.StdEncoding.Strict().DecodeString(in.LoginSalt) + if err != nil || len(salt) < 16 || len(salt) > 64 { + return errors.New("loginSalt must be 16 to 64 bytes in standard base64") + } + if in.Iterations == 0 { + in.Iterations = auth.LoginIterations + } + if in.Iterations < auth.LoginIterations || in.Iterations > 1000000 { + return errors.New("iterations must be between 600000 and 1000000") + } + store, err := storage.OpenPostgresCurrent(ctx, dsn) + if err != nil { + return errors.New("cannot open the exact existing PostgreSQL schema; check target and matching release") + } + defer store.Close() + // Verify the recorded target before spending password-hash work or creating credentials. + tenancy, err := storage.TenancyOfContext(ctx, store.DB()) + if err != nil || !tenancy.Multi() || tenancy.StaffOrg != staffOrg || tenancy.Region != region { + return errors.New("recorded multi-mode staff org or region differs; no account created") + } + hash, err := auth.HashAuthSecret(in.AuthSecret) + if err != nil { + return errors.New("password verifier unavailable; no account created") + } + code, recoveryHash, err := auth.NewRecoveryCode() + if err != nil { + return err + } + id, err := ids.Mint("usr") + if err != nil { + return err + } + now := time.Now().UTC().Format(time.RFC3339) + err = store.WithTx(ctx, func(tx *sql.Tx) error { + current, err := storage.TenancyOfContext(ctx, tx) + if err != nil { + return err + } + if current != tenancy { + return errors.New("target changed") + } + if _, err := tx.ExecContext(ctx, `INSERT INTO users(id,username,auth_secret_hash,login_salt,login_iterations,recovery_hash,role,account_kind,status,password_admin_known,created_at,updated_at,org_id) VALUES(?,?,?,?,?,?,'admin','admin','active',1,?,?,?)`, id, username, hash, in.LoginSalt, in.Iterations, recoveryHash, now, now, staffOrg); err != nil { + return err + } + return storage.RecordAuditOutcomeTx(tx, "", "admin.user.create", "", id, "success", "kind=admin,source=host", "staff-user-add") + }) + if err != nil { + return errors.New("staff account creation failed; check target, username and audit availability") + } + _, err = fmt.Fprintf(stdout, "Created staff administrator %s.\nrecovery code: %s\nStore it offline; it is shown once. This administrator cannot open notes.\n", username, code) + if err != nil { + return errors.New("staff account was created but recovery-code output failed; retain the input credentials") + } + return nil +} diff --git a/cmd/kynotes-server/staff_user_test.go b/cmd/kynotes-server/staff_user_test.go new file mode 100644 index 00000000..696cfecf --- /dev/null +++ b/cmd/kynotes-server/staff_user_test.go @@ -0,0 +1,145 @@ +package main + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Busnes-app/kynotes-server/internal/auth" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +func staffCredentials() string { + raw, _ := json.Marshal(map[string]any{"authSecret": strings.Repeat("a", 64), "loginSalt": base64.StdEncoding.EncodeToString([]byte("0123456789abcdef")), "iterations": auth.LoginIterations}) + return string(raw) +} +func staffTarget(t *testing.T) *storage.Store { + t.Helper() + if !storage.OnPostgresTest() { + t.Skip("native PostgreSQL staff target") + } + st, err := storage.Open(filepath.Join(t.TempDir(), "staff.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + for _, q := range []string{`UPDATE server_settings SET value='multi' WHERE key='tenancy_mode'`, `INSERT INTO orgs(id,status,home_region) VALUES('org_staff','active','local')`, `INSERT INTO server_settings(key,value,updated_at) VALUES('staff_org_id','org_staff','t'),('region','local','t')`} { + if _, err := st.DB().Exec(q); err != nil { + t.Fatal(err) + } + } + var schema string + if err := st.DB().QueryRow(`SELECT current_schema()`).Scan(&schema); err != nil { + t.Fatal(err) + } + dsn, err := url.Parse(os.Getenv("KYNOTES_TEST_DATABASE_URL")) + if err != nil { + t.Fatal(err) + } + q := dsn.Query() + q.Set("search_path", schema) + dsn.RawQuery = q.Encode() + t.Setenv("KYNOTES_TENANCY", "multi") + t.Setenv("KYNOTES_DB_DSN", dsn.String()) + t.Setenv("KYNOTES_STAFF_ORG_ID", "org_staff") + t.Setenv("KYNOTES_REGION", "local") + return st +} +func TestStaffUserCommandValidatesBeforeWriting(t *testing.T) { + t.Setenv("KYNOTES_DB_DSN", "postgres://operator:fixture-secret-password@%zz/invalid") + t.Setenv("KYNOTES_STAFF_ORG_ID", "org_staff") + t.Setenv("KYNOTES_REGION", "local") + for _, args := range [][]string{nil, {"add", "--username", "staff"}, {"add", "--admin", "--everyday", "--username", "staff"}, {"add", "--admin", "--username", "staff", "--password", "fixture-secret-password"}} { + var out bytes.Buffer + if err := staffUserCommand(t.Context(), args, strings.NewReader(staffCredentials()), &out); err == nil || out.Len() != 0 || strings.Contains(err.Error(), "fixture-secret-password") { + t.Fatalf("flag boundary: %v", err) + } + } + for _, input := range []string{"", strings.Repeat("x", 4097), `{"password":"fixture-secret-password"}`, strings.ReplaceAll(staffCredentials(), strings.Repeat("a", 64), strings.Repeat("x", 64)), staffCredentials() + `{}`} { + var out bytes.Buffer + if err := staffUserCommand(t.Context(), []string{"add", "--admin", "--username", "staff"}, strings.NewReader(input), &out); err == nil || out.Len() != 0 || strings.Contains(err.Error(), "fixture-secret-password") { + t.Fatalf("credential boundary: %v", err) + } + } + var out bytes.Buffer + if err := staffUserCommand(t.Context(), []string{"add", "--admin", "--username", "staff"}, strings.NewReader(staffCredentials()), &out); err == nil || strings.Contains(err.Error(), "fixture-secret-password") { + t.Fatalf("DSN boundary: %v", err) + } +} +func TestStaffUserCommandCreatesOnlyAuditedStaffAdministrator(t *testing.T) { + st := staffTarget(t) + var out bytes.Buffer + args := []string{"add", "--admin", "--username", " Staff.Operator "} + if err := staffUserCommand(t.Context(), args, strings.NewReader(staffCredentials()), &out); err != nil { + t.Fatal(err) + } + var id, kind, role, org, hash, recovery string + var iterations, known int + if err := st.DB().QueryRow(`SELECT id,account_kind,role,org_id,auth_secret_hash,recovery_hash,login_iterations,password_admin_known FROM users WHERE username='staff.operator'`).Scan(&id, &kind, &role, &org, &hash, &recovery, &iterations, &known); err != nil { + t.Fatal(err) + } + if kind != "admin" || role != "admin" || org != "org_staff" || iterations != auth.LoginIterations || known != 1 || recovery == "" { + t.Fatal("staff account contract changed") + } + if err := auth.VerifyAuthSecret(strings.Repeat("a", 64), hash); err != nil { + t.Fatal("real password verifier refused supplied proof") + } + if err := auth.VerifyAuthSecret(strings.Repeat("b", 64), hash); err == nil { + t.Fatal("wrong proof matched") + } + if !strings.Contains(out.String(), "recovery code:") || strings.Contains(out.String(), strings.Repeat("a", 64)) { + t.Fatal("unexpected credential output") + } + var n int + if err := st.DB().QueryRow(`SELECT count(*) FROM audit_events WHERE event='admin.user.create' AND object_id=? AND org_id IS NULL AND reason_code='kind=admin,source=host'`, id).Scan(&n); err != nil || n != 1 { + t.Fatal("staff creation not audited") + } + if _, err := st.DB().Exec(`INSERT INTO containers(id,kind,owner_user_id,created_at,updated_at,org_id) VALUES('cnt_forbidden','workbook',?,'t','t','org_staff')`, id); err == nil { + t.Fatal("administrator acquired ordinary content") + } + out.Reset() + if err := staffUserCommand(t.Context(), args, strings.NewReader(staffCredentials()), &out); err == nil || out.Len() != 0 { + t.Fatal("duplicate staff creation changed credentials or returned a new recovery code") + } +} +func TestStaffUserCommandRefusesWrongTargetAndRollsBackAuditFailure(t *testing.T) { + for _, kind := range []string{"single", "staff-org", "region", "audit", "cancel"} { + t.Run(kind, func(t *testing.T) { + st := staffTarget(t) + switch kind { + case "single": + if _, err := st.DB().Exec(`UPDATE server_settings SET value='single' WHERE key='tenancy_mode'`); err != nil { + t.Fatal(err) + } + case "staff-org": + t.Setenv("KYNOTES_STAFF_ORG_ID", "org_customer") + case "region": + t.Setenv("KYNOTES_REGION", "another-region") + case "audit": + if _, err := st.DB().Exec(`CREATE FUNCTION refuse_staff() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.event='admin.user.create' THEN RAISE EXCEPTION 'test audit unavailable'; END IF; RETURN NEW; END $$; CREATE TRIGGER refuse_staff BEFORE INSERT ON audit_events FOR EACH ROW EXECUTE FUNCTION refuse_staff()`); err != nil { + t.Fatal(err) + } + } + ctx := t.Context() + if kind == "cancel" { + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + cancel() + } + var out bytes.Buffer + if err := staffUserCommand(ctx, []string{"add", "--admin", "--username", "staff"}, strings.NewReader(staffCredentials()), &out); err == nil || out.Len() != 0 { + t.Fatal("failed staff creation returned credentials") + } + var n int + if err := st.DB().QueryRow(`SELECT count(*) FROM users WHERE username='staff'`).Scan(&n); err != nil || n != 0 { + t.Fatal("failed creation left an account") + } + }) + } +} diff --git a/docs/ASSURANCE-CASE.md b/docs/ASSURANCE-CASE.md index 51931b09..b983fe7c 100644 --- a/docs/ASSURANCE-CASE.md +++ b/docs/ASSURANCE-CASE.md @@ -210,3 +210,11 @@ multiline/empty refusal and secret-safe errors/formatting. Construction writes n settings or local store and does not enable startup. Actual delayed PUT completion after a lost PG lock remains unqualified; neither a canceled context nor the published wire API is erasure proof. Runtime/GC/purge/provider and native-PG recovery gates remain explicit. + +Host maintenance uses the exact existing PG schema and recorded staff org/region, with no +migration or local-key fallback. Tests require atomic account/audit creation, real password +verification and wrong-proof refusal, bounded secret input and redacted errors, and one-create +bootstrap across independent pools. Explicit config acceptance derives the complete application +field map; tests preserve the retained encryption key and fixed install bindings, roll back on +audit failure and verify the ordinary multi startup gate remains closed. Operator acknowledgement +that every replica is stopped is a maintenance precondition, not an automatic liveness proof. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 0e4dea15..6703dc9a 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -335,3 +335,47 @@ longer to the per-address rate. `X-Forwarded-Proto` and `X-Forwarded-Host` follow the same rule: KyNotes reads them, last value first, only from a trusted proxy. They shape the SSO callback and KySignOn pairing URL when none is configured, and the SSO state cookie's `Secure` flag. + + +## Offline host maintenance preparation + +Hosted startup remains unavailable. These commands operate only on an already initialized, +exact-release PostgreSQL schema for tenancy rehearsals; they do not initialize a hosted install, +recover backup bytes or make it ready to serve. Keep every deployment/recovery key unchanged. +Standalone commands and startup retain their existing behavior. + +### Create a dedicated staff administrator + +Set `KYNOTES_TENANCY=multi`, `KYNOTES_DB_DSN`, `KYNOTES_STAFF_ORG_ID` and `KYNOTES_REGION` +in the host environment, matching the database record. Run `kynotes-server user add --admin +--username ` and supply one JSON object on stdin with `authSecret` (64 lowercase hex +characters), `loginSalt` (16–64 bytes in standard base64), and `iterations` (600000–1000000, +or omitted for 600000). Use the same password derivation as the existing single-mode stdin +workflow. Do not put the proof, DSN or password in argv or shell history. Multi mode refuses +`--password`, `--everyday` and customer creation. Save the recovery code printed after the +account and platform audit commit. On an output failure the account already exists; retain +the input credentials rather than blindly repeating creation. A dedicated administrator +cannot open notes and must change the operator-known password at first sign-in. + +Bootstrap preparation likewise places only an administrator in the recorded staff org; two +replicas seed at most one account. Multi bootstrap refuses both everyday-account variables. +This routine remains behind the unavailable hosted startup path. + +### Accept deliberate shared-setting changes + +1. Stop every replica and keep PostgreSQL running. This acknowledgement is the operator's + responsibility; the command cannot prove that no replica is serving. +2. Preserve the server-salt key that encrypts the sealed recovery token. Mode, staff org and + region cannot change. Distribute the intended new settings to every replica. +3. With the same deployment file and all shared replica environment settings, run + `kynotes-server accept-replica-config --confirm-stopped --config ` once. The command + requires environment pairing/salt/SSO/VAPID keys and object-store metadata, loads the full + app-owned field map without minting keys, and refuses the single-mode append-only mirror. + Object credentials are outside the fingerprint; no object request is made here. +4. Check success and the platform `admin.replica_config_accepted` event (changed names only). + An audit failure leaves the fingerprint unchanged. A replica retaining old settings will + refuse the next startup comparison. Normal hosted startup is still refused until every + object-store, native-recovery and end-to-end launch prerequisite is satisfied. + +No maintenance command selects the unresolved native PostgreSQL backup transport or changes +its retention/drill readiness. See the [restore runbook](RESTORE.md) for restored-target safety. diff --git a/docs/STRONG-CRYPTO.md b/docs/STRONG-CRYPTO.md index d2e7f0f8..43ed36be 100644 --- a/docs/STRONG-CRYPTO.md +++ b/docs/STRONG-CRYPTO.md @@ -28,6 +28,7 @@ delete accounts. Nothing in this guide rewrites a stored key. | Device linking | X25519, HKDF-SHA256, ChaCha20-Poly1305, SHA-256 commitments | Fixed suite. | | Browser vault key | Non-extractable AES-256-GCM generated in the browser | Not imported. | | Passwords and recovery codes on the server | Argon2id (`ky-primitives/password`) over a 256-bit derived login secret | scrypt verifiers are refused. | +| Hosted maintenance credentials and fingerprint | Same Argon2id and HMAC-SHA256 mechanisms as account creation and replica startup | Bounded stdin accepts exactly a 256-bit derived proof, standard-base64 salt of 16–64 bytes and 600000–1000000 iterations. Environment pairing/salt keys remain at least 32 bytes; configuration acceptance refuses a changed retained encryption key. | | Deployment secrets (`pairing.key`, `serversalt.key`) | 32 random bytes | A file that does not decode to exactly 32 bytes is a startup error and is never replaced; `KYNOTES_SECRETS_*` values below 32 bytes are refused. | | Web push (VAPID) | P-256 ES256 key in `secrets/vapid.key` | Fixed curve. Pushes carry no payload, so subscription keys are neither used nor kept. | | OIDC ID tokens and back-channel logout tokens | RS256 only, verified by `ky-primitives/oidcverify` against the provider's JWKS | Login and logout use the same verifier type: a JWKS RSA key below 2048 bits is never used, so a token it signed is refused. Issuer, authorization, token and JWKS URLs must be HTTPS without credentials; discovery, token and JWKS redirects are refused. | diff --git a/docs/src/reference.md b/docs/src/reference.md index 32bcddf3..ed3842a5 100644 --- a/docs/src/reference.md +++ b/docs/src/reference.md @@ -21,6 +21,8 @@ The links below open repository documents and need network access. - [Notebook export](https://github.com/Busnes-app/KyNotes-server/blob/master/docs/EXPORT.md) - [cleanup capacity and upgrade](https://github.com/Busnes-app/KyNotes-server/blob/master/docs/CLEANUP-CAPACITY.md) +- [Offline host maintenance preparation](https://github.com/Busnes-app/KyNotes-server/blob/master/docs/DEPLOYMENT.md#offline-host-maintenance-preparation): staff accounts and explicit stopped-replica config acceptance, without hosted startup. + ## Privacy and vulnerability reports Read [SECURITY.md](https://github.com/Busnes-app/KyNotes-server/blob/master/SECURITY.md) for this product's security model, diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index 43b7fc0b..b3a99cdd 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1570,7 +1570,7 @@ client, volume fallback, automatic pruning or hosted/native-backup readiness is The object preparation consumes the shared client's encoded-byte GET correction: identity encoding preserves opaque gzip-labelled bytes and GET/HEAD size agreement. A regression fails against the earlier published client and passes after the upstream correction. This does not -make the separately published but unmerged conditional-PUT/timestamp follow-up a merged dependency. +make the separately merged conditional-PUT/timestamp follow-up part of the consumed dependency. ### PR 5b-2 as built: credential/client preparation (startup still refused) @@ -1583,8 +1583,26 @@ network or database I/O and is not called by ordinary startup or maintenance loa Tests cover direct/file/mixed sources, ambiguity/empty/size/multiline/path/type refusal, secret-safe errors/formatting, shared-field separation and unchanged startup refusals. -Base #77 is merged and pinned to79823f9; published #78 remains unmerged/not consumed. Before +Base #77 is merged and pinned to79823f9; #78 is merged asb55ca6d but is not consumed. Before complete GC/purge/runtime binding, Notes must select and qualify delayed remote-PUT fate after PG-lock loss; cancellation alone is no completion proof. Shared conditional operations do not select a Notes ledger/protocol. Keep this and native-PG recovery open question3 as explicit remaining gates, alongside store controls/age/provider proof and lifecycle E2E. + + +### Phase 6 host maintenance as built (startup still refused) + +Multi-mode `user add --admin` uses bounded stdin derived credentials and an exact existing PG +schema, refusing customer/everyday creation and password/DSN argv. Recorded staff-org/region +checks and an in-transaction binding recheck precede atomic account/platform-audit creation; +the recovery code is emitted only after commit. Staff bootstrap preparation is staff-only, +audited and serialized across independent pools, with password work outside N3. Everyday +bootstrap variables refuse; single-mode paths remain unchanged. + +`accept-replica-config --confirm-stopped` reads deployment configuration without local-key +fallback/minting and uses the full existing app field map. The retained salt/encryption key +and fixed mode/staff/region cannot change. Fingerprint and changed-name audit commit together; +a failed audit leaves the old fingerprint. Ordinary startup/config loaders still refuse multi. +Tests cover both backends where applicable, actual PG target/schema/audit/input boundaries, +real password checks, concurrent bootstrap and unchanged single-account workflows. Maintenance +preparation does not choose PG backup transport or enable object/runtime/hosted startup. diff --git a/internal/app/bootstrap.go b/internal/app/bootstrap.go index 0402e9e3..4547276e 100644 --- a/internal/app/bootstrap.go +++ b/internal/app/bootstrap.go @@ -12,6 +12,7 @@ import ( "github.com/Busnes-app/kynotes-server/internal/config" "github.com/Busnes-app/kynotes-server/internal/ids" "github.com/Busnes-app/kynotes-server/internal/logging" + "github.com/Busnes-app/kynotes-server/internal/storage" ) // EnsureBootstrapAdmin seeds an empty database from the environment: BOOTSTRAP_ADMIN_PASS (and @@ -21,6 +22,13 @@ import ( // passwords, so both accounts are flagged (password_admin_known) and change them at first sign-in. // Without BOOTSTRAP_ADMIN_PASS the database stays empty and the web setup creates both accounts. func EnsureBootstrapAdmin(db *sql.DB, c config.Config) error { + tenancy, err := storage.TenancyOf(db) + if err != nil { + return err + } + if tenancy.Multi() { + return ensureStaffBootstrap(db, c, tenancy) + } var count int if err := db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&count); err != nil { return err @@ -86,7 +94,7 @@ func EnsureBootstrapAdmin(db *sql.DB, c config.Config) error { // closed; the CLI creates one. role='admin' implies an admin account (0026 triggers). func WarnWithoutAdmin(db *sql.DB, log *logging.Logger) bool { var users, admins int - if db.QueryRow(`SELECT COUNT(*), COUNT(*) FILTER (WHERE role='admin' AND status='active') FROM users`).Scan(&users, &admins) != nil || users == 0 || admins > 0 { + if db.QueryRow(`SELECT COUNT(*), COUNT(*) FILTER (WHERE role='admin' AND status='active' AND (COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')<>'multi' OR org_id=(SELECT value FROM server_settings WHERE key='staff_org_id'))) FROM users`).Scan(&users, &admins) != nil || users == 0 || admins > 0 { return false } // The remedy is in the message: the logger drops every attribute key outside its allowlist. diff --git a/internal/app/replica_accept.go b/internal/app/replica_accept.go new file mode 100644 index 00000000..90c7f52c --- /dev/null +++ b/internal/app/replica_accept.go @@ -0,0 +1,32 @@ +package app + +import ( + "context" + "errors" + + "github.com/Busnes-app/kynotes-server/internal/config" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +// AcceptReplicaConfiguration is host-only maintenance after every replica has stopped. +// It loads the same full field map used by startup preparation, never an operator-made map. +func AcceptReplicaConfiguration(ctx context.Context, path string) error { + c, err := config.LoadReplicaMaintenance(path) + if err != nil { + return errors.New("replicas: configuration unavailable; check the deployment file and environment") + } + c, in, err := readReplicaInputs(c) + if err != nil { + return err + } + store, err := storage.OpenPostgresCurrent(ctx, in.DSN) + if err != nil { + return errors.New("replicas: cannot open the exact existing PostgreSQL schema") + } + defer store.Close() + current, err := storage.TenancyOfContext(ctx, store.DB()) + if err != nil || current != in.Tenancy { + return errors.New("replicas: recorded install binding differs") + } + return storage.AcceptReplicaConfig(ctx, store.DB(), c.Secrets.ServerSaltKey, replicaFields(c, in)) +} diff --git a/internal/app/replica_accept_test.go b/internal/app/replica_accept_test.go new file mode 100644 index 00000000..79079e43 --- /dev/null +++ b/internal/app/replica_accept_test.go @@ -0,0 +1,176 @@ +package app + +import ( + "bytes" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/Busnes-app/kynotes-server/internal/auth" + "github.com/Busnes-app/kynotes-server/internal/config" + "github.com/Busnes-app/kynotes-server/internal/logging" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +func replicaMaintenanceTarget(t *testing.T) (*storage.Store, string) { + t.Helper() + if !storage.OnPostgresTest() { + t.Skip("native PostgreSQL maintenance") + } + st, err := storage.Open(filepath.Join(t.TempDir(), "target.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + for _, q := range []string{`UPDATE server_settings SET value='multi' WHERE key='tenancy_mode'`, `INSERT INTO orgs(id,status,home_region) VALUES('org_staff','active','eu')`, `INSERT INTO server_settings(key,value,updated_at) VALUES('staff_org_id','org_staff','t'),('region','eu','t')`} { + if _, err := st.DB().Exec(q); err != nil { + t.Fatal(err) + } + } + var schema string + if err := st.DB().QueryRow(`SELECT current_schema()`).Scan(&schema); err != nil { + t.Fatal(err) + } + dsn, err := url.Parse(os.Getenv("KYNOTES_TEST_DATABASE_URL")) + if err != nil { + t.Fatal(err) + } + query := dsn.Query() + query.Set("search_path", schema) + dsn.RawQuery = query.Encode() + replicaEnvironment(t) + t.Setenv("KYNOTES_DB_DSN", dsn.String()) + t.Setenv("KYNOTES_TENANCY", "multi") + t.Setenv("KYNOTES_SERVER_BIND", "127.0.0.1:8080") + t.Setenv("KYNOTES_SERVER_DEV_INSECURE_COOKIES", "true") + dir := t.TempDir() + t.Setenv("KYNOTES_DATA_DIR", dir) + return st, filepath.Join(dir, "config.yaml") +} + +func TestReplicaMaintenanceUsesFullFingerprintAndRetainedKey(t *testing.T) { + st, path := replicaMaintenanceTarget(t) + c, err := config.LoadReplicaMaintenance(path) + if err != nil { + t.Fatal(err) + } + c, in, err := readReplicaInputs(c) + if err != nil { + t.Fatal(err) + } + if err := storage.VerifyReplicaConfig(t.Context(), st.DB(), c.Secrets.ServerSaltKey, replicaFields(c, in)); err != nil { + t.Fatal(err) + } + t.Setenv("KYNOTES_SSO_CLIENT_SECRET", "new-private-client-secret") + if err := AcceptReplicaConfiguration(t.Context(), path); err != nil { + t.Fatal(err) + } + c, in, err = readReplicaInputs(c) + if err != nil { + t.Fatal(err) + } + if err := storage.VerifyReplicaConfig(t.Context(), st.DB(), c.Secrets.ServerSaltKey, replicaFields(c, in)); err != nil { + t.Fatal(err) + } + var reason string + if err := st.DB().QueryRow(`SELECT reason_code FROM audit_events WHERE event='admin.replica_config_accepted'`).Scan(&reason); err != nil || reason != "fields=sso" { + t.Fatalf("audit %q %v", reason, err) + } + t.Setenv("KYNOTES_SECRETS_SERVER_SALT_KEY", strings.Repeat("z", 32)) + if err := AcceptReplicaConfiguration(t.Context(), path); err == nil { + t.Fatal("retained encryption key rotated") + } + t.Setenv("KYNOTES_SECRETS_SERVER_SALT_KEY", c.Secrets.ServerSaltKey) + t.Setenv("KYNOTES_STAFF_ORG_ID", "org_customer") + if err := AcceptReplicaConfiguration(t.Context(), path); err == nil { + t.Fatal("wrong recorded target accepted") + } + if err := storage.VerifyReplicaConfig(t.Context(), st.DB(), c.Secrets.ServerSaltKey, replicaFields(c, in)); err != nil { + t.Fatal("refusal changed fingerprint", err) + } + if _, err := config.Load(path); err == nil { + t.Fatal("maintenance enabled hosted startup") + } +} + +func TestStaffBootstrapIsAuditedStaffOnlyAndConcurrentSafe(t *testing.T) { + st, _ := replicaMaintenanceTarget(t) + t.Setenv("BOOTSTRAP_ADMIN_USER", " Operator ") + t.Setenv("BOOTSTRAP_ADMIN_PASS", "staff bootstrap actual password") + t.Setenv("BOOTSTRAP_EVERYDAY_USER", "") + t.Setenv("BOOTSTRAP_EVERYDAY_PASS", "") + c := config.Defaults() + c.Secrets.ServerSaltKey = strings.Repeat("s", 32) + other, err := storage.OpenPostgresCurrent(t.Context(), os.Getenv("KYNOTES_DB_DSN")) + if err != nil { + t.Fatal(err) + } + defer other.Close() + var wg sync.WaitGroup + outcomes := make(chan error, 2) + for _, db := range []*storage.Store{st, other} { + wg.Go(func() { outcomes <- EnsureBootstrapAdmin(db.DB(), c) }) + } + wg.Wait() + close(outcomes) + for err := range outcomes { + if err != nil { + t.Fatal(err) + } + } + var org, kind, hash, salt string + var n, iterations, known int + if err := st.DB().QueryRow(`SELECT org_id,account_kind,auth_secret_hash,login_salt,login_iterations,password_admin_known FROM users WHERE username='operator'`).Scan(&org, &kind, &hash, &salt, &iterations, &known); err != nil { + t.Fatal(err) + } + if org != "org_staff" || kind != "admin" || known != 1 { + t.Fatal("bootstrap granted an everyday/customer account") + } + proof, err := auth.DeriveAuthSecret("staff bootstrap actual password", salt, iterations) + if err != nil || auth.VerifyAuthSecret(proof, hash) != nil { + t.Fatal("real password verification failed", err) + } + if err := auth.VerifyAuthSecret(strings.Repeat("b", 64), hash); err == nil { + t.Fatal("wrong proof matched") + } + if err := st.DB().QueryRow(`SELECT count(*) FROM users`).Scan(&n); err != nil || n != 1 { + t.Fatal("multiple replicas seeded twice", n, err) + } + if err := st.DB().QueryRow(`SELECT count(*) FROM audit_events WHERE event='admin.user.create' AND org_id IS NULL AND reason_code='kind=admin,source=bootstrap'`).Scan(&n); err != nil || n != 1 { + t.Fatal("bootstrap audit", n, err) + } + t.Setenv("BOOTSTRAP_EVERYDAY_USER", "customer") + if err := EnsureBootstrapAdmin(st.DB(), c); err == nil { + t.Fatal("multi everyday bootstrap accepted") + } +} + +func TestStaffBootstrapAuditFailureAndCustomerAdminDoNotGrantStaff(t *testing.T) { + st, _ := replicaMaintenanceTarget(t) + t.Setenv("BOOTSTRAP_ADMIN_PASS", "staff bootstrap actual password") + t.Setenv("BOOTSTRAP_ADMIN_USER", "operator") + t.Setenv("BOOTSTRAP_EVERYDAY_USER", "") + t.Setenv("BOOTSTRAP_EVERYDAY_PASS", "") + if _, err := st.DB().Exec(`INSERT INTO users(id,username,auth_secret_hash,login_salt,login_iterations,role,account_kind,status,created_at,updated_at) VALUES('usr_customer_admin','customer-admin','','',600000,'admin','admin','active','t','t')`); err != nil { + t.Fatal(err) + } + var output bytes.Buffer + if !WarnWithoutAdmin(st.DB(), logging.New(&output, "info", "json")) { + t.Fatal("customer administrator masked missing staff") + } + if _, err := st.DB().Exec(`CREATE FUNCTION refuse_bootstrap() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.event='admin.user.create' THEN RAISE EXCEPTION 'test audit unavailable'; END IF; RETURN NEW; END $$; CREATE TRIGGER refuse_bootstrap BEFORE INSERT ON audit_events FOR EACH ROW EXECUTE FUNCTION refuse_bootstrap()`); err != nil { + t.Fatal(err) + } + c := config.Defaults() + c.Secrets.ServerSaltKey = strings.Repeat("s", 32) + if err := EnsureBootstrapAdmin(st.DB(), c); err == nil { + t.Fatal("unaudited bootstrap succeeded") + } + var n int + if err := st.DB().QueryRow(`SELECT count(*) FROM users WHERE org_id='org_staff'`).Scan(&n); err != nil || n != 0 { + t.Fatal("failed audit left administrator", n, err) + } +} diff --git a/internal/app/staff_bootstrap.go b/internal/app/staff_bootstrap.go new file mode 100644 index 00000000..6b903830 --- /dev/null +++ b/internal/app/staff_bootstrap.go @@ -0,0 +1,87 @@ +package app + +import ( + "database/sql" + "errors" + "fmt" + "os" + "strings" + "time" + "unicode" + + "github.com/Busnes-app/kynotes-server/internal/auth" + "github.com/Busnes-app/kynotes-server/internal/config" + "github.com/Busnes-app/kynotes-server/internal/ids" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +func ensureStaffBootstrap(db *sql.DB, c config.Config, tenancy storage.Tenancy) error { + if !storage.IsPostgres(db) || tenancy.StaffOrg == "" || tenancy.Region == "" { + return errors.New("staff bootstrap requires recorded multi PostgreSQL bindings") + } + if os.Getenv("BOOTSTRAP_EVERYDAY_USER") != "" || os.Getenv("BOOTSTRAP_EVERYDAY_PASS") != "" { + return errors.New("multi mode refuses BOOTSTRAP_EVERYDAY_USER and BOOTSTRAP_EVERYDAY_PASS; customer accounts come from KyIdentity") + } + password := os.Getenv("BOOTSTRAP_ADMIN_PASS") + if password == "" { + return nil + } + var count int + if err := db.QueryRow(`SELECT count(*) FROM users WHERE org_id=?`, tenancy.StaffOrg).Scan(&count); err != nil { + return err + } + if count > 0 { + return nil + } + username := strings.ToLower(strings.TrimSpace(os.Getenv("BOOTSTRAP_ADMIN_USER"))) + if username == "" { + username = "admin" + } + if len(username) > 128 || strings.IndexFunc(username, unicode.IsControl) >= 0 { + return errors.New("BOOTSTRAP_ADMIN_USER is invalid") + } + salt := auth.SyntheticLoginSalt(c.Secrets.ServerSaltKey, username) + proof, err := auth.DeriveAuthSecret(password, salt, auth.LoginIterations) + if err != nil { + return err + } + hash, err := auth.HashAuthSecret(proof) + if err != nil { + return err + } + id, err := ids.Mint("usr") + if err != nil { + return err + } + now := time.Now().UTC().Format(time.RFC3339) + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + current, err := storage.TenancyOf(tx) + if err != nil { + return err + } + if current != tenancy { + return errors.New("staff bootstrap target changed") + } + // N3 serializes this recheck across replicas; password work occurs before taking it. + if err := tx.QueryRow(`SELECT count(*) FROM users WHERE org_id=?`, tenancy.StaffOrg).Scan(&count); err != nil { + return err + } + if count > 0 { + return nil + } + if _, err := tx.Exec(`INSERT INTO users(id,username,auth_secret_hash,login_salt,login_iterations,role,account_kind,status,password_admin_known,created_at,updated_at,org_id) VALUES(?,?,?,?,?,'admin','admin','active',1,?,?,?)`, id, username, hash, salt, auth.LoginIterations, now, now, tenancy.StaffOrg); err != nil { + return err + } + if err := storage.RecordAuditOutcomeTx(tx, "", "admin.user.create", "", id, "success", "kind=admin,source=bootstrap", "staff-bootstrap"); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + fmt.Printf("Initial staff administrator account created for '%s' from BOOTSTRAP_ADMIN_PASS.\n", username) + return nil +} diff --git a/internal/config/config.go b/internal/config/config.go index 8388ea21..0524c665 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -120,6 +120,14 @@ func DataDir(path string) (string, error) { } func parse(path string) (Config, error) { + c, err := parseFile(path) + if err != nil { + return c, err + } + return c, applyEnv(&c) +} + +func parseFile(path string) (Config, error) { c := Defaults() if path != "" { b, err := os.ReadFile(path) @@ -132,7 +140,7 @@ func parse(path string) (Config, error) { } } } - return c, applyEnv(&c) + return c, nil } func loadMode(path string, probe, createSecrets bool) (Config, error) { @@ -204,6 +212,10 @@ func applyEnv(c *Config) error { if err := tenancyEnv(); err != nil { return err } + return applyEnvValues(c) +} + +func applyEnvValues(c *Config) error { applyBlobEnv(&c.Backup.BlobTarget) if v := os.Getenv("KYNOTES_PORT"); v != "" { c.Server.Bind = "0.0.0.0:" + v diff --git a/internal/config/replica_maintenance.go b/internal/config/replica_maintenance.go new file mode 100644 index 00000000..0063accb --- /dev/null +++ b/internal/config/replica_maintenance.go @@ -0,0 +1,30 @@ +package config + +import ( + "errors" + "os" +) + +// LoadReplicaMaintenance reads configuration for explicit offline fingerprint acceptance. +// It never mints or reads local keys. Normal startup loaders retain their multi refusal. +func LoadReplicaMaintenance(path string) (Config, error) { + if os.Getenv("KYNOTES_TENANCY") != "multi" { + return Config{}, errors.New("replica maintenance requires KYNOTES_TENANCY=multi") + } + c, err := parseFile(path) + if err != nil { + return c, err + } + if err := applyEnvValues(&c); err != nil { + return c, err + } + c.Secrets.PairingSecret = os.Getenv("KYNOTES_SECRETS_PAIRING_SECRET") + c.Secrets.ServerSaltKey = os.Getenv("KYNOTES_SECRETS_SERVER_SALT_KEY") + if len(c.Secrets.PairingSecret) < 32 || len(c.Secrets.ServerSaltKey) < 32 { + return c, errors.New("replica maintenance requires retained pairing and server-salt keys in environment") + } + if c.Backup.BlobTarget.URL != "" { + return c, errors.New("replica maintenance refuses the single-mode offsite mirror") + } + return c, validate(c, false) +} diff --git a/internal/config/replica_maintenance_test.go b/internal/config/replica_maintenance_test.go new file mode 100644 index 00000000..20cd0108 --- /dev/null +++ b/internal/config/replica_maintenance_test.go @@ -0,0 +1,50 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestReplicaMaintenanceReadsEnvironmentWithoutMintingOrEnablingStartup(t *testing.T) { + t.Setenv("KYNOTES_SERVER_BIND", "127.0.0.1:8080") + t.Setenv("KYNOTES_SERVER_DEV_INSECURE_COOKIES", "true") + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + raw := "data_dir: " + dir + "\nratelimit:\n login_per_minute: 19\nsecrets:\n pairing_secret: " + strings.Repeat("x", 32) + "\n server_salt_key: " + strings.Repeat("y", 32) + "\n" + if err := os.WriteFile(path, []byte(raw), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("KYNOTES_TENANCY", "single") + if _, err := LoadReplicaMaintenance(path); err == nil { + t.Fatal("single maintenance accepted") + } + t.Setenv("KYNOTES_TENANCY", "multi") + t.Setenv("KYNOTES_SECRETS_PAIRING_SECRET", "") + t.Setenv("KYNOTES_SECRETS_SERVER_SALT_KEY", "") + if _, err := LoadReplicaMaintenance(path); err == nil { + t.Fatal("file keys used as environment fallback") + } + t.Setenv("KYNOTES_SECRETS_PAIRING_SECRET", strings.Repeat("p", 32)) + t.Setenv("KYNOTES_SECRETS_SERVER_SALT_KEY", strings.Repeat("s", 32)) + c, err := LoadReplicaMaintenance(path) + if err != nil || c.RateLimit.LoginPerMinute != 19 || c.Secrets.PairingSecret != strings.Repeat("p", 32) { + t.Fatalf("maintenance config: %+v %v", c.RateLimit, err) + } + files, err := os.ReadDir(dir) + if err != nil || len(files) != 1 || files[0].Name() != "config.yaml" { + t.Fatal("maintenance wrote local state", err) + } + for _, load := range []func(string) (Config, error){Load, LoadExisting} { + if _, err := load(path); err == nil { + t.Fatal("maintenance lifted ordinary startup refusal") + } + } + if err := os.WriteFile(path, []byte(raw+"backup:\n blob_target:\n url: s3://bucket\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err := LoadReplicaMaintenance(path); err == nil { + t.Fatal("multi accepted append-only single-mode mirror") + } +} diff --git a/internal/storage/replica_accept.go b/internal/storage/replica_accept.go new file mode 100644 index 00000000..384ce0f0 --- /dev/null +++ b/internal/storage/replica_accept.go @@ -0,0 +1,80 @@ +package storage + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "sort" + "strings" + "time" +) + +// AcceptReplicaConfig is preparation for explicit offline configuration acceptance, never an +// automatic mismatch fallback. The host caller must stop every replica first. Immutable +// install bindings and the retained salt/encryption key cannot be changed through this path. +func AcceptReplicaConfig(ctx context.Context, db *sql.DB, key string, fields map[string]string) error { + tenancy, err := TenancyOfContext(ctx, db) + if err != nil { + return err + } + if !IsPostgres(db) || !tenancy.Multi() { + return errors.New("replicas: configuration acceptance requires multi PostgreSQL") + } + want := replicaFingerprint(key, fields) + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + current, err := TenancyOfContext(ctx, tx) + if err != nil { + return err + } + if current != tenancy { + return errors.New("replicas: install binding changed during acceptance") + } + var raw string + if err := tx.QueryRowContext(ctx, `SELECT value FROM server_settings WHERE key='replica_config_fingerprint'`).Scan(&raw); err != nil { + return errors.New("replicas: no usable stored configuration to accept") + } + var got map[string]string + if json.Unmarshal([]byte(raw), &got) != nil || got["$key"] != want["$key"] { + return errors.New("replicas: retained server salt key is required") + } + for _, name := range []string{"tenancy_mode", "staff_org_id", "region"} { + if got[name] != want[name] { + return errors.New("replicas: immutable install binding differs: " + name) + } + } + changed := map[string]bool{} + for name, value := range want { + if got[name] != value { + changed[name] = true + } + } + for name := range got { + if _, ok := want[name]; !ok { + changed[name] = true + } + } + if len(changed) == 0 { + return nil + } + names := make([]string, 0, len(changed)) + for name := range changed { + names = append(names, name) + } + sort.Strings(names) + encoded, err := json.Marshal(want) + if err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `UPDATE server_settings SET value=?,updated_at=? WHERE key='replica_config_fingerprint'`, string(encoded), time.Now().UTC().Format(time.RFC3339)); err != nil { + return err + } + if err := RecordAuditOutcomeTx(tx, "", "admin.replica_config_accepted", "", "", "success", "fields="+strings.Join(names, ","), "replica-config"); err != nil { + return err + } + return tx.Commit() +} diff --git a/internal/storage/replica_accept_test.go b/internal/storage/replica_accept_test.go new file mode 100644 index 00000000..d9650b04 --- /dev/null +++ b/internal/storage/replica_accept_test.go @@ -0,0 +1,68 @@ +package storage + +import ( + "path/filepath" + "strings" + "testing" +) + +func TestReplicaAcceptKeepsBindingsKeyAndAuditsNamesOnly(t *testing.T) { + a, b := sharedReplicas(t) + key := strings.Repeat("k", 32) + fields := map[string]string{"tenancy_mode": "multi", "staff_org_id": "org_staff", "region": "local", "sso": "old-private-secret"} + if err := VerifyReplicaConfig(t.Context(), a, key, fields); err != nil { + t.Fatal(err) + } + changed := map[string]string{"tenancy_mode": "multi", "staff_org_id": "org_staff", "region": "local", "sso": "new-private-secret"} + if err := AcceptReplicaConfig(t.Context(), a, key, changed); err != nil { + t.Fatal(err) + } + if err := VerifyReplicaConfig(t.Context(), b, key, changed); err != nil { + t.Fatal(err) + } + var reason string + if err := a.QueryRow(`SELECT reason_code FROM audit_events WHERE event='admin.replica_config_accepted'`).Scan(&reason); err != nil || reason != "fields=sso" { + t.Fatalf("accept audit %q %v", reason, err) + } + for _, kind := range []string{"key", "tenancy_mode", "staff_org_id", "region"} { + next := map[string]string{} + for name, value := range changed { + next[name] = value + } + candidate := key + if kind == "key" { + candidate = strings.Repeat("q", 32) + } else { + next[kind] = "different" + } + if err := AcceptReplicaConfig(t.Context(), a, candidate, next); err == nil { + t.Fatalf("accepted changed %s", kind) + } + if err := VerifyReplicaConfig(t.Context(), b, key, changed); err != nil { + t.Fatal("refusal changed fingerprint") + } + } + if _, err := a.Exec(`CREATE FUNCTION deny_accept() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.event='admin.replica_config_accepted' THEN RAISE EXCEPTION 'test audit unavailable'; END IF; RETURN NEW; END $$; CREATE TRIGGER deny_accept BEFORE INSERT ON audit_events FOR EACH ROW EXECUTE FUNCTION deny_accept()`); err != nil { + t.Fatal(err) + } + if err := AcceptReplicaConfig(t.Context(), a, key, fields); err == nil { + t.Fatal("unaudited config acceptance succeeded") + } + if err := VerifyReplicaConfig(t.Context(), b, key, changed); err != nil { + t.Fatal("failed audit changed config") + } +} +func TestReplicaAcceptRefusesSingleModeWithoutWrites(t *testing.T) { + st, err := openSQLite(filepath.Join(t.TempDir(), "single.db"), true) + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := AcceptReplicaConfig(t.Context(), st.DB(), strings.Repeat("k", 32), map[string]string{}); err == nil { + t.Fatal("single config accepted") + } + var n int + if err := st.DB().QueryRow(`SELECT count(*) FROM server_settings WHERE key='replica_config_fingerprint'`).Scan(&n); err != nil || n != 0 { + t.Fatal("single config record written") + } +} diff --git a/internal/storage/replica_config.go b/internal/storage/replica_config.go index be46320f..8a7dfad5 100644 --- a/internal/storage/replica_config.go +++ b/internal/storage/replica_config.go @@ -21,16 +21,7 @@ func VerifyReplicaConfig(ctx context.Context, db *sql.DB, key string, fields map if err != nil || !shared { return err } - digest := func(name, value string) string { - h := hmac.New(sha256.New, []byte(key)) - h.Write([]byte("kynotes/replica-config/v1\x00" + name + "\x00" + value)) - return hex.EncodeToString(h.Sum(nil)) - } - want := make(map[string]string, len(fields)+1) - for name, value := range fields { - want[name] = digest(name, value) - } - want["$key"] = digest("$key", key) + want := replicaFingerprint(key, fields) encoded, err := json.Marshal(want) if err != nil { return err @@ -75,3 +66,17 @@ func VerifyReplicaConfig(ctx context.Context, db *sql.DB, key string, fields map } return tx.Commit() } + +func replicaFingerprint(key string, fields map[string]string) map[string]string { + digest := func(name, value string) string { + h := hmac.New(sha256.New, []byte(key)) + h.Write([]byte("kynotes/replica-config/v1\x00" + name + "\x00" + value)) + return hex.EncodeToString(h.Sum(nil)) + } + want := make(map[string]string) + for name, value := range fields { + want[name] = digest(name, value) + } + want["$key"] = digest("$key", key) + return want +}