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 da8222eb..93e74f64 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -256,6 +256,14 @@ 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 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 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..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: []string{oidc.ScopeOpenID, "profile", "email", "groups"}, + Scopes: scopes, }, } }, } - err := discovery.attempt(ctx) + err = discovery.attempt(ctx) if err != nil && oidcConfigurationInvalid(err) { return nil, fmt.Errorf("discover OIDC provider: %w", err) } @@ -385,9 +389,34 @@ 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. 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(explicit) != 0 { + return explicit, nil + } + scopes := []string{oidc.ScopeOpenID, "profile", "email"} + if oidcGroupPolicyConfigured(cfg) { + scopes = append(scopes, "groups") + } + return scopes, nil +} + // 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..f8919e8a 100644 --- a/internal/api/oidc_discovery_test.go +++ b/internal/api/oidc_discovery_test.go @@ -519,3 +519,96 @@ func TestOIDCDiscoveryWrongIssuerOnRetryStaysUnavailable(t *testing.T) { default: } } + +func TestOIDCStartRequestsExpectedAuthorizationScopes(t *testing.T) { + cases := []struct { + name string + cfg func(*config.Config) + scopesSupported []string + wantScope string + }{ + { + name: "google domain allowlist omits groups", + cfg: func(c *config.Config) { c.OIDCAllowedDomains = "example.com" }, + scopesSupported: []string{"openid", "email", "profile"}, + wantScope: "openid profile email", + }, + { + name: "group policy keeps groups even when omitted from scopes_supported", + cfg: func(c *config.Config) { c.OIDCAllowedGroups = "sre" }, + scopesSupported: []string{"openid", "profile", "email"}, + 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: "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", + }, + } + + 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.scopesSupported != nil { + 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) + } + }) + } + + 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 28e815c3..058f0609 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,77 @@ 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 + want []string + }{ + { + name: "no policy requests standard scopes", + cfg: config.Config{}, + want: standard, + }, + { + name: "domain allowlist omits groups", + cfg: config.Config{OIDCAllowedDomains: "example.com"}, + want: standard, + }, + { + name: "blank group lists omit groups", + cfg: config.Config{ + OIDCAllowedGroups: " , , ", + OIDCAdminGroups: " , ", + OIDCOperatorGroups: " ", + }, + want: standard, + }, + { + 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: "operator group mapping requests groups", + cfg: config.Config{OIDCOperatorGroups: "operators"}, + want: withGroups, + }, + { + name: "explicit PITOT_OIDC_SCOPES overrides group policy default", + cfg: config.Config{ + OIDCAllowedGroups: "sre", + OIDCScopes: "openid, profile, email", + }, + 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, 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 9dee0b80..0e0e4e67 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 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 `PITOT_OIDC_AUTO_PROVISION` creates eligible accounts on first sign-in after 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.