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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
25 changes: 23 additions & 2 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions cmd/kynotes-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -540,6 +546,12 @@ func checkCommand(kind string, args []string) error {
var errUserAddUsage = errors.New("usage: user add --username <name> [--password <pass>] [--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
}
Expand Down
29 changes: 29 additions & 0 deletions cmd/kynotes-server/replica_accept.go
Original file line number Diff line number Diff line change
@@ -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 <path>]; 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
}
18 changes: 18 additions & 0 deletions cmd/kynotes-server/replica_accept_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
123 changes: 123 additions & 0 deletions cmd/kynotes-server/staff_user.go
Original file line number Diff line number Diff line change
@@ -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 <name>; 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
}
Loading