Files
certctl/internal/auth/oidc/groupclaim/resolver.go
T
shankar0123 854135dfb7 auth-bundle-2 Phase 3: OIDC service (HandleAuthRequest, HandleCallback,
RefreshKeys), hand-rolled group-claim resolver, 21+ negative-test
matrix, token-leak hygiene, IdP downgrade-attack defense

Phase 3 of the bundle ships the business logic that turns the Phase 2
storage primitives into a working OpenID Connect 1.0 + RFC 7636 PKCE
authorization-code flow against any enterprise IdP (Okta / Azure AD /
Google Workspace / Keycloak / Authentik / Auth0).

Service surface:

  - Service.HandleAuthRequest(providerID) -> authURL, cookie, preLoginID
    Builds the IdP redirect with PKCE-S256 (mandatory; RFC 9700 §2.1.1),
    server-generated 32-byte state + nonce, persisted to the pre-login
    row keyed by the cookie value.
  - Service.HandleCallback(cookie, code, state, ip, ua) -> *CallbackResult
    11-step validation: pre-login lookup-and-consume (single-use),
    constant-time state compare, code-for-token exchange with PKCE
    verifier, ID-token verify (alg pin via go-oidc/v3), service-layer
    re-checks of iss / aud / azp (multi-aud requires it; mismatch
    rejected) / at_hash (REQUIRED when access_token returned —
    Phase 3 lifts the OIDC core "MAY" to a service-level "MUST") /
    exp / iat-window / nonce, group-claim resolution with userinfo
    fallback, group->role mapping (fail-closed on no match),
    user upsert, session mint via SessionMinter port.
  - Service.RefreshKeys(providerID) — explicit cache eviction +
    re-load. Re-runs the IdP downgrade-attack defense so a provider
    that later rotates to advertising HS* / none is caught BEFORE the
    next user login attempt.

Security posture (every fail-closed branch is a sentinel error +
test):

  - Algorithm pinning: allow-list {RS256, RS512, ES256, ES384, EdDSA};
    deny-list {HS256, HS384, HS512, none}. Belt-and-braces re-check
    via isDisallowedAlg after go-oidc.Verify.
  - PKCE-S256 mandatory (oauth2.GenerateVerifier + S256ChallengeOption);
    `plain` rejection sentinel exists for defense-in-depth.
  - State + nonce: 32-byte crypto/rand, base64url-no-pad,
    constant-time compare, single-use.
  - IdP downgrade-attack defense: at provider creation / RefreshKeys,
    reject any IdP whose discovery doc advertises HS* / none in
    id_token_signing_alg_values_supported.
  - JWKS fail-closed: in-flight login fails 503; existing sessions
    untouched. isJWKSFetchError detects the gooidc verify-error
    shape; ErrJWKSUnreachable is the wire mapping.
  - Token-leak hygiene: ID tokens, access tokens, refresh tokens,
    authorization codes, PKCE verifiers, state, nonce, signing key
    bytes — NEVER logged at any level. logging_test.go pins the
    invariant via a slog buffer + grep-assert across HandleAuthRequest,
    HandleCallback, alg rejection, and provider-load paths.

