From 99b74273c01e3ad91d1946f85d51f45ccbbb1f24 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Tue, 1 Dec 2026 11:39:13 -0800 Subject: [PATCH 1/2] fix(auth): request OIDC groups scope only when needed and supported --- docs/authentication.md | 9 ++ internal/api/oidc.go | 36 +++++++- internal/api/oidc_discovery_test.go | 91 +++++++++++++++++++ internal/api/oidc_test.go | 66 ++++++++++++++ .../docs/docs/concepts/authentication.mdx | 7 ++ 5 files changed, 207 insertions(+), 2 deletions(-) diff --git a/docs/authentication.md b/docs/authentication.md index da8222eb..ac407986 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -256,6 +256,15 @@ If neither list is configured there is no allow policy to enforce. Membership is then managed locally through user administration, unless a role mapping is set; see [Who owns accounts](#who-owns-accounts). +Pitot always requests the standard `openid`, `profile`, and `email` scopes. It +appends `groups` only when `PITOT_OIDC_ALLOWED_GROUPS`, +`PITOT_OIDC_ADMIN_GROUPS`, or `PITOT_OIDC_OPERATOR_GROUPS` is configured and +the provider's discovery document either advertises `groups` in +`scopes_supported` or omits `scopes_supported`. Providers such as Google (when +no group policy is set) and Microsoft Entra ID (which emits group claims from +token configuration rather than a `groups` scope) therefore never receive an +unsupported `groups` scope. + ### Role ownership If `PITOT_OIDC_ADMIN_GROUPS` or `PITOT_OIDC_OPERATOR_GROUPS` is set, the diff --git a/internal/api/oidc.go b/internal/api/oidc.go index fedd4dbc..72a1b88f 100644 --- a/internal/api/oidc.go +++ b/internal/api/oidc.go @@ -61,7 +61,7 @@ func registerOIDCRoutes(ctx context.Context, e *echo.Echo, cfg config.Config, us oauth: oauth2.Config{ ClientID: cfg.OIDCClientID, ClientSecret: cfg.OIDCClientSecret, Endpoint: provider.Endpoint(), RedirectURL: callback, - Scopes: []string{oidc.ScopeOpenID, "profile", "email", "groups"}, + Scopes: oidcAuthorizationScopes(cfg, discoveredScopesSupported(provider)), }, } }, @@ -385,9 +385,41 @@ func (h *OIDCHandler) reconcileEligibility(claims oidcClaims) error { return nil } +// oidcGroupPolicyConfigured reports whether any decision depends on group claims. +func oidcGroupPolicyConfigured(cfg config.Config) bool { + return len(csvValues(cfg.OIDCAllowedGroups)) != 0 || cfg.OIDCRoleMappingConfigured() +} + +// oidcAuthorizationScopes returns the OAuth 2.0 scopes to request at the +// authorization endpoint. "groups" is not a standard OIDC Core scope: +// providers such as Google and Microsoft Entra ID reject it with invalid_scope, +// and Entra ID emits group claims from application token configuration rather +// than a scope. Request it only when a group policy uses the claim and the +// provider's discovery metadata does not advertise a scope set without it. +func oidcAuthorizationScopes(cfg config.Config, scopesSupported []string) []string { + scopes := []string{oidc.ScopeOpenID, "profile", "email"} + if !oidcGroupPolicyConfigured(cfg) { + return scopes + } + if len(scopesSupported) == 0 || slices.Contains(scopesSupported, "groups") { + scopes = append(scopes, "groups") + } + return scopes +} + +func discoveredScopesSupported(provider *oidc.Provider) []string { + var meta struct { + ScopesSupported []string `json:"scopes_supported"` + } + if err := provider.Claims(&meta); err != nil { + return nil + } + return meta.ScopesSupported +} + // groupPolicyConfigured reports whether any decision depends on group claims. func (h *OIDCHandler) groupPolicyConfigured() bool { - return len(csvValues(h.cfg.OIDCAllowedGroups)) != 0 || h.roleMappingConfigured() + return oidcGroupPolicyConfigured(h.cfg) } // roleMappingConfigured reports whether the IdP owns the fixed role. Without a diff --git a/internal/api/oidc_discovery_test.go b/internal/api/oidc_discovery_test.go index ce8035f2..1eba96db 100644 --- a/internal/api/oidc_discovery_test.go +++ b/internal/api/oidc_discovery_test.go @@ -519,3 +519,94 @@ func TestOIDCDiscoveryWrongIssuerOnRetryStaysUnavailable(t *testing.T) { default: } } + +func TestOIDCStartRequestsGroupsScopeOnlyWhenNeededAndSupported(t *testing.T) { + cases := []struct { + name string + cfg func(*config.Config) + scopesSupported any + hasScopesField bool + wantScope string + }{ + { + name: "google domain allowlist", + cfg: func(c *config.Config) { c.OIDCAllowedDomains = "example.com" }, + scopesSupported: []string{"openid", "email", "profile"}, + hasScopesField: true, + wantScope: "openid profile email", + }, + { + name: "entra group policy without groups scope", + cfg: func(c *config.Config) { c.OIDCAllowedGroups = "sre" }, + scopesSupported: []string{"openid", "profile", "email", "offline_access"}, + hasScopesField: true, + wantScope: "openid profile email", + }, + { + name: "okta group policy with groups scope", + cfg: func(c *config.Config) { c.OIDCAdminGroups = "pitot-admins" }, + scopesSupported: []string{"openid", "profile", "email", "groups"}, + hasScopesField: true, + wantScope: "openid profile email groups", + }, + { + name: "group policy with discovery omitting scopes_supported", + cfg: func(c *config.Config) { c.OIDCOperatorGroups = "operators" }, + hasScopesField: false, + wantScope: "openid profile email groups", + }, + { + name: "group policy tolerates malformed scopes_supported metadata", + cfg: func(c *config.Config) { c.OIDCAllowedGroups = "sre" }, + scopesSupported: "unexpected-string", + hasScopesField: true, + wantScope: "openid profile email groups", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var issuer string + idp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/.well-known/openid-configuration" { + http.NotFound(w, r) + return + } + doc := map[string]any{ + "issuer": issuer, + "authorization_endpoint": issuer + "/authorize", + "token_endpoint": issuer + "/token", + "jwks_uri": issuer + "/keys", + "response_types_supported": []string{"code"}, + "subject_types_supported": []string{"public"}, + "id_token_signing_alg_values_supported": []string{"RS256"}, + } + if tc.hasScopesField { + doc["scopes_supported"] = tc.scopesSupported + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(doc) + })) + defer idp.Close() + issuer = idp.URL + + fixture := newOIDCDiscoveryFixture(t, idp.URL) + tc.cfg(&fixture.cfg) + if _, err := fixture.register(t.Context(), fastOIDCDiscovery); err != nil { + t.Fatalf("register: %v", err) + } + + redirect := fixture.get("/api/auth/oidc/start") + if redirect.Code != http.StatusFound { + t.Fatalf("start status = %d, want 302: %s", redirect.Code, redirect.Body.String()) + } + location, err := url.Parse(redirect.Header().Get("Location")) + if err != nil { + t.Fatalf("parse redirect location: %v", err) + } + if got := location.Query().Get("scope"); got != tc.wantScope { + t.Fatalf("redirect scope = %q, want %q", got, tc.wantScope) + } + }) + } +} diff --git a/internal/api/oidc_test.go b/internal/api/oidc_test.go index 28e815c3..af009300 100644 --- a/internal/api/oidc_test.go +++ b/internal/api/oidc_test.go @@ -11,6 +11,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "slices" "strings" "testing" "time" @@ -785,3 +786,68 @@ func TestReconciledRoleChangeIsAttributableToItsSource(t *testing.T) { t.Fatalf("role.changed recorded ip=%q agent=%q, want %q and %q: the handler's most security-relevant event must be correlatable", ip, agent, source.IP, source.UserAgent) } } + +func TestOIDCAuthorizationScopes(t *testing.T) { + standard := []string{"openid", "profile", "email"} + withGroups := []string{"openid", "profile", "email", "groups"} + + cases := []struct { + name string + cfg config.Config + scopesSupported []string + want []string + }{ + { + name: "no policy requests standard scopes", + cfg: config.Config{}, + want: standard, + }, + { + name: "domain allowlist omits groups even when provider supports it", + cfg: config.Config{OIDCAllowedDomains: "example.com"}, + scopesSupported: []string{"openid", "profile", "email", "groups"}, + want: standard, + }, + { + name: "blank group lists omit groups", + cfg: config.Config{ + OIDCAllowedGroups: " , , ", + OIDCAdminGroups: " , ", + OIDCOperatorGroups: " ", + }, + want: standard, + }, + { + name: "allowed groups requests groups when discovery omits scopes_supported", + cfg: config.Config{OIDCAllowedGroups: "sre"}, + want: withGroups, + }, + { + name: "admin group mapping requests groups when discovery advertises it", + cfg: config.Config{OIDCAdminGroups: "pitot-admins"}, + scopesSupported: []string{"openid", "profile", "email", "groups"}, + want: withGroups, + }, + { + name: "operator group mapping requests groups when discovery advertises it", + cfg: config.Config{OIDCOperatorGroups: "operators"}, + scopesSupported: []string{"openid", "profile", "email", "groups"}, + want: withGroups, + }, + { + name: "group policy omits groups when provider advertises scopes without it", + cfg: config.Config{OIDCAllowedGroups: "sre", OIDCAdminGroups: "pitot-admins"}, + scopesSupported: []string{"openid", "profile", "email", "offline_access"}, + want: standard, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := oidcAuthorizationScopes(tc.cfg, tc.scopesSupported) + if !slices.Equal(got, tc.want) { + t.Fatalf("oidcAuthorizationScopes = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/site/src/content/docs/docs/concepts/authentication.mdx b/site/src/content/docs/docs/concepts/authentication.mdx index 9dee0b80..4b3a2c2f 100644 --- a/site/src/content/docs/docs/concepts/authentication.mdx +++ b/site/src/content/docs/docs/concepts/authentication.mdx @@ -48,6 +48,13 @@ If neither `PITOT_OIDC_ALLOWED_GROUPS` nor `PITOT_OIDC_ALLOWED_DOMAINS` is configured, no eligibility allow policy is enforced. Membership is then managed locally, unless a role mapping is set; see [Who owns accounts](#who-owns-accounts). +Pitot requests `openid`, `profile` and `email` by default, and adds `groups` +only when a group allowlist or group role mapping is configured and the +provider's discovery metadata either advertises `groups` in `scopes_supported` +or omits `scopes_supported`. Providers that reject unknown scopes or emit group +claims from token configuration (such as Google and Microsoft Entra ID) do not +receive an unsupported `groups` scope. + ### Account provisioning `PITOT_OIDC_AUTO_PROVISION` creates eligible accounts on first sign-in after From 8d010f084c7263cc3cd663d7d4cb87ab7c9e3b09 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Tue, 1 Dec 2026 12:08:18 -0800 Subject: [PATCH 2/2] fix(auth): add PITOT_OIDC_SCOPES and request groups regardless of discovery --- .env.example | 5 ++ docs/authentication.md | 15 +++-- internal/api/oidc.go | 43 +++++++------- internal/api/oidc_discovery_test.go | 52 +++++++++-------- internal/api/oidc_test.go | 55 ++++++++++-------- internal/config/config.go | 49 +++++++++++++++- internal/config/config_test.go | 57 +++++++++++++++++++ .../docs/docs/concepts/authentication.mdx | 12 ++-- .../docs/reference/configuration/auth.mdx | 5 ++ 9 files changed, 206 insertions(+), 87 deletions(-) diff --git a/.env.example b/.env.example index 30cf4029..ab31ea15 100644 --- a/.env.example +++ b/.env.example @@ -209,6 +209,11 @@ # Default: (empty) # PITOT_OIDC_OPERATOR_GROUPS= +# PITOT_OIDC_SCOPES; string +# Overrides the OAuth 2.0 scopes requested during OIDC sign-in, separated by commas; empty requests openid, profile, and email, plus groups when a group policy is configured. +# Default: (empty) +# PITOT_OIDC_SCOPES= + # PITOT_PPROF_ENABLED; boolean # Exposes Go's net/http/pprof handlers at /debug/pprof/* for CPU/heap/mutex/goroutine profiling under load. Off by default; the routes require an admin browser session with operations:read. # Default: false diff --git a/docs/authentication.md b/docs/authentication.md index ac407986..93e74f64 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -256,14 +256,13 @@ If neither list is configured there is no allow policy to enforce. Membership is then managed locally through user administration, unless a role mapping is set; see [Who owns accounts](#who-owns-accounts). -Pitot always requests the standard `openid`, `profile`, and `email` scopes. It -appends `groups` only when `PITOT_OIDC_ALLOWED_GROUPS`, -`PITOT_OIDC_ADMIN_GROUPS`, or `PITOT_OIDC_OPERATOR_GROUPS` is configured and -the provider's discovery document either advertises `groups` in -`scopes_supported` or omits `scopes_supported`. Providers such as Google (when -no group policy is set) and Microsoft Entra ID (which emits group claims from -token configuration rather than a `groups` scope) therefore never receive an -unsupported `groups` scope. +Pitot requests the standard `openid`, `profile`, and `email` scopes by default, +and appends `groups` only when `PITOT_OIDC_ALLOWED_GROUPS`, +`PITOT_OIDC_ADMIN_GROUPS`, or `PITOT_OIDC_OPERATOR_GROUPS` is configured. Set +`PITOT_OIDC_SCOPES` (comma-separated, must include `openid`) when a provider +uses a different scope to release the `groups` claim or emits group claims from +token configuration while rejecting `scope=groups` (such as Microsoft Entra ID: +`PITOT_OIDC_SCOPES=openid,profile,email`). ### Role ownership diff --git a/internal/api/oidc.go b/internal/api/oidc.go index 72a1b88f..8ffd7f16 100644 --- a/internal/api/oidc.go +++ b/internal/api/oidc.go @@ -52,6 +52,10 @@ func registerOIDCRoutes(ctx context.Context, e *echo.Echo, cfg config.Config, us if users == nil || identities == nil || sessions == nil || audit == nil { return nil, fmt.Errorf("OIDC dependencies are required") } + scopes, err := oidcAuthorizationScopes(cfg) + if err != nil { + return nil, err + } callback := strings.TrimRight(cfg.PublicURL, "/") + "/api/auth/oidc/callback" discovery := &OIDCDiscovery{ issuer: cfg.OIDCIssuerURL, timing: timing, done: make(chan struct{}), @@ -61,12 +65,12 @@ func registerOIDCRoutes(ctx context.Context, e *echo.Echo, cfg config.Config, us oauth: oauth2.Config{ ClientID: cfg.OIDCClientID, ClientSecret: cfg.OIDCClientSecret, Endpoint: provider.Endpoint(), RedirectURL: callback, - Scopes: oidcAuthorizationScopes(cfg, discoveredScopesSupported(provider)), + Scopes: scopes, }, } }, } - err := discovery.attempt(ctx) + err = discovery.attempt(ctx) if err != nil && oidcConfigurationInvalid(err) { return nil, fmt.Errorf("discover OIDC provider: %w", err) } @@ -391,30 +395,23 @@ func oidcGroupPolicyConfigured(cfg config.Config) bool { } // oidcAuthorizationScopes returns the OAuth 2.0 scopes to request at the -// authorization endpoint. "groups" is not a standard OIDC Core scope: -// providers such as Google and Microsoft Entra ID reject it with invalid_scope, -// and Entra ID emits group claims from application token configuration rather -// than a scope. Request it only when a group policy uses the claim and the -// provider's discovery metadata does not advertise a scope set without it. -func oidcAuthorizationScopes(cfg config.Config, scopesSupported []string) []string { - scopes := []string{oidc.ScopeOpenID, "profile", "email"} - if !oidcGroupPolicyConfigured(cfg) { - return scopes +// authorization endpoint. When PITOT_OIDC_SCOPES is set, its validated list is +// used directly; otherwise Pitot requests openid, profile, and email, appending +// groups whenever a group policy uses the claim (even if the provider's +// discovery metadata omits non-core scopes per OIDC Discovery 1.0 §3). +func oidcAuthorizationScopes(cfg config.Config) ([]string, error) { + explicit, err := cfg.ParsedOIDCScopes() + if err != nil { + return nil, err } - if len(scopesSupported) == 0 || slices.Contains(scopesSupported, "groups") { - scopes = append(scopes, "groups") + if len(explicit) != 0 { + return explicit, nil } - return scopes -} - -func discoveredScopesSupported(provider *oidc.Provider) []string { - var meta struct { - ScopesSupported []string `json:"scopes_supported"` - } - if err := provider.Claims(&meta); err != nil { - return nil + scopes := []string{oidc.ScopeOpenID, "profile", "email"} + if oidcGroupPolicyConfigured(cfg) { + scopes = append(scopes, "groups") } - return meta.ScopesSupported + return scopes, nil } // groupPolicyConfigured reports whether any decision depends on group claims. diff --git a/internal/api/oidc_discovery_test.go b/internal/api/oidc_discovery_test.go index 1eba96db..f8919e8a 100644 --- a/internal/api/oidc_discovery_test.go +++ b/internal/api/oidc_discovery_test.go @@ -520,47 +520,41 @@ func TestOIDCDiscoveryWrongIssuerOnRetryStaysUnavailable(t *testing.T) { } } -func TestOIDCStartRequestsGroupsScopeOnlyWhenNeededAndSupported(t *testing.T) { +func TestOIDCStartRequestsExpectedAuthorizationScopes(t *testing.T) { cases := []struct { name string cfg func(*config.Config) - scopesSupported any - hasScopesField bool + scopesSupported []string wantScope string }{ { - name: "google domain allowlist", + name: "google domain allowlist omits groups", cfg: func(c *config.Config) { c.OIDCAllowedDomains = "example.com" }, scopesSupported: []string{"openid", "email", "profile"}, - hasScopesField: true, wantScope: "openid profile email", }, { - name: "entra group policy without groups scope", + name: "group policy keeps groups even when omitted from scopes_supported", cfg: func(c *config.Config) { c.OIDCAllowedGroups = "sre" }, - scopesSupported: []string{"openid", "profile", "email", "offline_access"}, - hasScopesField: true, - wantScope: "openid profile email", - }, - { - name: "okta group policy with groups scope", - cfg: func(c *config.Config) { c.OIDCAdminGroups = "pitot-admins" }, - scopesSupported: []string{"openid", "profile", "email", "groups"}, - hasScopesField: true, + scopesSupported: []string{"openid", "profile", "email"}, wantScope: "openid profile email groups", }, { - name: "group policy with discovery omitting scopes_supported", - cfg: func(c *config.Config) { c.OIDCOperatorGroups = "operators" }, - hasScopesField: false, - wantScope: "openid profile email groups", + name: "entra group policy uses PITOT_OIDC_SCOPES override", + cfg: func(c *config.Config) { + c.OIDCAllowedGroups = "sre" + c.OIDCScopes = "openid,profile,email" + }, + scopesSupported: []string{"openid", "profile", "email", "offline_access"}, + wantScope: "openid profile email", }, { - name: "group policy tolerates malformed scopes_supported metadata", - cfg: func(c *config.Config) { c.OIDCAllowedGroups = "sre" }, - scopesSupported: "unexpected-string", - hasScopesField: true, - wantScope: "openid profile email groups", + name: "custom scope releasing groups via PITOT_OIDC_SCOPES", + cfg: func(c *config.Config) { + c.OIDCAdminGroups = "pitot-admins" + c.OIDCScopes = "openid, profile, email, https://example.com/auth/groups" + }, + wantScope: "openid profile email https://example.com/auth/groups", }, } @@ -581,7 +575,7 @@ func TestOIDCStartRequestsGroupsScopeOnlyWhenNeededAndSupported(t *testing.T) { "subject_types_supported": []string{"public"}, "id_token_signing_alg_values_supported": []string{"RS256"}, } - if tc.hasScopesField { + if tc.scopesSupported != nil { doc["scopes_supported"] = tc.scopesSupported } w.Header().Set("Content-Type", "application/json") @@ -609,4 +603,12 @@ func TestOIDCStartRequestsGroupsScopeOnlyWhenNeededAndSupported(t *testing.T) { } }) } + + t.Run("rejects invalid OIDCScopes before discovery", func(t *testing.T) { + fixture := newOIDCDiscoveryFixture(t, "https://issuer.example.com") + fixture.cfg.OIDCScopes = "profile,email" + if _, err := fixture.register(t.Context(), fastOIDCDiscovery); err == nil { + t.Fatal("register accepted OIDCScopes missing openid") + } + }) } diff --git a/internal/api/oidc_test.go b/internal/api/oidc_test.go index af009300..058f0609 100644 --- a/internal/api/oidc_test.go +++ b/internal/api/oidc_test.go @@ -792,10 +792,9 @@ func TestOIDCAuthorizationScopes(t *testing.T) { withGroups := []string{"openid", "profile", "email", "groups"} cases := []struct { - name string - cfg config.Config - scopesSupported []string - want []string + name string + cfg config.Config + want []string }{ { name: "no policy requests standard scopes", @@ -803,10 +802,9 @@ func TestOIDCAuthorizationScopes(t *testing.T) { want: standard, }, { - name: "domain allowlist omits groups even when provider supports it", - cfg: config.Config{OIDCAllowedDomains: "example.com"}, - scopesSupported: []string{"openid", "profile", "email", "groups"}, - want: standard, + name: "domain allowlist omits groups", + cfg: config.Config{OIDCAllowedDomains: "example.com"}, + want: standard, }, { name: "blank group lists omit groups", @@ -818,33 +816,44 @@ func TestOIDCAuthorizationScopes(t *testing.T) { want: standard, }, { - name: "allowed groups requests groups when discovery omits scopes_supported", - cfg: config.Config{OIDCAllowedGroups: "sre"}, + name: "allowed groups requests groups including names with spaces", + cfg: config.Config{OIDCAllowedGroups: "Platform Engineers"}, + want: withGroups, + }, + { + name: "admin group mapping requests groups", + cfg: config.Config{OIDCAdminGroups: "pitot-admins"}, want: withGroups, }, { - name: "admin group mapping requests groups when discovery advertises it", - cfg: config.Config{OIDCAdminGroups: "pitot-admins"}, - scopesSupported: []string{"openid", "profile", "email", "groups"}, - want: withGroups, + name: "operator group mapping requests groups", + cfg: config.Config{OIDCOperatorGroups: "operators"}, + want: withGroups, }, { - name: "operator group mapping requests groups when discovery advertises it", - cfg: config.Config{OIDCOperatorGroups: "operators"}, - scopesSupported: []string{"openid", "profile", "email", "groups"}, - want: withGroups, + name: "explicit PITOT_OIDC_SCOPES overrides group policy default", + cfg: config.Config{ + OIDCAllowedGroups: "sre", + OIDCScopes: "openid, profile, email", + }, + want: standard, }, { - name: "group policy omits groups when provider advertises scopes without it", - cfg: config.Config{OIDCAllowedGroups: "sre", OIDCAdminGroups: "pitot-admins"}, - scopesSupported: []string{"openid", "profile", "email", "offline_access"}, - want: standard, + name: "explicit PITOT_OIDC_SCOPES supports custom scope releasing groups", + cfg: config.Config{ + OIDCAdminGroups: "pitot-admins", + OIDCScopes: "openid, profile, email, https://example.com/auth/groups", + }, + want: []string{"openid", "profile", "email", "https://example.com/auth/groups"}, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - got := oidcAuthorizationScopes(tc.cfg, tc.scopesSupported) + got, err := oidcAuthorizationScopes(tc.cfg) + if err != nil { + t.Fatalf("oidcAuthorizationScopes error = %v", err) + } if !slices.Equal(got, tc.want) { t.Fatalf("oidcAuthorizationScopes = %v, want %v", got, tc.want) } diff --git a/internal/config/config.go b/internal/config/config.go index 6394c7a3..0cb4dc96 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "net" "net/url" "path/filepath" + "slices" "strings" "time" "unicode" @@ -207,6 +208,8 @@ type Config struct { OIDCOperatorGroups string `group:"auth" env:"PITOT_OIDC_OPERATOR_GROUPS"` // OIDCAdminGroups lists identity-provider groups mapped to admin, separated by commas. OIDCAdminGroups string `group:"auth" env:"PITOT_OIDC_ADMIN_GROUPS"` + // OIDCScopes overrides the OAuth 2.0 scopes requested during OIDC sign-in, separated by commas; empty requests openid, profile, and email, plus groups when a group policy is configured. + OIDCScopes string `group:"auth" env:"PITOT_OIDC_SCOPES"` // MetricsToken authorizes Prometheus scrapes with a bearer token; optional when using an admin session. MetricsToken string `group:"metrics" env:"PITOT_METRICS_TOKEN" secret:"true"` // MetricsPublic allows unauthenticated Prometheus scrapes. @@ -258,6 +261,45 @@ func (c Config) OIDCRoleMappingConfigured() bool { return nameListed(c.OIDCAdminGroups) || nameListed(c.OIDCOperatorGroups) } +// ParsedOIDCScopes parses PITOT_OIDC_SCOPES as comma-separated RFC 6749 §3.3 +// scope tokens, preserving case and deduplicating in order. It returns nil when +// PITOT_OIDC_SCOPES is unset. +func (c Config) ParsedOIDCScopes() ([]string, error) { + if c.OIDCScopes == "" { + return nil, nil + } + var scopes []string + for _, raw := range strings.Split(c.OIDCScopes, ",") { + scope := strings.TrimSpace(raw) + if scope == "" { + continue + } + if !validOAuthScopeToken(scope) { + return nil, fmt.Errorf("PITOT_OIDC_SCOPES contains invalid scope token %q", scope) + } + if !slices.Contains(scopes, scope) { + scopes = append(scopes, scope) + } + } + if len(scopes) == 0 { + return nil, fmt.Errorf("PITOT_OIDC_SCOPES must list at least openid when set") + } + if !slices.Contains(scopes, "openid") { + return nil, fmt.Errorf("PITOT_OIDC_SCOPES must include openid") + } + return scopes, nil +} + +func validOAuthScopeToken(s string) bool { + for i := 0; i < len(s); i++ { + b := s[i] + if b < 0x21 || b == '"' || b == '\\' || b > 0x7e { + return false + } + } + return len(s) > 0 +} + func nameListed(raw string) bool { return len(strings.FieldsFunc(raw, func(r rune) bool { return r == ',' || unicode.IsSpace(r) })) != 0 } @@ -424,15 +466,18 @@ func (c Config) Validate() error { if strings.TrimSpace(c.OIDCEmailClaim) == "" { return fmt.Errorf("PITOT_OIDC_EMAIL_CLAIM must not be empty") } - if c.OIDCEmailVerification == "issuer" && strings.TrimSpace(c.OIDCAllowedGroups) == "" && strings.TrimSpace(c.OIDCAllowedDomains) == "" { + if c.OIDCEmailVerification == "issuer" && !nameListed(c.OIDCAllowedGroups) && !nameListed(c.OIDCAllowedDomains) { return fmt.Errorf("OIDC issuer email verification requires PITOT_OIDC_ALLOWED_GROUPS or PITOT_OIDC_ALLOWED_DOMAINS") } if !appauth.ValidRole(c.OIDCDefaultRole) { return fmt.Errorf("PITOT_OIDC_DEFAULT_ROLE must be viewer, operator, or admin") } - if c.OIDCAutoProvision && strings.TrimSpace(c.OIDCAllowedGroups) == "" && strings.TrimSpace(c.OIDCAllowedDomains) == "" { + if c.OIDCAutoProvision && !nameListed(c.OIDCAllowedGroups) && !nameListed(c.OIDCAllowedDomains) { return fmt.Errorf("OIDC auto-provisioning requires PITOT_OIDC_ALLOWED_GROUPS or PITOT_OIDC_ALLOWED_DOMAINS") } + if _, err := c.ParsedOIDCScopes(); err != nil { + return err + } } provider, supported := providers[c.AIProvider] if c.AIProvider != "" && !supported { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 50e04b12..a9895a5e 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -800,3 +800,60 @@ func TestControlDatabaseUsesProductFilename(t *testing.T) { t.Fatal("control database must use the product filename") } } + +func TestOIDCScopesValidation(t *testing.T) { + oidcEnv := []string{ + "PITOT_AUTH_MODE=oidc", + "PITOT_OIDC_ISSUER_URL=https://issuer.example.com", + "PITOT_OIDC_CLIENT_ID=client", + "PITOT_OIDC_CLIENT_SECRET=secret", + "PITOT_PUBLIC_URL=https://pitot.example.com", + } + + t.Run("valid comma-separated scopes preserve case and deduplicate", func(t *testing.T) { + cfg, err := Load(LoadOptions{Environ: append(slices.Clone(oidcEnv), "PITOT_OIDC_SCOPES=openid, profile, email, CustomGroups, https://example.com/auth/groups, profile")}) + if err != nil { + t.Fatalf("Load: %v", err) + } + scopes, err := cfg.ParsedOIDCScopes() + if err != nil { + t.Fatalf("ParsedOIDCScopes: %v", err) + } + want := []string{"openid", "profile", "email", "CustomGroups", "https://example.com/auth/groups"} + if !slices.Equal(scopes, want) { + t.Fatalf("ParsedOIDCScopes = %v, want %v", scopes, want) + } + }) + + t.Run("ignored in local mode", func(t *testing.T) { + if _, err := Load(LoadOptions{Environ: append(validEnvironment(), "PITOT_OIDC_SCOPES=profile")}); err != nil { + t.Fatalf("local mode should ignore PITOT_OIDC_SCOPES: %v", err) + } + }) + + t.Run("separator-only allowlists fail issuer verification and auto-provisioning", func(t *testing.T) { + if _, err := Load(LoadOptions{Environ: append(slices.Clone(oidcEnv), "PITOT_OIDC_EMAIL_VERIFICATION=issuer", "PITOT_OIDC_ALLOWED_GROUPS= , ")}); err == nil { + t.Fatal("separator-only PITOT_OIDC_ALLOWED_GROUPS satisfied issuer verification allowlist check") + } + if _, err := Load(LoadOptions{Environ: append(slices.Clone(oidcEnv), "PITOT_OIDC_AUTO_PROVISION=true", "PITOT_OIDC_ALLOWED_DOMAINS= , ")}); err == nil { + t.Fatal("separator-only PITOT_OIDC_ALLOWED_DOMAINS satisfied auto-provisioning allowlist check") + } + }) + + for label, raw := range map[string]string{ + "missing openid": "profile,email", + "wrong openid case": "OPENID,profile,email", + "space separated": "openid profile email", + "blank separators": " , , ", + "quoted token": `openid,"groups"`, + "backslash token": `openid,domain\groups`, + "non-ascii token": "openid,gröups", + } { + t.Run(label, func(t *testing.T) { + _, err := Load(LoadOptions{Environ: append(slices.Clone(oidcEnv), "PITOT_OIDC_SCOPES="+raw)}) + if err == nil || !strings.Contains(err.Error(), "PITOT_OIDC_SCOPES") { + t.Fatalf("Load(%q) = %v, want PITOT_OIDC_SCOPES validation error", raw, err) + } + }) + } +} diff --git a/site/src/content/docs/docs/concepts/authentication.mdx b/site/src/content/docs/docs/concepts/authentication.mdx index 4b3a2c2f..0e0e4e67 100644 --- a/site/src/content/docs/docs/concepts/authentication.mdx +++ b/site/src/content/docs/docs/concepts/authentication.mdx @@ -48,12 +48,12 @@ If neither `PITOT_OIDC_ALLOWED_GROUPS` nor `PITOT_OIDC_ALLOWED_DOMAINS` is configured, no eligibility allow policy is enforced. Membership is then managed locally, unless a role mapping is set; see [Who owns accounts](#who-owns-accounts). -Pitot requests `openid`, `profile` and `email` by default, and adds `groups` -only when a group allowlist or group role mapping is configured and the -provider's discovery metadata either advertises `groups` in `scopes_supported` -or omits `scopes_supported`. Providers that reject unknown scopes or emit group -claims from token configuration (such as Google and Microsoft Entra ID) do not -receive an unsupported `groups` scope. +Pitot requests `openid`, `profile` and `email` by default, and appends `groups` +only when a group allowlist or group role mapping is configured. Set +`PITOT_OIDC_SCOPES` (comma-separated, must include `openid`) when a provider +uses a different scope to release the `groups` claim or emits group claims from +token configuration while rejecting `scope=groups` (such as Microsoft Entra ID: +`PITOT_OIDC_SCOPES=openid,profile,email`). ### Account provisioning diff --git a/site/src/content/docs/docs/reference/configuration/auth.mdx b/site/src/content/docs/docs/reference/configuration/auth.mdx index 54b849b5..b2eaf720 100644 --- a/site/src/content/docs/docs/reference/configuration/auth.mdx +++ b/site/src/content/docs/docs/reference/configuration/auth.mdx @@ -32,6 +32,7 @@ Vendor credentials and endpoints keep the vendor's documented names. | `PITOT_OIDC_EMAIL_VERIFICATION` | string | `required` | | `PITOT_OIDC_ISSUER_URL` | string | — | | `PITOT_OIDC_OPERATOR_GROUPS` | string | — | +| `PITOT_OIDC_SCOPES` | string | — | | `PITOT_SCIM_TOKEN` or `PITOT_SCIM_TOKEN_FILE` | string · secret | — | | `PITOT_SELF_SIGNUP` | boolean | `false` | | `PITOT_SESSION_ABSOLUTE_TTL` | duration | `168h` | @@ -91,6 +92,10 @@ Selects the identity provider issuer; required in OIDC mode. Pitot starts while Lists identity-provider groups mapped to operator, separated by commas. +### `PITOT_OIDC_SCOPES` + +Overrides the OAuth 2.0 scopes requested during OIDC sign-in, separated by commas; empty requests openid, profile, and email, plus groups when a group policy is configured. + ### `PITOT_SCIM_TOKEN` Enables SCIM 2.0 user provisioning under /scim/v2 and turns off browser setup; requires OIDC mode and at least 32 characters.