mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-28 16:58:31 +01:00
Keep enabled Community OIDC provider scopes usable (#5034)
Reject enabled creation, activation and changed scope selections when a custom list lacks the required openid token. Check the effective update under the existing save lock before persistence or service initialization. Keep defaults, disabled drafts, unchanged legacy selections and the last working provider intact. Contract-Neutral: Reject unusable non-OIDC scope selections only on enabled creation, activation or replacement. Supported OIDC scopes, legacy round-trips, routes, response schemas, stored configuration and access semantics are unchanged. --- Fleet candidate `20261123T215226Z-core-runtime` from the `core-runtime` lane. Reviewed tip `32b01d62d1ab9e270d6c1e6c23c5b4df1d5b5ba1` on `main`. [How Pulse handles triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
@@ -13,6 +13,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -33,6 +34,29 @@ const (
|
||||
)
|
||||
|
||||
var errSSOProviderManaged = errors.New("provider is managed by OIDC environment variables")
|
||||
var errSSOOIDCOpenIDScopeRequired = errors.New("Include openid in Scopes, or clear Scopes to use the defaults. Nothing was saved.")
|
||||
|
||||
// Validate the selection at the Community write boundary, not on load or
|
||||
// sign-in. Existing malformed selections can be left alone or disabled.
|
||||
func validateSSOOIDCScopeWrite(next, previous *config.SSOProvider) error {
|
||||
if !next.Enabled || next.Type != config.SSOProviderTypeOIDC || next.OIDC == nil || len(next.OIDC.Scopes) == 0 {
|
||||
return nil // An empty list uses the existing OpenID Connect defaults.
|
||||
}
|
||||
if previous != nil && previous.Enabled && previous.Type == next.Type && previous.OIDC != nil &&
|
||||
slices.Equal(previous.OIDC.Scopes, next.OIDC.Scopes) {
|
||||
return nil // An already enabled legacy provider can round-trip unchanged.
|
||||
}
|
||||
// The OAuth client joins entries with ASCII spaces. Check exact tokens
|
||||
// as sent (not substrings, case-folded values or other whitespace).
|
||||
for _, entry := range next.OIDC.Scopes {
|
||||
for token := range strings.SplitSeq(entry, " ") {
|
||||
if token == "openid" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return errSSOOIDCOpenIDScopeRequired
|
||||
}
|
||||
|
||||
// providerIDRegex validates provider IDs (alphanumeric, hyphens, underscores)
|
||||
var providerIDRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}[a-zA-Z0-9]?$`)
|
||||
@@ -462,6 +486,10 @@ func (r *Router) handleCreateSSOProvider(w http.ResponseWriter, req *http.Reques
|
||||
writeErrorResponse(w, http.StatusConflict, "duplicate_id", "Provider with this ID already exists", nil)
|
||||
return
|
||||
}
|
||||
if err := validateSSOOIDCScopeWrite(&provider, nil); err != nil {
|
||||
writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Add and persist the provider; nothing is published if either step fails.
|
||||
addErr, saveErr := r.commitSSOConfig(func(cfg *config.SSOConfig) error {
|
||||
@@ -590,6 +618,9 @@ func (r *Router) handleUpdateSSOProvider(w http.ResponseWriter, req *http.Reques
|
||||
if err := mergeSSOProviderUpdate(data, &updated, current); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateSSOOIDCScopeWrite(&updated, current); err != nil {
|
||||
return err
|
||||
}
|
||||
// UpdateProvider replaces the slice element current points at. Retain
|
||||
// its prior value for the post-commit service lifecycle comparison.
|
||||
existing = &previous
|
||||
@@ -600,6 +631,10 @@ func (r *Router) handleUpdateSSOProvider(w http.ResponseWriter, req *http.Reques
|
||||
writeErrorResponse(w, http.StatusConflict, "provider_managed_by_environment", "Provider is managed by OIDC environment variables", nil)
|
||||
return
|
||||
}
|
||||
if errors.Is(updateErr, errSSOOIDCOpenIDScopeRequired) {
|
||||
writeErrorResponse(w, http.StatusBadRequest, "validation_error", updateErr.Error(), nil)
|
||||
return
|
||||
}
|
||||
writeErrorResponse(w, http.StatusBadRequest, "update_error", updateErr.Error(), nil)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -241,6 +243,136 @@ func TestSSOProviderDetailRoundTripPreservesOIDCEditableSettings(t *testing.T) {
|
||||
assert.Equal(t, map[string]string{"admins": "admin"}, stored.GroupRoleMappings)
|
||||
}
|
||||
|
||||
func TestSSOOIDCRejectsUnusableEnabledScopeWrites(t *testing.T) {
|
||||
f := newPresentationFixture(t, config.SSOProviderTypeOIDC)
|
||||
r, original := f.router, f.provider
|
||||
draft := original
|
||||
draft.ID, draft.Enabled = "legacy-draft", false
|
||||
draftOIDC := *original.OIDC
|
||||
draftOIDC.Scopes = []string{"groups"}
|
||||
draft.OIDC = &draftOIDC
|
||||
require.NoError(t, r.ssoConfig.AddProvider(draft))
|
||||
require.NoError(t, r.saveSSOConfig())
|
||||
t.Cleanup(func() {
|
||||
r.oidcManager.RemoveService("new-oidc")
|
||||
r.oidcManager.RemoveService(draft.ID)
|
||||
})
|
||||
|
||||
file := filepath.Join(r.config.DataPath, "sso.enc")
|
||||
before, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
snapshot := r.ensureSSOConfig()
|
||||
live := r.oidcManager.GetService(original.ID)
|
||||
requests := f.requests.Load()
|
||||
newProvider := draft
|
||||
newProvider.ID, newProvider.Enabled = "new-oidc", true
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
edit := providerToDetailResponse(&original, r.config.PublicURL, req)
|
||||
edit.OIDC.Scopes = []string{"OpenID", "openid-extra", "groups\topenid"}
|
||||
enable := providerToResponse(&draft, r.config.PublicURL, req)
|
||||
enable.Enabled = true
|
||||
|
||||
for _, tc := range []struct {
|
||||
action, method, suffix string
|
||||
body any
|
||||
}{
|
||||
{"add", http.MethodPost, "", newProvider},
|
||||
{"edit", http.MethodPut, "/" + original.ID, edit},
|
||||
{"enable-with-omitted-oidc", http.MethodPut, "/" + draft.ID, enable},
|
||||
} {
|
||||
t.Run(tc.action, func(t *testing.T) {
|
||||
rec := ssoScopeWrite(t, r, tc.method, tc.suffix, tc.body)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
var reply APIError
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &reply))
|
||||
require.Contains(t, reply.ErrorMessage, "Include openid in Scopes")
|
||||
require.NotContains(t, rec.Body.String(), "openid-extra")
|
||||
require.NotContains(t, rec.Body.String(), original.OIDC.ClientSecret)
|
||||
require.Same(t, snapshot, r.currentSSOConfig())
|
||||
require.Same(t, live, r.oidcManager.GetService(original.ID))
|
||||
require.Nil(t, r.oidcManager.GetService(draft.ID))
|
||||
require.Equal(t, requests, f.requests.Load(), "refused write must not discover the issuer")
|
||||
after, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, before, after, "refused write must not persist")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOOIDCScopeWritesKeepDefaultsAndLegacyRecovery(t *testing.T) {
|
||||
f := newPresentationFixture(t, config.SSOProviderTypeOIDC)
|
||||
r, original := f.router, f.provider
|
||||
legacy := original
|
||||
legacy.ID = "legacy-enabled"
|
||||
legacyOIDC := *original.OIDC
|
||||
legacyOIDC.Scopes = []string{"groups"}
|
||||
legacy.OIDC = &legacyOIDC
|
||||
require.NoError(t, r.ssoConfig.AddProvider(legacy))
|
||||
require.NoError(t, r.saveSSOConfig())
|
||||
t.Cleanup(func() { r.oidcManager.RemoveService(legacy.ID) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
readBack := func(id string, wantScopes []string, enabled bool) *config.SSOProvider {
|
||||
t.Helper()
|
||||
cfg, err := r.persistence.LoadSSOConfig()
|
||||
require.NoError(t, err)
|
||||
p := cfg.GetProvider(id)
|
||||
require.NotNil(t, p)
|
||||
require.Equal(t, wantScopes, p.OIDC.Scopes)
|
||||
require.Equal(t, enabled, p.Enabled)
|
||||
require.Equal(t, original.OIDC.ClientSecret, p.OIDC.ClientSecret)
|
||||
require.Equal(t, original.AllowedGroups, p.AllowedGroups)
|
||||
require.Equal(t, original.GroupRoleMappings, p.GroupRoleMappings)
|
||||
return p
|
||||
}
|
||||
save := func(p *config.SSOProvider, scopes []string, enabled bool) {
|
||||
t.Helper()
|
||||
edit := providerToDetailResponse(p, r.config.PublicURL, req)
|
||||
edit.Enabled, edit.OIDC.Scopes = enabled, scopes
|
||||
rec := ssoScopeWrite(t, r, http.MethodPut, "/"+p.ID, edit)
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// A legacy entry elsewhere cannot prevent a valid provider from saving.
|
||||
// A compound ASCII-space entry has the same wire scope as separate entries.
|
||||
custom := []string{"profile openid", "groups"}
|
||||
save(&original, custom, true)
|
||||
saved := readBack(original.ID, custom, true)
|
||||
readBack(legacy.ID, legacyOIDC.Scopes, true)
|
||||
require.Equal(t, custom, r.oidcManager.GetService(original.ID).oauth2Cfg.Scopes)
|
||||
|
||||
// Explicit empty selection still uses the runtime defaults, without
|
||||
// manufacturing a custom array in persistence.
|
||||
save(saved, []string{}, true)
|
||||
readBack(original.ID, nil, true)
|
||||
require.Equal(t, []string{"openid", "profile", "email"}, r.oidcManager.GetService(original.ID).oauth2Cfg.Scopes)
|
||||
|
||||
// Round-tripping a legacy selection doesn't rewrite it. Disabling it is
|
||||
// still possible, as is correcting and enabling it with exact new scopes.
|
||||
save(&legacy, legacyOIDC.Scopes, true)
|
||||
save(&legacy, legacyOIDC.Scopes, false)
|
||||
disabled := readBack(legacy.ID, legacyOIDC.Scopes, false)
|
||||
require.Nil(t, r.oidcManager.GetService(legacy.ID))
|
||||
corrected := []string{"openid", "groups"}
|
||||
save(disabled, corrected, true)
|
||||
readBack(legacy.ID, corrected, true)
|
||||
require.Equal(t, corrected, r.oidcManager.GetService(legacy.ID).oauth2Cfg.Scopes)
|
||||
}
|
||||
|
||||
func ssoScopeWrite(t *testing.T, r *Router, method, suffix string, payload any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
req := httptest.NewRequest(method, "/api/security/sso/providers"+suffix, bytes.NewReader(data))
|
||||
rec := httptest.NewRecorder()
|
||||
if suffix == "" {
|
||||
r.handleSSOProviders(rec, req)
|
||||
} else {
|
||||
r.handleSSOProvider(rec, req)
|
||||
}
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestUpdateSSOProvider_EmptyValuesClearRestrictionFields(t *testing.T) {
|
||||
router, _ := setupTestRouter(t)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user