Group-claim resolver (internal/auth/oidc/groupclaim/):

  - Hand-rolled per Decision 10 (no JSON-path lib; ~150 LOC).
  - URL-shape paths (https:// / http://) treated as a single
    literal key — Auth0 namespaced claims like
    https://your-namespace/groups work without splitting on the
    dots in the URL.
  - Dot-separated paths walked through nested map[string]interface{}.
  - []interface{} / []string / single-string normalized to []string;
    bool / number / object / nil → fail closed.
  - 18 unit tests + sentinels (ErrPathEmpty, ErrSegmentMissing,
    ErrSegmentNotObject, ErrInvalidValueType).

Test surface:

  - service_test.go: 57 test functions including all 21 prompt-mandated
    negative cases (wrong aud / wrong iss / expired / unknown alg /
    alg=none / HMAC alg / azp missing on multi-aud / azp mismatched /
    at_hash missing / at_hash mismatched / iat in future / iat too old /
    nonce mismatched / state mismatched / state replayed / PKCE plain
    sentinel / pre-login replay / forged cookie / IdP downgrade /
    group-claim missing / group-claim unmapped) plus the userinfo
    fallback matrix (happy path + endpoint-missing + endpoint-failing +
    userinfo-also-empty), HandleAuthRequest entry point + RNG-failure
    paths, upsertUser update + create + display-name fallback +
    Validate-error paths, decryptClientSecret real-encrypt round-trip
    + bad-passphrase, alg-parser malformed-header matrix.
  - logging_test.go: 4 hygiene tests pinning no token / code / verifier /
    state / cookie / client_secret / alg name appears in any captured
    log line.
  - groupclaim/resolver_test.go: 18 cases covering Okta string-array,
    Keycloak realm_access.roles, Auth0 namespaced URL claim,
    single-string normalization, deeply-nested 3-segment walks, and
    every fail-closed branch.

Coverage:
  internal/auth/oidc                  92.2%  (floor: 90)
  internal/auth/oidc/groupclaim      100.0%  (floor: 95)
  internal/auth/oidc/domain           96.2%  (floor: 90)

Coverage gates added at .github/coverage-thresholds.yml so a future
regression in any fail-closed branch fails CI before the commit lands.

Phase 3 of cowork/auth-bundle-2-prompt.md is closed. Next up: Phase 4
(Session service: cookies, revocation, sliding-vs-absolute expiry).
2026-05-10 04:56:03 +00:00

143 lines
5.3 KiB
Go

// Package groupclaim resolves the operator-configured `groups_claim_path`
// against an ID token's parsed claims, returning the user's group
// membership as a `[]string`.
//
// Auth Bundle 2 Phase 3 ships this without a JSON-path library
// dependency per the pre-bundle dep audit. The contract is narrow
// enough that ~40 LOC of straight Go covers every documented use case
// (Keycloak, Auth0, Okta, Azure AD, Google Workspace) without the
// transitive footprint or maintenance liability of pulling in
// PaesslerAG/jsonpath, ohler55/ojg, or tidwall/gjson.
//
// Resolution rules:
//
// 1. URL-shape paths (prefix `https://` or `http://`) are treated as a
// single literal key. This handles Auth0's namespaced claims like
// `https://your-namespace/groups`.
// 2. Dot-separated paths (e.g. Keycloak's `realm_access.roles`) are
// split on `.` and walked through nested `map[string]interface{}`
// chains. A non-object segment or missing key fails closed with a
// clear error.
// 3. The resolved value is coerced to `[]string`:
// - `[]string` → as-is.
// - `[]interface{}` of strings → coerced.
// - single `string` → wrapped in a one-element slice.
// - any other type (bool, number, object, nil) → fails closed.
//
// Phase 3 callers MUST treat the empty-result case as fail-closed: no
// session is minted, an audit row records `auth.oidc_login_unmapped_groups`
// (the user's IdP returned a claim but it didn't match any of the
// operator's mappings).
package groupclaim
import (
"errors"
"fmt"
"strings"
)
// Sentinel errors. Service-layer callers branch on these via errors.Is.
var (
// ErrPathEmpty is returned when the configured path is the empty
// string. The operator API layer + domain Validate() catch this
// upstream; this sentinel exists so the resolver is safe to call
// even with malformed config.
ErrPathEmpty = errors.New("groupclaim: path is empty")
// ErrSegmentMissing is returned when a path segment doesn't exist
// on the current claims object (e.g. path `realm_access.roles`
// applied to a token without `realm_access`). Phase 3's
// HandleCallback maps to "no groups; fail closed".
ErrSegmentMissing = errors.New("groupclaim: path segment missing")
// ErrSegmentNotObject is returned when an intermediate path
// segment resolves to a non-object (e.g. trying to walk into a
// string). Indicates the IdP token shape doesn't match the
// operator's configured path.
ErrSegmentNotObject = errors.New("groupclaim: intermediate segment is not an object")
// ErrInvalidValueType is returned when the resolved value cannot
// be coerced to a string array. Bool, number, object, nil all
// fail closed.
ErrInvalidValueType = errors.New("groupclaim: resolved value is not coercible to []string")
)
// Resolve walks `path` through `claims` and returns the resolved
// group list. See the package doc for the full contract.
//
// Per Phase 3's "complete path, not easy path" discipline: this
// function does NOT modify `claims` and does NOT log any of its
// inputs. Token-leak hygiene tests assert that paths through this
// function never emit any of `claims`, `path`, or the resolved
// value to the slog buffer.
func Resolve(claims map[string]interface{}, path string) ([]string, error) {
if path == "" {
return nil, ErrPathEmpty
}
// Rule 1: URL-shape paths are single literal keys.
var segments []string
if isURLShapePath(path) {
segments = []string{path}
} else {
segments = strings.Split(path, ".")
}
// Walk the segments through the nested map.
var cur interface{} = claims
for i, seg := range segments {
obj, ok := cur.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%w: segment %q (index %d) applied to non-object", ErrSegmentNotObject, seg, i)
}
next, ok := obj[seg]
if !ok {
return nil, fmt.Errorf("%w: %q at index %d", ErrSegmentMissing, seg, i)
}
cur = next
}
// Coerce the resolved value to []string.
return coerceStringArray(cur)
}
// isURLShapePath reports whether path is a URL-shape (Auth0-style
// namespaced claim). Such paths are NOT split on `.`; they're treated
// as a single literal key against the top-level claims map.
func isURLShapePath(path string) bool {
return strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://")
}
// coerceStringArray converts the resolved claim value to []string per
// the rules in the package doc. Fails closed on any other type.
func coerceStringArray(v interface{}) ([]string, error) {
switch x := v.(type) {
case []string:
// Already the right type. Return a copy so the caller can't
// mutate the underlying claims map by surprise.
out := make([]string, len(x))
copy(out, x)
return out, nil
case []interface{}:
// JSON unmarshal into map[string]interface{} produces
// []interface{} for arrays. Coerce each element to string;
// any non-string element fails the whole resolution.
out := make([]string, 0, len(x))
for i, e := range x {
s, ok := e.(string)
if !ok {
return nil, fmt.Errorf("%w: element %d is %T not string", ErrInvalidValueType, i, e)
}
out = append(out, s)
}
return out, nil
case string:
// Single string: wrap in a one-element slice. Some IdPs
// return a single role as a bare string rather than a
// one-element array; the resolver normalizes both shapes.
return []string{x}, nil
default:
return nil, fmt.Errorf("%w: got %T", ErrInvalidValueType, v)
}
}