From c5ff0e9a97fcc70ddb54665d408749f5ec8415ef Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Mon, 23 Nov 2026 17:50:53 -0500 Subject: [PATCH 1/3] add: prepare immutable replica SSO settings Keep validated environment settings out of SQL while sharing one-use login state across PostgreSQL pools. Refuse store mutation, prove signed cross-replica callbacks and preserve mutable single-mode settings and the startup gate. Co-Authored-By: GPT 6.1 Sol --- AGENTS.md | 6 ++ DESIGN.md | 10 +++ IMPLEMENTATION_PLAN.md | 11 +++ docs/ASSURANCE-CASE.md | 7 ++ .../specs/2026-11-23-tenancy-design.md | 11 +++ internal/app/replica_config_test.go | 8 ++ internal/httpapi/fixed_sso_test.go | 90 +++++++++++++++++++ internal/sso/fixed_test.go | 40 +++++++++ internal/sso/sso.go | 20 ++++- 9 files changed, 199 insertions(+), 4 deletions(-) create mode 100644 internal/httpapi/fixed_sso_test.go create mode 100644 internal/sso/fixed_test.go diff --git a/AGENTS.md b/AGENTS.md index 3c3cbccf..0afd8208 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -302,6 +302,12 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che Preserve single volume behavior; exclusive marker creation/provider age metadata, GC, provider qualification and hosted startup remain prerequisites. See blobstore's child DOX. +- Fixed multi-mode SSO preparation: pass `readReplicaInputs`' validated `SSO` snapshot to + `sso.NewFixedStore`; it has no DB handle, never reloads persisted settings and rejects Save. + Shared PKCE state still belongs to the route's PG database. No environment client/directory + secret enters settings or pending-state rows. The original `NewStore` stays mutable in single + mode. Verify `TestFixed*`, signed two-pool callback/one-use/wrong-org/settings-mismatch cases, + existing SSO/strong-key tests and golden. Runtime construction/startup remain gated. - 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. diff --git a/DESIGN.md b/DESIGN.md index c5d12b70..5108900d 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1047,3 +1047,13 @@ config loading still refuses multi. Acceptance requires the retained server salt 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. + + +### Fixed environment SSO preparation + +`readReplicaInputs` validates the environment provider and shared keys. `sso.NewFixedStore` +holds that typed snapshot without a database handle: Reload preserves it and Save refuses. +The shared PG PKCE/state adapter remains independent of settings persistence, so a login can +begin on one replica and finish on another without copying client/directory secrets into SQL. +A different deployment snapshot invalidates the one-use state. Single mode keeps the original +mutable store. Production multi construction remains behind the unavailable startup path. diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index ba80f183..d556a732 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -2351,3 +2351,14 @@ Unbuilt: hosted startup/SSO/runtime assembly and complete lifecycle E2E, primary 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. + + +### Phase 6 fixed environment SSO preparation + +Built a fixed store for the existing validated replica SSO snapshot, with no SQL handle or +settings persistence. Reload retains the snapshot, Save refuses, and the original mutable +single store remains unchanged. Signed TLS issuer tests run a login across independent PG +pools without persisted environment secrets, prove one-use/wrong-org/settings-mismatch refusal, +and inspect pending-state bytes. Environment-input and concurrent reload/save tests cover the +adapter contract. Runtime selection of this adapter belongs to final gated multi assembly; +this preparation does not enable startup or complete object/native-PG backup prerequisites. diff --git a/docs/ASSURANCE-CASE.md b/docs/ASSURANCE-CASE.md index b983fe7c..a38509e0 100644 --- a/docs/ASSURANCE-CASE.md +++ b/docs/ASSURANCE-CASE.md @@ -218,3 +218,10 @@ bootstrap across independent pools. Explicit config acceptance derives the compl 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. + + +The fixed environment SSO store has no database handle and refuses Save; concurrent Reload +and Save cannot replace its deployment snapshot. Signed issuer tests across independent PG +pools prove shared one-use login state, wrong-org and changed-settings refusal, and absence of +environment client/directory secrets in settings and PKCE payloads. The normal single store +and hosted startup gate retain their existing contracts; runtime assembly is still unbuilt. diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index b3a99cdd..5549c5cc 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1606,3 +1606,14 @@ a failed audit leaves the old fingerprint. Ordinary startup/config loaders still 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. + + +### Phase 6 fixed environment SSO as built (startup still refused) + +`NewFixedStore` accepts the existing app-validated environment snapshot without a database +handle. Reload preserves it and Save refuses; single mode retains its original mutable store. +PG PKCE state remains route-owned. Actual signed TLS issuer/two-pool tests exercise callback, +one-use, wrong-org and differing-environment refusal without persisting client/directory +secrets. Unit/environment-input tests prove immutable copies and concurrent mutation refusal. +This prepares N5's store adapter; final runtime construction still waits for primary object +storage, native PG recovery and full lifecycle acceptance before startup can be enabled. diff --git a/internal/app/replica_config_test.go b/internal/app/replica_config_test.go index 91a189ec..e44a6890 100644 --- a/internal/app/replica_config_test.go +++ b/internal/app/replica_config_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/Busnes-app/kynotes-server/internal/config" + "github.com/Busnes-app/kynotes-server/internal/sso" ) func replicaEnvironment(t *testing.T) { @@ -35,6 +36,13 @@ func TestReplicaKeysRequireEnvironmentAndCreateNoLocalFiles(t *testing.T) { if !in.Tenancy.Multi() || !in.SSO.AutoProvision || got.Secrets.PairingSecret != strings.Repeat("p", 32) || in.VAPID == nil { t.Fatal("incomplete replica inputs") } + fixed := sso.NewFixedStore(in.SSO) + if fixed.Load() != in.SSO { + t.Fatal("environment snapshot changed") + } + if err := fixed.Save(sso.SSOSettings{}); err != sso.ErrFixedSettings { + t.Fatal("environment snapshot was writable") + } if _, err := os.Stat(c.DataDir); !os.IsNotExist(err) { t.Fatalf("replica key input wrote a local directory: %v", err) } diff --git a/internal/httpapi/fixed_sso_test.go b/internal/httpapi/fixed_sso_test.go new file mode 100644 index 00000000..53f81f08 --- /dev/null +++ b/internal/httpapi/fixed_sso_test.go @@ -0,0 +1,90 @@ +package httpapi + +import ( + "net/http" + "strings" + "testing" + "time" + + "github.com/Busnes-app/kynotes-server/internal/sso" + "github.com/Busnes-app/kynotes-server/internal/storage" +) + +func TestFixedSSOSettingsAuthenticateAcrossPoolsWithoutDatabaseSecrets(t *testing.T) { + if !storage.OnPostgresTest() { + t.Skip("native PostgreSQL shared login state") + } + first := newLogoutFixture(t) + second := &logoutFixture{t: t, db: replicaDB(t, first.db), cfg: first.cfg} + toMultiMode(t, first.db, "org_staff") + for _, org := range []string{storage.DefaultOrgID, "org_other"} { + if _, err := first.db.Exec(`INSERT INTO orgs(id,status,home_region) VALUES(?,'active','local') ON CONFLICT(id) DO NOTHING`, org); err != nil { + t.Fatal(err) + } + } + settings := first.settings.Load() + settings.ClientSecret = "fixed-environment-client-secret" + settings.HMACSecret = strings.Repeat("h", 32) + if _, err := first.db.Exec(`DELETE FROM server_settings WHERE key LIKE 'sso_%'`); err != nil { + t.Fatal(err) + } + install := func(f *logoutFixture, snapshot sso.SSOSettings) { + f.settings = sso.NewFixedStore(snapshot) + mux := http.NewServeMux() + SSORoutes(mux, f.db, f.cfg, f.settings) + f.router = mux + } + install(first, settings) + install(second, settings) + request := func(org string) *http.Request { + req := first.beginLogin("fixed-user", "sid", time.Now()) + state := req.URL.Query().Get("state") + first.mu.Lock() + first.proofs[state]["org_id"] = org + first.mu.Unlock() + return req + } + // Inserting stale settings cannot change either replica's deployment snapshot. + if _, err := first.db.Exec(`INSERT INTO server_settings(key,value,updated_at) VALUES('sso_issuer_url','https://untrusted.example','t')`); err != nil { + t.Fatal(err) + } + if err := second.settings.Reload(); err != nil { + t.Fatal(err) + } + req := request(storage.DefaultOrgID) + if res := second.send(req); res.Code != 302 { + t.Fatalf("fixed cross-pool callback: %d %s", res.Code, res.Body.String()) + } + if res := first.send(req); res.Code != 400 { + t.Fatalf("replayed callback: %d %s", res.Code, res.Body.String()) + } + if res := second.send(request("org_other")); res.Code != 403 || errorCode(t, res.Body.String()) != "org_mismatch" { + t.Fatalf("wrong org: %d %s", res.Code, res.Body.String()) + } + // A differing environment snapshot consumes/refuses the state, even with the same issuer. + req = request(storage.DefaultOrgID) + changed := settings + changed.ClientSecret = "other-environment-secret" + install(second, changed) + if res := second.send(req); res.Code != 400 { + t.Fatalf("changed environment accepted state: %d", res.Code) + } + if res := first.send(req); res.Code != 400 { + t.Fatalf("refused state remained replayable: %d", res.Code) + } + var n int + if err := first.db.QueryRow(`SELECT count(*) FROM server_settings WHERE value IN (?,?)`, settings.ClientSecret, settings.HMACSecret).Scan(&n); err != nil || n != 0 { + t.Fatal("environment secret entered settings", n, err) + } + req = request(storage.DefaultOrgID) + var payload []byte + if err := first.db.QueryRow(`SELECT payload FROM replica_logins WHERE state_hash=?`, storage.StateHash(req.URL.Query().Get("state"))).Scan(&payload); err != nil { + t.Fatal(err) + } + if strings.Contains(string(payload), settings.ClientSecret) || strings.Contains(string(payload), settings.HMACSecret) { + t.Fatal("pending state contains deployment secrets") + } + if err := first.settings.Save(changed); err != sso.ErrFixedSettings { + t.Fatal("fixed settings save succeeded", err) + } +} diff --git a/internal/sso/fixed_test.go b/internal/sso/fixed_test.go new file mode 100644 index 00000000..10a456ae --- /dev/null +++ b/internal/sso/fixed_test.go @@ -0,0 +1,40 @@ +package sso + +import ( + "errors" + "strings" + "sync" + "testing" +) + +func TestFixedSettingsKeepDeploymentSnapshotAcrossReloadAndSave(t *testing.T) { + settings := SSOSettings{Enabled: true, IssuerURL: "https://identity.example", ClientID: "kynotes", ClientSecret: "environment-client-secret", HMACSecret: strings.Repeat("h", 32), AutoProvision: true} + store := NewFixedStore(settings) + settings.ClientSecret = "caller-change" + var work sync.WaitGroup + for range 8 { + work.Go(func() { + if err := store.Reload(); err != nil { + t.Error(err) + } + if err := store.Save(SSOSettings{}); !errors.Is(err, ErrFixedSettings) { + t.Error("fixed settings were writable", err) + } + if got := store.Load(); !got.Enabled || !got.AutoProvision || got.ClientSecret != "environment-client-secret" { + t.Error("snapshot changed") + } + }) + } + work.Wait() + if store.db != nil { + t.Fatal("fixed deployment snapshot holds a database") + } + if strings.Contains(ErrFixedSettings.Error(), "environment-client-secret") { + t.Fatal("refusal disclosed a secret") + } + // The existing in-memory single-mode store remains writable. + ordinary := NewStore(nil) + if err := ordinary.Save(settings); err != nil { + t.Fatal("single-mode memory store changed", err) + } +} diff --git a/internal/sso/sso.go b/internal/sso/sso.go index c0826462..b7fcb0c5 100644 --- a/internal/sso/sso.go +++ b/internal/sso/sso.go @@ -34,7 +34,7 @@ type SSOSettings struct { HMACSecret string `json:"hmacSecret,omitempty"` } -// Store manages SSOSettings loaded and persisted to the SQLite server_settings table. +// Store holds either persisted single-mode settings or a fixed, app-validated deployment snapshot. type Store struct { mu sync.RWMutex discoveryMu sync.Mutex @@ -42,18 +42,26 @@ type Store struct { logoutDiscoveryKey string db *sql.DB cached SSOSettings - inMemory bool + fixed bool verifier *oidcverify.Verifier } -// NewStore initializes a new Store backed by the SQLite database. +// NewStore initializes the mutable settings store backed by the database. func NewStore(db *sql.DB) *Store { s := &Store{db: db} _ = s.Reload() return s } -// Reload re-reads settings from the database. +// NewFixedStore holds validated environment settings without a database handle. Shared login +// transactions remain in the route's database; no client/directory secret is persisted here. +func NewFixedStore(settings SSOSettings) *Store { + return &Store{cached: settings, fixed: true} +} + +var ErrFixedSettings = errors.New("sso: deployment settings are fixed") + +// Reload re-reads persisted settings; fixed and legacy in-memory snapshots stay unchanged. func (s *Store) Reload() error { s.mu.Lock() defer s.mu.Unlock() @@ -99,6 +107,10 @@ func (s *Store) Save(settings SSOSettings) error { s.mu.Lock() defer s.mu.Unlock() + if s.fixed { + return ErrFixedSettings + } + if settings.HMACSecret != "" && settings.HMACSecret != s.cached.HMACSecret && len(settings.HMACSecret) < syncauth.MinKeyBytes { return ErrShortDirectorySecret } From 6d4616a1b2335e2252dac734340569355602b0ac Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Mon, 23 Nov 2026 17:57:09 -0500 Subject: [PATCH 2/3] fix: use fixed SSO snapshots at commit-time admission Require both recorded multi mode and the store-owned immutable marker before replacing mutable SQL configuration checks. Retain all account, org, erasure, logout and replay fences; prove signed directory/logout and single-mode refusal paths. Co-Authored-By: GPT 6.1 Sol --- AGENTS.md | 4 +- DESIGN.md | 6 +++ IMPLEMENTATION_PLAN.md | 6 +++ docs/ASSURANCE-CASE.md | 6 +++ .../specs/2026-11-23-tenancy-design.md | 6 +++ internal/auth/sso_logout.go | 4 +- internal/auth/sso_session.go | 7 ++-- internal/httpapi/fixed_sso_test.go | 41 +++++++++++++++++++ internal/httpapi/sso_directory.go | 8 ++-- internal/httpapi/sso_logout.go | 2 +- internal/httpapi/sso_routes.go | 4 +- internal/sso/sso.go | 4 ++ 12 files changed, 85 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0afd8208..6f08eeed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -304,7 +304,9 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che - Fixed multi-mode SSO preparation: pass `readReplicaInputs`' validated `SSO` snapshot to `sso.NewFixedStore`; it has no DB handle, never reloads persisted settings and rejects Save. - Shared PKCE state still belongs to the route's PG database. No environment client/directory + Shared PKCE state still belongs to the route's PG database. Only recorded multi mode + plus this fixed-store marker uses the immutable snapshot at final login/step-up/logout/ + directory admission; single and mutable stores retain their SQL configuration recheck. No environment client/directory secret enters settings or pending-state rows. The original `NewStore` stays mutable in single mode. Verify `TestFixed*`, signed two-pool callback/one-use/wrong-org/settings-mismatch cases, existing SSO/strong-key tests and golden. Runtime construction/startup remain gated. diff --git a/DESIGN.md b/DESIGN.md index 5108900d..2cbea067 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1057,3 +1057,9 @@ The shared PG PKCE/state adapter remains independent of settings persistence, so begin on one replica and finish on another without copying client/directory secrets into SQL. A different deployment snapshot invalidates the one-use state. Single mode keeps the original mutable store. Production multi construction remains behind the unavailable startup path. + +Final login/step-up, logout and signed-directory admission recognize the immutable snapshot +only when both the store's server-owned fixed marker and recorded multi mode agree. All +account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and +mutable stores retain the database configuration recheck. Signed tests cover fixed directory +signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings. diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index d556a732..50bf239b 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -2362,3 +2362,9 @@ pools without persisted environment secrets, prove one-use/wrong-org/settings-mi and inspect pending-state bytes. Environment-input and concurrent reload/save tests cover the adapter contract. Runtime selection of this adapter belongs to final gated multi assembly; this preparation does not enable startup or complete object/native-PG backup prerequisites. + +Final login/step-up, logout and signed-directory admission recognize the immutable snapshot +only when both the store's server-owned fixed marker and recorded multi mode agree. All +account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and +mutable stores retain the database configuration recheck. Signed tests cover fixed directory +signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings. diff --git a/docs/ASSURANCE-CASE.md b/docs/ASSURANCE-CASE.md index a38509e0..0157135f 100644 --- a/docs/ASSURANCE-CASE.md +++ b/docs/ASSURANCE-CASE.md @@ -225,3 +225,9 @@ and Save cannot replace its deployment snapshot. Signed issuer tests across inde pools prove shared one-use login state, wrong-org and changed-settings refusal, and absence of environment client/directory secrets in settings and PKCE payloads. The normal single store and hosted startup gate retain their existing contracts; runtime assembly is still unbuilt. + +Final login/step-up, logout and signed-directory admission recognize the immutable snapshot +only when both the store's server-owned fixed marker and recorded multi mode agree. All +account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and +mutable stores retain the database configuration recheck. Signed tests cover fixed directory +signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings. diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index 5549c5cc..6c2e7906 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1617,3 +1617,9 @@ one-use, wrong-org and differing-environment refusal without persisting client/d secrets. Unit/environment-input tests prove immutable copies and concurrent mutation refusal. This prepares N5's store adapter; final runtime construction still waits for primary object storage, native PG recovery and full lifecycle acceptance before startup can be enabled. + +Final login/step-up, logout and signed-directory admission recognize the immutable snapshot +only when both the store's server-owned fixed marker and recorded multi mode agree. All +account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and +mutable stores retain the database configuration recheck. Signed tests cover fixed directory +signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings. diff --git a/internal/auth/sso_logout.go b/internal/auth/sso_logout.go index 97e42f7c..b49e65bc 100644 --- a/internal/auth/sso_logout.go +++ b/internal/auth/sso_logout.go @@ -15,7 +15,7 @@ var ErrSSOLogoutRejected = errors.New("invalid or repeated SSO logout") // ApplySSOLogout records replay admission, a fence for callbacks already in flight, // scoped session/device revocation and audit in one writer transaction. -func ApplySSOLogout(ctx context.Context, db *sql.DB, c oidcverify.LogoutClaims, clientID, requestID string) error { +func ApplySSOLogout(ctx context.Context, db *sql.DB, c oidcverify.LogoutClaims, clientID, requestID string, fixedConfiguration bool) error { tx, err := db.BeginTx(ctx, nil) if err != nil { return err @@ -26,7 +26,7 @@ func ApplySSOLogout(ctx context.Context, db *sql.DB, c oidcverify.LogoutClaims, return ErrSSOLogoutRejected } var configured int - if err = tx.QueryRow(`SELECT count(*) FROM server_settings WHERE key='sso_issuer_url' AND value=? AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_client_id' AND value=?)`, c.Issuer, clientID).Scan(&configured); err != nil { + if err = tx.QueryRow(`SELECT CASE WHEN COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')='multi' AND ?=1 THEN 1 ELSE (SELECT count(*) FROM server_settings WHERE key='sso_issuer_url' AND value=? AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_client_id' AND value=?)) END`, fixedConfiguration, c.Issuer, clientID).Scan(&configured); err != nil { return err } if configured != 1 { diff --git a/internal/auth/sso_session.go b/internal/auth/sso_session.go index aaaae876..b37d389e 100644 --- a/internal/auth/sso_session.go +++ b/internal/auth/sso_session.go @@ -20,6 +20,7 @@ type SSOIdentity struct { Issuer, ClientID, Subject, SessionID string IssuedAt, LoginExpires time.Time AppAdmin bool + FixedConfiguration bool // server-owned immutable deployment snapshot, never a token claim ExportOnly bool // the token's export_only claim (tenancy N11) } @@ -65,14 +66,14 @@ func checkSSOIdentityTx(tx *sql.Tx, userID string, identity SSOIdentity, now tim AND (COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')<>'multi' OR NOT EXISTS(SELECT 1 FROM erased_subjects WHERE subject=?)) AND NOT EXISTS(SELECT 1 FROM sso_directory_state WHERE issuer=? AND subject=? AND revoked_before>=?) AND NOT EXISTS(SELECT 1 FROM sso_login_cutoffs WHERE issuer=? AND subject=? AND revoked_before>=?) - AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_enabled' AND value IN ('true','1')) + AND ((COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')='multi' AND ?=1) OR (EXISTS(SELECT 1 FROM server_settings WHERE key='sso_enabled' AND value IN ('true','1')) AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_issuer_url' AND value=?) - AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_client_id' AND value=?) + AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_client_id' AND value=?))) AND NOT EXISTS(SELECT 1 FROM sso_logout_events WHERE issuer=? AND client_id=? AND retain_until>=? AND ((sid<>'' AND sid=? AND (subject='' OR subject=?)) OR (?='' AND subject<>'' AND subject=? AND issued_at>=?) OR (sid='' AND subject=? AND issued_at>=?)))`, - userID, identity.Issuer, identity.Subject, identity.Subject, identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.Issuer, identity.ClientID, identity.Issuer, identity.ClientID, now.Unix(), identity.SessionID, identity.Subject, identity.SessionID, identity.Subject, identity.IssuedAt.Unix(), identity.Subject, identity.IssuedAt.Unix()).Scan(&allowed) + userID, identity.Issuer, identity.Subject, identity.Subject, identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.FixedConfiguration, identity.Issuer, identity.ClientID, identity.Issuer, identity.ClientID, now.Unix(), identity.SessionID, identity.Subject, identity.SessionID, identity.Subject, identity.IssuedAt.Unix(), identity.Subject, identity.IssuedAt.Unix()).Scan(&allowed) if err != nil { return err } diff --git a/internal/httpapi/fixed_sso_test.go b/internal/httpapi/fixed_sso_test.go index 53f81f08..dabc5a1a 100644 --- a/internal/httpapi/fixed_sso_test.go +++ b/internal/httpapi/fixed_sso_test.go @@ -84,7 +84,48 @@ func TestFixedSSOSettingsAuthenticateAcrossPoolsWithoutDatabaseSecrets(t *testin if strings.Contains(string(payload), settings.ClientSecret) || strings.Contains(string(payload), settings.HMACSecret) { t.Fatal("pending state contains deployment secrets") } + readback := sendDirectory(t, first.router, "/api/v1/sync/readback", settings.HMACSecret, "fixed-readback", "user.readback", map[string]string{"subject": "fixed-user"}) + if readback.Code != 200 { + t.Fatalf("fixed directory: %d %s", readback.Code, readback.Body.String()) + } + refused := sendDirectory(t, first.router, "/api/v1/sync/readback", strings.Repeat("q", 32), "fixed-wrong-key", "user.readback", map[string]string{"subject": "fixed-user"}) + if refused.Code == 200 { + t.Fatal("wrong directory signature accepted") + } + logout := first.sign("logout+jwt", first.logoutClaims("fixed-logout", "fixed-user", "sid")) + if res := first.logout(logout); res.Code != 200 { + t.Fatalf("fixed logout: %d %s", res.Code, res.Body.String()) + } + if res := first.logout(logout); res.Code != 400 { + t.Fatalf("logout replay: %d", res.Code) + } + if res := first.send(req); res.Code != 403 || errorCode(t, res.Body.String()) != "sso_login_rejected" { + t.Fatalf("logout failed to fence an in-flight login: %d %s", res.Code, res.Body.String()) + } + if err := first.db.QueryRow(`SELECT count(*) FROM sessions WHERE revoked_at='' AND sso_subject='fixed-user'`).Scan(&n); err != nil || n != 0 { + t.Fatal("logout left a live session", n, err) + } if err := first.settings.Save(changed); err != sso.ErrFixedSettings { t.Fatal("fixed settings save succeeded", err) } } + +func TestFixedSSOStoreRetainsSingleModeConfigurationFences(t *testing.T) { + f := newLogoutFixture(t) + settings := f.settings.Load() + settings.HMACSecret = strings.Repeat("h", 32) + fixed := sso.NewFixedStore(settings) + router := http.NewServeMux() + SSORoutes(router, f.db, f.cfg, fixed) + f.router = router + req := f.beginLogin("single-fixed", "sid", time.Now()) + if _, err := f.db.Exec(`UPDATE server_settings SET value='false' WHERE key='sso_enabled'`); err != nil { + t.Fatal(err) + } + if res := f.send(req); res.Code != 403 || errorCode(t, res.Body.String()) != "sso_login_rejected" { + t.Fatalf("fixed flag bypassed single-mode configuration: %d %s", res.Code, res.Body.String()) + } + if res := sendDirectory(t, router, "/api/v1/sync/readback", settings.HMACSecret, "single-fixed-read", "user.readback", map[string]string{"subject": "single-fixed"}); res.Code != 422 { + t.Fatalf("fixed flag bypassed single directory fence: %d %s", res.Code, res.Body.String()) + } +} diff --git a/internal/httpapi/sso_directory.go b/internal/httpapi/sso_directory.go index cad5c1d5..e9da7d62 100644 --- a/internal/httpapi/sso_directory.go +++ b/internal/httpapi/sso_directory.go @@ -77,14 +77,14 @@ func registerDirectorySync(mux RouteMux, db *sql.DB, cfg config.Config, settings verified.ServeHTTP(&syncAuthWriter{ResponseWriter: w, request: r}, r) }) } - apply := wrap(func(w http.ResponseWriter, r *http.Request) { directoryRequest(w, r, db, cfg, false) }) + apply := wrap(func(w http.ResponseWriter, r *http.Request) { directoryRequest(w, r, db, cfg, false, settings.Fixed()) }) for _, path := range []string{"/api/v1/sync/events", "/api/sync/events", "/sync/events"} { mux.Handle("POST "+path, apply) } - mux.Handle("POST /api/v1/sync/readback", wrap(func(w http.ResponseWriter, r *http.Request) { directoryRequest(w, r, db, cfg, true) })) + mux.Handle("POST /api/v1/sync/readback", wrap(func(w http.ResponseWriter, r *http.Request) { directoryRequest(w, r, db, cfg, true, settings.Fixed()) })) } -func directoryRequest(w http.ResponseWriter, r *http.Request, db *sql.DB, cfg config.Config, readback bool) { +func directoryRequest(w http.ResponseWriter, r *http.Request, db *sql.DB, cfg config.Config, readback, fixedSettings bool) { settings := r.Context().Value(syncSettingsKey{}).(sso.SSOSettings) event, ok := syncauth.EventFromContext(r) if !ok { @@ -139,7 +139,7 @@ func directoryRequest(w http.ResponseWriter, r *http.Request, db *sql.DB, cfg co } defer tx.Rollback() var current int - if err = tx.QueryRow(`SELECT count(*) FROM server_settings WHERE key='sso_hmac_secret' AND value=? AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_issuer_url' AND value=?)`, settings.HMACSecret, settings.IssuerURL).Scan(¤t); err != nil { + if err = tx.QueryRow(`SELECT CASE WHEN COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')='multi' AND ?=1 THEN 1 ELSE (SELECT count(*) FROM server_settings WHERE key='sso_hmac_secret' AND value=? AND EXISTS(SELECT 1 FROM server_settings WHERE key='sso_issuer_url' AND value=?)) END`, fixedSettings, settings.HMACSecret, settings.IssuerURL).Scan(¤t); err != nil { WriteError(w, r, 500, "sync_failed", "configuration lookup failed") return } diff --git a/internal/httpapi/sso_logout.go b/internal/httpapi/sso_logout.go index 2592a5ff..7773c93b 100644 --- a/internal/httpapi/sso_logout.go +++ b/internal/httpapi/sso_logout.go @@ -57,7 +57,7 @@ func registerSSOLogout(mux RouteMux, db *sql.DB, store *sso.Store, cfg config.Co reject(w, r, 400, "invalid logout token") return } - if err = auth.ApplySSOLogout(r.Context(), db, c, settings.ClientID, RequestID(r)); err != nil { + if err = auth.ApplySSOLogout(r.Context(), db, c, settings.ClientID, RequestID(r), store.Fixed()); err != nil { if errors.Is(err, auth.ErrSSOLogoutRejected) { WriteError(w, r, 400, "invalid_logout", "invalid logout token") } else { diff --git a/internal/httpapi/sso_routes.go b/internal/httpapi/sso_routes.go index 81e9f9f5..19c9d4fe 100644 --- a/internal/httpapi/sso_routes.go +++ b/internal/httpapi/sso_routes.go @@ -365,7 +365,7 @@ func SSORoutes(mux RouteMux, db *sql.DB, cfg config.Config, ssoStore *sso.Store, if claims.ValidUntil.Before(deadline) { deadline = claims.ValidUntil } - identity := auth.SSOIdentity{Issuer: settings.IssuerURL, ClientID: settings.ClientID, Subject: claims.Subject, SessionID: claims.SessionID, IssuedAt: claims.IssuedAt, AppAdmin: claims.AppAdmin, LoginExpires: deadline} + identity := auth.SSOIdentity{FixedConfiguration: ssoStore.Fixed(), Issuer: settings.IssuerURL, ClientID: settings.ClientID, Subject: claims.Subject, SessionID: claims.SessionID, IssuedAt: claims.IssuedAt, AppAdmin: claims.AppAdmin, LoginExpires: deadline} err := auth.CompleteSSOStepUp(r.Context(), db, transaction.ReauthSession, transaction.Challenge, identity, claims.AuthTime, claims.Assurance, RequestID(r)) if err != nil { if errors.Is(err, auth.ErrSSOLoginRejected) { @@ -472,7 +472,7 @@ func SSORoutes(mux RouteMux, db *sql.DB, cfg config.Config, ssoStore *sso.Store, if claims.ValidUntil.Before(deadline) { deadline = claims.ValidUntil } - _, err = auth.MintSSOSession(r.Context(), db, w, userID, auth.SSOIdentity{Issuer: settings.IssuerURL, ClientID: settings.ClientID, Subject: claims.Subject, SessionID: claims.SessionID, AppAdmin: claims.AppAdmin, IssuedAt: claims.IssuedAt, LoginExpires: deadline, ExportOnly: tenancy.Multi() && claims.ExportOnly}, cfg.Server.DevInsecureCookies, RequestID(r)) + _, err = auth.MintSSOSession(r.Context(), db, w, userID, auth.SSOIdentity{FixedConfiguration: ssoStore.Fixed(), Issuer: settings.IssuerURL, ClientID: settings.ClientID, Subject: claims.Subject, SessionID: claims.SessionID, AppAdmin: claims.AppAdmin, IssuedAt: claims.IssuedAt, LoginExpires: deadline, ExportOnly: tenancy.Multi() && claims.ExportOnly}, cfg.Server.DevInsecureCookies, RequestID(r)) if err != nil { if errors.Is(err, auth.ErrSSOLoginRejected) { WriteError(w, r, 403, "sso_login_rejected", "restart Single Sign-On login") diff --git a/internal/sso/sso.go b/internal/sso/sso.go index b7fcb0c5..09b1d112 100644 --- a/internal/sso/sso.go +++ b/internal/sso/sso.go @@ -59,6 +59,10 @@ func NewFixedStore(settings SSOSettings) *Store { return &Store{cached: settings, fixed: true} } +// Fixed reports whether configuration can change during this process. Only the fixed +// constructor sets it; ordinary database-backed stores retain their commit-time SQL checks. +func (s *Store) Fixed() bool { return s.fixed } + var ErrFixedSettings = errors.New("sso: deployment settings are fixed") // Reload re-reads persisted settings; fixed and legacy in-memory snapshots stay unchanged. From 7357c2bac9317c67eaabd8702b932f7e44210e62 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Mon, 23 Nov 2026 18:06:10 -0500 Subject: [PATCH 3/3] fix: fence stopped orgs at final SSO session admission Recheck serving state under the writer lock, retaining only the approved export-only deletion exception. Prove stopped normal sessions emit no cookies and export-only admission remains available. Co-Authored-By: GPT 6.1 Sol --- internal/auth/sso_session.go | 5 +++-- internal/httpapi/fixed_sso_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/internal/auth/sso_session.go b/internal/auth/sso_session.go index b37d389e..77bcd063 100644 --- a/internal/auth/sso_session.go +++ b/internal/auth/sso_session.go @@ -62,7 +62,8 @@ func MintSSOSession(ctx context.Context, db *sql.DB, w http.ResponseWriter, user // checkSSOIdentityTx rechecks the issuer configuration and revocation fences under the writer lock. func checkSSOIdentityTx(tx *sql.Tx, userID string, identity SSOIdentity, now time.Time) error { var allowed int - err := tx.QueryRow(`SELECT count(*) FROM users WHERE id=? AND status='active' AND sso_issuer=? AND sso_subject=? + err := tx.QueryRow(`SELECT count(*) FROM users u WHERE id=? AND status='active' AND sso_issuer=? AND sso_subject=? + AND (`+storage.OrgServes("u.org_id")+` OR (?=1 AND `+exportOrg+`)) AND (COALESCE((SELECT value FROM server_settings WHERE key='tenancy_mode'),'single')<>'multi' OR NOT EXISTS(SELECT 1 FROM erased_subjects WHERE subject=?)) AND NOT EXISTS(SELECT 1 FROM sso_directory_state WHERE issuer=? AND subject=? AND revoked_before>=?) AND NOT EXISTS(SELECT 1 FROM sso_login_cutoffs WHERE issuer=? AND subject=? AND revoked_before>=?) @@ -73,7 +74,7 @@ func checkSSOIdentityTx(tx *sql.Tx, userID string, identity SSOIdentity, now tim AND ((sid<>'' AND sid=? AND (subject='' OR subject=?)) OR (?='' AND subject<>'' AND subject=? AND issued_at>=?) OR (sid='' AND subject=? AND issued_at>=?)))`, - userID, identity.Issuer, identity.Subject, identity.Subject, identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.FixedConfiguration, identity.Issuer, identity.ClientID, identity.Issuer, identity.ClientID, now.Unix(), identity.SessionID, identity.Subject, identity.SessionID, identity.Subject, identity.IssuedAt.Unix(), identity.Subject, identity.IssuedAt.Unix()).Scan(&allowed) + userID, identity.Issuer, identity.Subject, identity.ExportOnly, identity.Subject, identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.Issuer, identity.Subject, identity.IssuedAt.Unix(), identity.FixedConfiguration, identity.Issuer, identity.ClientID, identity.Issuer, identity.ClientID, now.Unix(), identity.SessionID, identity.Subject, identity.SessionID, identity.Subject, identity.IssuedAt.Unix(), identity.Subject, identity.IssuedAt.Unix()).Scan(&allowed) if err != nil { return err } diff --git a/internal/httpapi/fixed_sso_test.go b/internal/httpapi/fixed_sso_test.go index dabc5a1a..c03a8dc2 100644 --- a/internal/httpapi/fixed_sso_test.go +++ b/internal/httpapi/fixed_sso_test.go @@ -1,7 +1,10 @@ package httpapi import ( + "errors" + "github.com/Busnes-app/kynotes-server/internal/auth" "net/http" + "net/http/httptest" "strings" "testing" "time" @@ -58,6 +61,30 @@ func TestFixedSSOSettingsAuthenticateAcrossPoolsWithoutDatabaseSecrets(t *testin if res := first.send(req); res.Code != 400 { t.Fatalf("replayed callback: %d %s", res.Code, res.Body.String()) } + // Admission may have checked an active org before waiting for the writer lock. + // Recheck current status/region and the export exception at the final mint boundary. + var userID string + if err := first.db.QueryRow(`SELECT id FROM users WHERE sso_subject='fixed-user'`).Scan(&userID); err != nil { + t.Fatal(err) + } + identity := auth.SSOIdentity{Issuer: settings.IssuerURL, ClientID: settings.ClientID, Subject: "fixed-user", SessionID: "sid", IssuedAt: time.Now(), LoginExpires: time.Now().Add(time.Minute), FixedConfiguration: true} + for _, status := range []string{"suspended", "deletion_scheduled"} { + if _, err := first.db.Exec(`UPDATE orgs SET status=? WHERE id=?`, status, storage.DefaultOrgID); err != nil { + t.Fatal(err) + } + out := httptest.NewRecorder() + if _, err := auth.MintSSOSession(t.Context(), first.db, out, userID, identity, true, "fixed-org-stop"); !errors.Is(err, auth.ErrSSOLoginRejected) || len(out.Result().Cookies()) != 0 { + t.Fatalf("stopped org minted a session: %s %v", status, err) + } + } + identity.ExportOnly = true + if _, err := auth.MintSSOSession(t.Context(), first.db, httptest.NewRecorder(), userID, identity, true, "fixed-export"); err != nil { + t.Fatal("export-only deletion exception lost", err) + } + if _, err := first.db.Exec(`UPDATE orgs SET status='active' WHERE id=?`, storage.DefaultOrgID); err != nil { + t.Fatal(err) + } + if res := second.send(request("org_other")); res.Code != 403 || errorCode(t, res.Body.String()) != "org_mismatch" { t.Fatalf("wrong org: %d %s", res.Code, res.Body.String()) }