Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Preserve environment SSO authority across extension saves
pulse-triage[bot]b801b3438195
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex f4ba0f4917..291d49f773 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -12888,3 +12888,28 @@ detail response; `sso_json_admission_test.go`, `rbac_json_admission_test.go` and`admin_json_test.go` cover persisted preservation, explicit clears, aliases,limits and one-use recovery. These are public source controls, not an observedexploit, private runtime acceptance or installed sign-in recovery.++### Environment authority survives SSO extension snapshots (26 October 2026)++`extensions.SSOProvider.RuntimeManaged` carries the core-owned environment+authority through both provider conversions; it is not a JSON field. Snapshot+reads and accepted replacements detach all nested authorization collections.+Before persistence, a replacement must retain each current environment provider+unchanged and exactly once. An older consumer may omit the internal marker,+but core restores it and the environment field locks from the authoritative+configuration. Changed, missing, duplicated or newly asserted environment+authority returns `ErrSSOProviderManagedByEnvironment` without saving or+publishing. Environment credentials never become a persisted provider as a+side effect of an unrelated saved-provider edit.++Authenticated/scoped PUT and DELETE refuse environment providers with the+existing `409 provider_managed_by_environment` before dispatch to replacement+handlers. Extension initialization refuses those IDs and removal callbacks+leave their live services alone. Saved-provider CRUD, blank-secret preservation,+discovery, local administrator access and Community SSO entitlement remain+unchanged. `sso_environment_boundary_test.go` covers legacy conversions,+credential/persistence authority, detached ownership, callbacks and pre-dispatch+refusal. `TestContractSSOEnvironmentBoundaryConsumer` binds actual authenticated+responses and temporary persistence to the existing editor's request shapes;+optional synthetic fixtures support consuming browser proof. These controls+are not a claim of an installed leak or native identity-provider recovery.diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 96f9c3982c..30734add4c 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -72,6 +72,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/pkg/cloudauth""github.com/rcourtman/pulse-go-rewrite/pkg/diskinventory""github.com/rcourtman/pulse-go-rewrite/pkg/edition"+ "github.com/rcourtman/pulse-go-rewrite/pkg/extensions"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"licensetestsupport "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/testsupport""github.com/rcourtman/pulse-go-rewrite/pkg/metrics"@@ -28184,3 +28185,86 @@ func TestContract_ConfigImportIncompleteRuntimeKeepsCommittedOutcome(t *testing.t.Fatalf("replay replaced a newer legitimate edit: %#v %v", newer, err)}}++// TestContractSSOEnvironmentBoundaryConsumer exercises the real authenticated+// routes and persistence, including a legacy extension's marker-free snapshot.+// Optional fixture output contains synthetic HTTP responses for browser proof.+func TestContractSSOEnvironmentBoundaryConsumer(t *testing.T) {+ fixture := environmentBoundaryRouter(t)+ const token = "sso-environment-consumer-synthetic-token.12345678"+ record := newTokenRecord(t, token, []string{config.ScopeSettingsRead, config.ScopeSettingsWrite}, nil)+ cfg := newTestConfigWithTokens(t, record)+ cfg.PublicURL = "https://pulse.example.test"+ var probe *environmentBoundaryEndpointProbe+ SetSSOAdminEndpointsBinder(func(defaults extensions.SSOAdminEndpoints, _ extensions.SSOAdminRuntime) extensions.SSOAdminEndpoints {+ probe = &environmentBoundaryEndpointProbe{SSOAdminEndpoints: defaults}+ return probe+ })+ t.Cleanup(func() { SetSSOAdminEndpointsBinder(nil) })+ r := NewRouter(cfg, nil, nil, nil, nil, "test")+ r.ssoConfig = fixture.currentSSOConfig().Clone()+ if err := r.saveSSOConfig(); err != nil {+ t.Fatal(err)+ }+ var responses []map[string]interface{}+ request := func(name, method, path, body string, status int) {+ t.Helper()+ req := httptest.NewRequest(method, path, strings.NewReader(body))+ req.RemoteAddr = ssoTestIP()+ req.Header.Set("X-API-Token", token)+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ r.Handler().ServeHTTP(w, req)+ if w.Code != status {+ t.Fatalf("%s: got %d, want %d: %s", name, w.Code, status, w.Body.String())+ }+ if strings.Contains(w.Body.String(), "synthetic-environment-secret") || strings.Contains(w.Body.String(), "synthetic-saved-secret") {+ t.Fatal("provider response exposed a credential")+ }+ responses = append(responses, map[string]interface{}{"name": name, "method": method, "path": path, "request": body, "status": w.Code, "body": w.Body.String()})+ }+ base := "/api/security/sso/providers"+ id := config.LegacyOIDCProviderID+ request("initial", http.MethodGet, base, "", http.StatusOK)+ request("environment-detail", http.MethodGet, base+"/"+id, "", http.StatusOK)+ // These request objects match the canonical editor's saved form shape.+ envDraft := `{"id":"` + id + `","name":"Environment draft","type":"oidc","enabled":true,"displayName":"Single Sign-On","priority":0,"allowedGroups":[],"allowedDomains":[],"allowedEmails":[],"groupRoleMappings":{},"oidc":{"issuerUrl":"https://environment.example.test","clientId":"environment-client","redirectUrl":"https://pulse.example.test/api/oidc/callback","scopes":["openid","profile","email"]}}`+ request("environment-refused", http.MethodPut, base+"/"+id, envDraft, http.StatusConflict)+ request("environment-delete-refused", http.MethodDelete, base+"/"+id, "", http.StatusConflict)+ if probe.writes != 0 {+ t.Fatal("environment mutation reached the extension")+ }+ request("saved-detail", http.MethodGet, base+"/saved", "", http.StatusOK)+ savedDraft := `{"id":"saved","name":"Edited recovery","type":"oidc","enabled":false,"priority":0,"allowedGroups":["operators"],"allowedDomains":[],"allowedEmails":[],"groupRoleMappings":{"operators":"admin"},"oidc":{"issuerUrl":"https://saved.example.test","clientId":"saved-client","scopes":["openid","email"]}}`+ request("saved-updated", http.MethodPut, base+"/saved", savedDraft, http.StatusOK)+ if probe.writes != 1 {+ t.Fatal("saved-provider update did not reach the extension")+ }+ hooks := newSSOAdminRuntime(r)+ encoded, err := json.Marshal(hooks.GetSSOConfigSnapshot())+ if err != nil {+ t.Fatal(err)+ }+ var legacy extensions.SSOConfigSnapshot+ if err := json.Unmarshal(encoded, &legacy); err != nil {+ t.Fatal(err)+ }+ if err := hooks.SaveSSOConfigSnapshot(legacy); err != nil {+ t.Fatal(err)+ }+ assertEnvironmentNotPersisted(t, r)+ if r.currentSSOConfig().GetProvider("saved").OIDC.ClientSecret != "synthetic-saved-secret" {+ t.Fatal("blank edit lost saved-provider credential")+ }+ request("after-unrelated-save", http.MethodGet, base, "", http.StatusOK)+ request("saved-detail-after", http.MethodGet, base+"/saved", "", http.StatusOK)+ if output := os.Getenv("PULSE_SSO_ENV_FIXTURES"); output != "" {+ data, err := json.MarshalIndent(map[string]interface{}{"responses": responses, "environment_id": id, "scope": "Real public authenticated routes, bound default-delegating extension, synthetic environment and saved credentials, real temporary persistence. A separate marker-free snapshot save occurs before the final list. Not a real private-handler, issuer sign-in or installed journey."}, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(output, data, 0600); err != nil {+ t.Fatal(err)+ }+ }+}diff --git a/internal/api/router_routes_auth_security.go b/internal/api/router_routes_auth_security.goindex 181a4c22c7..8eec3881c8 100644--- a/internal/api/router_routes_auth_security.go+++ b/internal/api/router_routes_auth_security.go@@ -1,6 +1,7 @@package apiimport (+ "bytes""context""encoding/json""fmt"@@ -215,6 +216,13 @@ func (r *Router) registerAuthSecurityInstallRoutes() {if !ensureSettingsWriteScope(r.config, w, req) {return}+ // Enforce core-owned environment authority before invoking a bound+ // replacement, which may otherwise initialize or remove live services.+ providerID := strings.TrimSuffix(strings.TrimPrefix(req.URL.Path, "/api/security/sso/providers/"), "/")+ if r.isEnvironmentManagedSSOProvider(providerID) {+ writeErrorResponse(w, http.StatusConflict, "provider_managed_by_environment", "Provider is managed by OIDC environment variables", nil)+ return+ }default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return@@ -706,18 +714,20 @@ func newSSOAdminRuntime(router *Router) extensions.SSOAdminRuntime {runtime.PreviewSAMLMetadata = previewSAMLMetadataFromRuntimeruntime.IsValidProviderID = validateProviderIDruntime.GetSSOConfigSnapshot = func() extensions.SSOConfigSnapshot {- return toExtensionSSOConfigSnapshot(router.ensureSSOConfig())+ return toExtensionSSOConfigSnapshot(router.ensureSSOConfig().Clone())}runtime.SaveSSOConfigSnapshot = func(snapshot extensions.SSOConfigSnapshot) error {if router == nil {return nil}// Publish the replacement only once it is persisted.- _, err := router.commitSSOConfig(func(cfg *config.SSOConfig) error {- *cfg = *toCoreSSOConfig(snapshot)- return nil+ applyErr, saveErr := router.commitSSOConfig(func(cfg *config.SSOConfig) error {+ return replaceSSOConfigSnapshot(cfg, snapshot)})- return err+ if applyErr != nil {+ return applyErr+ }+ return saveErr}runtime.GetPublicURL = func() string {if router == nil || router.config == nil {@@ -726,18 +736,27 @@ func newSSOAdminRuntime(router *Router) extensions.SSOAdminRuntime {return router.config.PublicURL}runtime.InitializeSAMLProvider = func(ctx context.Context, id string, samlCfg *extensions.SAMLProviderConfig) error {+ if router.isEnvironmentManagedSSOProvider(id) {+ return extensions.ErrSSOProviderManagedByEnvironment+ }if router == nil || router.samlManager == nil || samlCfg == nil {return nil}return router.samlManager.InitializeProvider(ctx, id, toCoreSAMLProviderConfig(samlCfg))}runtime.RemoveSAMLProvider = func(id string) {+ if router.isEnvironmentManagedSSOProvider(id) {+ return+ }if router == nil || router.samlManager == nil {return}router.samlManager.RemoveProvider(id)}runtime.InitializeOIDCProvider = func(ctx context.Context, id string, provider *extensions.SSOProvider) error {+ if router.isEnvironmentManagedSSOProvider(id) {+ return extensions.ErrSSOProviderManagedByEnvironment+ }if router == nil || router.oidcManager == nil || provider == nil {return nil}@@ -745,6 +764,9 @@ func newSSOAdminRuntime(router *Router) extensions.SSOAdminRuntime {return router.oidcManager.InitializeProvider(ctx, id, &coreProvider, "")}runtime.RemoveOIDCProvider = func(id string) {+ if router.isEnvironmentManagedSSOProvider(id) {+ return+ }if router == nil || router.oidcManager == nil {return}@@ -753,6 +775,58 @@ func newSSOAdminRuntime(router *Router) extensions.SSOAdminRuntime {return runtime}+func (r *Router) isEnvironmentManagedSSOProvider(id string) bool {+ provider := r.ensureSSOConfig().GetProvider(id)+ return provider != nil && provider.RuntimeManaged+}++// replaceSSOConfigSnapshot runs inside commitSSOConfig's lock, before any+// persistence or publication. Never trust a snapshot to assign environment+// authority, or to remove it by losing the runtime-only marker in a conversion.+func replaceSSOConfigSnapshot(current *config.SSOConfig, snapshot extensions.SSOConfigSnapshot) error {+ next := toCoreSSOConfig(snapshot).Clone()+ for _, provider := range next.Providers {+ existing := current.GetProvider(provider.ID)+ if provider.RuntimeManaged && (existing == nil || !existing.RuntimeManaged) {+ return extensions.ErrSSOProviderManagedByEnvironment+ }+ }+ for _, existing := range current.Providers {+ if !existing.RuntimeManaged {+ continue+ }+ found := false+ for i := range next.Providers {+ provider := &next.Providers[i]+ if provider.ID != existing.ID {+ continue+ }+ // Compare the configuration, not runtime-only bookkeeping. JSON also+ // treats omitted and empty optional collections alike for old consumers.+ proposed, err := json.Marshal(provider)+ if err != nil {+ return err+ }+ authoritative, err := json.Marshal(existing)+ if err != nil {+ return err+ }+ if found || !bytes.Equal(proposed, authoritative) {+ return extensions.ErrSSOProviderManagedByEnvironment+ }+ found = true+ // current is already a private clone. Restore the marker and any+ // environment field locks rather than publishing caller-owned data.+ *provider = existing+ }+ if !found {+ return extensions.ErrSSOProviderManagedByEnvironment+ }+ }+ *current = *next+ return nil+}+func toAPISAMLTestConfig(cfg *extensions.SAMLTestConfig) *SAMLTestConfig {if cfg == nil {return nil@@ -851,6 +925,7 @@ func toExtensionSSOProvider(p config.SSOProvider) extensions.SSOProvider {AllowedEmails: p.AllowedEmails,GroupsClaim: p.GroupsClaim,GroupRoleMappings: p.GroupRoleMappings,+ RuntimeManaged: p.RuntimeManaged,}if p.OIDC != nil {@@ -929,6 +1004,7 @@ func toCoreSSOProvider(p extensions.SSOProvider) config.SSOProvider {AllowedEmails: p.AllowedEmails,GroupsClaim: p.GroupsClaim,GroupRoleMappings: p.GroupRoleMappings,+ RuntimeManaged: p.RuntimeManaged,}if p.OIDC != nil {diff --git a/internal/api/sso_environment_boundary_test.go b/internal/api/sso_environment_boundary_test.gonew file mode 100644index 0000000000..01ef82efdd--- /dev/null+++ b/internal/api/sso_environment_boundary_test.go@@ -0,0 +1,302 @@+package api++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/pkg/extensions"+)++// All credentials and identity-provider endpoints in these tests are synthetic.+func environmentBoundaryRouter(t *testing.T) *Router {+ t.Helper()+ t.Setenv("OIDC_ENABLED", "true")+ t.Setenv("OIDC_ISSUER_URL", "https://environment.example.test")+ t.Setenv("OIDC_CLIENT_ID", "environment-client")+ t.Setenv("OIDC_CLIENT_SECRET", "synthetic-environment-secret")+ r, _ := setupTestRouter(t)+ r.ssoConfig.Providers = []config.SSOProvider{{+ ID: "saved", Name: "Saved recovery", Type: config.SSOProviderTypeOIDC,+ AllowedGroups: []string{"operators"}, GroupRoleMappings: map[string]string{"operators": "admin"},+ OIDC: &config.OIDCProviderConfig{IssuerURL: "https://saved.example.test", ClientID: "saved-client", ClientSecret: "synthetic-saved-secret", ClientSecretSet: true, Scopes: []string{"openid", "email"}},+ }}+ r.ensureSSOConfig()+ if err := r.saveSSOConfig(); err != nil {+ t.Fatal(err)+ }+ return r+}++func assertEnvironmentNotPersisted(t *testing.T, r *Router) {+ t.Helper()+ live := r.currentSSOConfig().GetProvider(config.LegacyOIDCProviderID)+ if live == nil || !live.RuntimeManaged || live.OIDC == nil || live.OIDC.ClientSecret != "synthetic-environment-secret" || !live.OIDC.EnvOverrides["clientSecret"] {+ t.Error("live environment authority or credential was lost")+ }+ disk, err := r.persistence.LoadSSOConfig()+ if err != nil {+ t.Fatal(err)+ }+ if disk.GetProvider(config.LegacyOIDCProviderID) != nil {+ t.Error("environment provider was persisted")+ }+ data, err := os.ReadFile(filepath.Join(r.config.DataPath, "sso.enc"))+ if err != nil {+ t.Fatal(err)+ }+ if bytes.Contains(data, []byte("synthetic-environment-secret")) {+ t.Error("environment credential reached disk")+ }+}++func TestSSOEnvironmentBoundaryRoundTrip(t *testing.T) {+ r := environmentBoundaryRouter(t)+ core := r.ensureSSOConfig()+ roundTrip := toCoreSSOConfig(toExtensionSSOConfigSnapshot(core))+ if p := roundTrip.GetProvider(config.LegacyOIDCProviderID); p == nil || !p.RuntimeManaged {+ t.Error("extension conversion discarded environment authority")+ }+ encoded, err := json.Marshal(toExtensionSSOConfigSnapshot(core))+ if err != nil {+ t.Fatal(err)+ }+ if bytes.Contains(bytes.ToLower(encoded), []byte("runtimemanaged")) {+ t.Error("internal authority marker is JSON-writable")+ }+}++func TestSSOEnvironmentBoundaryUnrelatedSave(t *testing.T) {+ for _, legacy := range []bool{false, true} {+ t.Run(map[bool]string{false: "marker-preserved", true: "legacy-marker-omitted"}[legacy], func(t *testing.T) {+ r := environmentBoundaryRouter(t)+ hooks := newSSOAdminRuntime(r)+ snapshot := hooks.GetSSOConfigSnapshot()+ if legacy {+ encoded, err := json.Marshal(snapshot)+ if err != nil {+ t.Fatal(err)+ }+ snapshot = extensions.SSOConfigSnapshot{}+ if err := json.Unmarshal(encoded, &snapshot); err != nil {+ t.Fatal(err)+ }+ }+ for i := range snapshot.Providers {+ if snapshot.Providers[i].ID == "saved" {+ snapshot.Providers[i].Name = "Edited recovery"+ }+ }+ if err := hooks.SaveSSOConfigSnapshot(snapshot); err != nil {+ t.Fatal(err)+ }+ assertEnvironmentNotPersisted(t, r)+ if r.currentSSOConfig().GetProvider("saved").Name != "Edited recovery" {+ t.Error("unrelated saved-provider edit was lost")+ }+ if r.currentSSOConfig().GetProvider("saved").OIDC.ClientSecret != "synthetic-saved-secret" {+ t.Error("saved-provider secret was lost")+ }+ })+ }+}++func TestSSOEnvironmentBoundaryRejectsSnapshotMutation(t *testing.T) {+ for _, mutation := range []string{"name", "secret", "disable", "delete", "duplicate", "new-runtime", "saved-runtime"} {+ t.Run(mutation, func(t *testing.T) {+ r := environmentBoundaryRouter(t)+ hooks := newSSOAdminRuntime(r)+ snapshot := hooks.GetSSOConfigSnapshot()+ before := r.currentSSOConfig().Clone()+ beforeDisk, err := os.ReadFile(filepath.Join(r.config.DataPath, "sso.enc"))+ if err != nil {+ t.Fatal(err)+ }+ for i := range snapshot.Providers {+ p := &snapshot.Providers[i]+ if p.ID != config.LegacyOIDCProviderID {+ continue+ }+ switch mutation {+ case "name":+ p.Name = "changed"+ case "secret":+ p.OIDC.ClientSecret = "changed"+ case "disable":+ p.Enabled = false+ case "delete":+ snapshot.Providers = append(snapshot.Providers[:i], snapshot.Providers[i+1:]...)+ case "duplicate":+ snapshot.Providers = append(snapshot.Providers, *p)+ case "new-runtime", "saved-runtime":+ id := "new"+ if mutation == "saved-runtime" {+ id = "saved"+ }+ forged := toExtensionSSOProvider(config.SSOProvider{ID: id, Name: "Forged", RuntimeManaged: true})+ if id == "saved" {+ snapshot.Providers[0] = forged+ } else {+ snapshot.Providers = append(snapshot.Providers, forged)+ }+ }+ break+ }+ if err := hooks.SaveSSOConfigSnapshot(snapshot); err == nil {+ t.Error("snapshot environment mutation was accepted")+ }+ if !reflect.DeepEqual(before, r.currentSSOConfig()) {+ t.Error("refused save changed the published snapshot")+ }+ afterDisk, err := os.ReadFile(filepath.Join(r.config.DataPath, "sso.enc"))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(beforeDisk, afterDisk) {+ t.Error("refused save changed persisted bytes")+ }+ assertEnvironmentNotPersisted(t, r)+ })+ }+}++func TestSSOEnvironmentBoundarySnapshotOwnership(t *testing.T) {+ for _, stage := range []string{"read", "save"} {+ t.Run(stage, func(t *testing.T) {+ r := environmentBoundaryRouter(t)+ hooks := newSSOAdminRuntime(r)+ snapshot := hooks.GetSSOConfigSnapshot()+ if stage == "save" {+ if err := hooks.SaveSSOConfigSnapshot(snapshot); err != nil {+ t.Fatal(err)+ }+ }+ before := r.currentSSOConfig().Clone()+ snapshot.Providers[0].AllowedGroups[0] = "changed"+ snapshot.Providers[0].GroupRoleMappings["operators"] = "viewer"+ snapshot.Providers[0].OIDC.Scopes[0] = "changed"+ if !reflect.DeepEqual(before, r.currentSSOConfig()) {+ t.Error("caller-owned snapshot mutates published authorization")+ }+ })+ }+}++func TestSSOEnvironmentBoundaryInitialization(t *testing.T) {+ r := environmentBoundaryRouter(t)+ hooks := newSSOAdminRuntime(r)+ provider := toExtensionSSOProvider(*r.currentSSOConfig().GetProvider(config.LegacyOIDCProviderID))+ // Nil managers must not turn a prohibited operation into apparent success.+ r.oidcManager = nil+ r.samlManager = nil+ if err := hooks.InitializeOIDCProvider(context.Background(), provider.ID, &provider); err == nil {+ t.Error("environment OIDC initialization was accepted")+ }+ if err := hooks.InitializeSAMLProvider(context.Background(), provider.ID, &extensions.SAMLProviderConfig{}); err == nil {+ t.Error("environment type change was accepted")+ }+ if err := hooks.InitializeOIDCProvider(context.Background(), "saved", &provider); err != nil {+ t.Error("saved-provider initialization was blocked")+ }+}++func TestSSOEnvironmentBoundaryRemoval(t *testing.T) {+ r := environmentBoundaryRouter(t)+ id := config.LegacyOIDCProviderID+ oidc := &OIDCService{stateStore: newOIDCStateStore()}+ t.Cleanup(oidc.stateStore.Stop)+ saml := &SAMLService{}+ r.oidcManager.services[id] = oidc+ r.oidcManager.services["saved"] = oidc+ r.samlManager.services[id] = saml+ r.samlManager.services["saved"] = saml+ hooks := newSSOAdminRuntime(r)+ hooks.RemoveOIDCProvider(id)+ hooks.RemoveSAMLProvider(id)+ if r.oidcManager.GetService(id) != oidc {+ t.Error("extension removed environment OIDC service")+ }+ if r.samlManager.GetService(id) != saml {+ t.Error("extension removed environment SAML service")+ }+ hooks.RemoveOIDCProvider("saved")+ hooks.RemoveSAMLProvider("saved")+ if r.oidcManager.GetService("saved") != nil || r.samlManager.GetService("saved") != nil {+ t.Error("saved-provider removal was blocked")+ }+}++type environmentBoundaryEndpointProbe struct {+ extensions.SSOAdminEndpoints+ writes int+ permissive bool+}++func (p *environmentBoundaryEndpointProbe) HandleProviderItem(w http.ResponseWriter, req *http.Request) {+ if req.Method == http.MethodPut || req.Method == http.MethodDelete {+ p.writes+++ if p.permissive {+ w.WriteHeader(http.StatusNoContent)+ return+ }+ }+ p.SSOAdminEndpoints.HandleProviderItem(w, req)+}++func TestSSOEnvironmentBoundaryBeforeExtensionDispatch(t *testing.T) {+ fixture := environmentBoundaryRouter(t)+ const token = "sso-environment-boundary-synthetic-token.12345678"+ record := newTokenRecord(t, token, []string{config.ScopeSettingsRead, config.ScopeSettingsWrite}, nil)+ cfg := newTestConfigWithTokens(t, record)+ var probe *environmentBoundaryEndpointProbe+ SetSSOAdminEndpointsBinder(func(defaults extensions.SSOAdminEndpoints, _ extensions.SSOAdminRuntime) extensions.SSOAdminEndpoints {+ probe = &environmentBoundaryEndpointProbe{SSOAdminEndpoints: defaults, permissive: true}+ return probe+ })+ t.Cleanup(func() { SetSSOAdminEndpointsBinder(nil) })+ r := NewRouter(cfg, nil, nil, nil, nil, "test")+ r.ssoConfig = fixture.currentSSOConfig().Clone()+ for _, method := range []string{http.MethodPut, http.MethodDelete} {+ for _, suffix := range []string{"", "/"} {+ req := httptest.NewRequest(method, "/api/security/sso/providers/"+config.LegacyOIDCProviderID+suffix, strings.NewReader(`{"name":"changed","type":"oidc"}`))+ req.RemoteAddr = ssoTestIP()+ req.Header.Set("X-API-Token", token)+ w := httptest.NewRecorder()+ r.Handler().ServeHTTP(w, req)+ if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "provider_managed_by_environment") {+ t.Errorf("%s environment provider: got %d, want 409", method, w.Code)+ }+ }+ }+ if probe.writes != 0 {+ t.Errorf("environment writes reached extension %d times", probe.writes)+ }+ for _, method := range []string{http.MethodPut, http.MethodDelete} {+ req := httptest.NewRequest(method, "/api/security/sso/providers/saved", strings.NewReader(`{}`))+ req.RemoteAddr = ssoTestIP()+ req.Header.Set("X-API-Token", token)+ w := httptest.NewRecorder()+ r.Handler().ServeHTTP(w, req)+ if w.Code != http.StatusNoContent {+ t.Errorf("saved provider: got %d, want extension 204", w.Code)+ }+ }+ if probe.writes != 2 {+ t.Error("saved-provider dispatch was blocked")+ }+ req := httptest.NewRequest(http.MethodDelete, "/api/security/sso/providers/"+config.LegacyOIDCProviderID, nil)+ req.RemoteAddr = ssoTestIP()+ w := httptest.NewRecorder()+ r.Handler().ServeHTTP(w, req)+ if w.Code != http.StatusUnauthorized {+ t.Errorf("authentication must precede environment detail, got %d", w.Code)+ }+}diff --git a/pkg/extensions/sso_admin.go b/pkg/extensions/sso_admin.goindex bd2bfbd340..24e82ba521 100644--- a/pkg/extensions/sso_admin.go+++ b/pkg/extensions/sso_admin.go@@ -2,10 +2,15 @@ package extensionsimport ("context"+ "errors""net/http""time")+// ErrSSOProviderManagedByEnvironment refuses an extension's attempt to change+// a provider whose authoritative configuration comes from the process environment.+var ErrSSOProviderManagedByEnvironment = errors.New("provider is managed by OIDC environment variables")+// SSOAdminEndpoints defines the enterprise SSO admin endpoint surface.type SSOAdminEndpoints interface {HandleProvidersCollection(http.ResponseWriter, *http.Request)@@ -83,6 +88,9 @@ type SSOProvider struct {GroupRoleMappings map[string]string `json:"groupRoleMappings,omitempty"`OIDC *OIDCProviderConfig `json:"oidc,omitempty"`SAML *SAMLProviderConfig `json:"saml,omitempty"`+ // RuntimeManaged is core-owned authority, not an API-editable setting.+ // Such providers remain discoverable but cannot be changed or persisted.+ RuntimeManaged bool `json:"-"`}// SSOConfigSnapshot is the runtime snapshot used by enterprise handlers.@@ -205,12 +213,14 @@ type LogSSOAuditEventFunc func(ctx context.Context, event, path string, success// SSOAdminRuntime exposes runtime capabilities needed by SSO admin endpoints.type SSOAdminRuntime struct {- GetClientIP func(*http.Request) string- AllowAuthRequest func(clientIP string) bool- TestSAMLConnection func(context.Context, *SAMLTestConfig) SSOTestResponse- TestOIDCConnection func(context.Context, *OIDCTestConfig) SSOTestResponse- PreviewSAMLMetadata func(context.Context, MetadataPreviewRequest) (MetadataPreviewResponse, error)- IsValidProviderID func(string) bool+ GetClientIP func(*http.Request) string+ AllowAuthRequest func(clientIP string) bool+ TestSAMLConnection func(context.Context, *SAMLTestConfig) SSOTestResponse+ TestOIDCConnection func(context.Context, *OIDCTestConfig) SSOTestResponse+ PreviewSAMLMetadata func(context.Context, MetadataPreviewRequest) (MetadataPreviewResponse, error)+ IsValidProviderID func(string) bool+ // Get returns a detached snapshot. Save rejects environment-provider changes+ // and restores core-owned authority when an older consumer omits the marker.GetSSOConfigSnapshot func() SSOConfigSnapshotSaveSSOConfigSnapshot func(SSOConfigSnapshot) errorGetPublicURL func() string