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
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,14 @@ 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. 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.
- 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.
Expand Down
16 changes: 16 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1047,3 +1047,19 @@ 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.

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.
17 changes: 17 additions & 0 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2351,3 +2351,20 @@ 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.

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.
13 changes: 13 additions & 0 deletions docs/ASSURANCE-CASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,16 @@ 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.

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.
17 changes: 17 additions & 0 deletions docs/superpowers/specs/2026-11-23-tenancy-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -1606,3 +1606,20 @@ 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.

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.
8 changes: 8 additions & 0 deletions internal/app/replica_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/auth/sso_logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down
10 changes: 6 additions & 4 deletions internal/auth/sso_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -61,18 +62,19 @@ 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>=?)
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.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
}
Expand Down
158 changes: 158 additions & 0 deletions internal/httpapi/fixed_sso_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package httpapi

import (
"errors"
"github.com/Busnes-app/kynotes-server/internal/auth"
"net/http"
"net/http/httptest"
"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())
}
// 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())
}
// 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")
}
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())
}
}
Loading
Loading