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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 32 additions & 3 deletions internal/api/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}),
Expand All @@ -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)
}
Expand Down Expand Up @@ -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
Expand Down
93 changes: 93 additions & 0 deletions internal/api/oidc_discovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
})
}
75 changes: 75 additions & 0 deletions internal/api/oidc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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)
}
})
}
}
49 changes: 47 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net"
"net/url"
"path/filepath"
"slices"
"strings"
"time"
"unicode"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading