mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-11 21:28:52 +00:00
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).
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package groupclaim
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Happy-path tests covering the documented IdP shapes.
|
||||
// =============================================================================
|
||||
|
||||
// TestResolve_OktaStyleStringArray pins the most common shape:
|
||||
// {"groups": ["engineers", "platform-admins"]}.
|
||||
func TestResolve_OktaStyleStringArray(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"groups": []interface{}{"engineers", "platform-admins"},
|
||||
}
|
||||
got, err := Resolve(claims, "groups")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
want := []string{"engineers", "platform-admins"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_KeycloakNestedRoles pins the dot-path walk:
|
||||
// {"realm_access": {"roles": ["admin", "user"]}}.
|
||||
func TestResolve_KeycloakNestedRoles(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"realm_access": map[string]interface{}{
|
||||
"roles": []interface{}{"admin", "user"},
|
||||
},
|
||||
}
|
||||
got, err := Resolve(claims, "realm_access.roles")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
want := []string{"admin", "user"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_Auth0NamespacedClaim pins the URL-shape literal-key path:
|
||||
// {"https://your-namespace/groups": ["engineers"]}.
|
||||
func TestResolve_Auth0NamespacedClaim(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"https://your-namespace/groups": []interface{}{"engineers"},
|
||||
}
|
||||
got, err := Resolve(claims, "https://your-namespace/groups")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
want := []string{"engineers"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_HTTPSchemeAlsoTreatedAsLiteral pins that http:// (not just
|
||||
// https://) triggers the URL-shape path treatment. Some on-prem IdPs
|
||||
// use http for namespaced claims in dev environments.
|
||||
func TestResolve_HTTPSchemeAlsoTreatedAsLiteral(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"http://internal.example.com/groups": []interface{}{"role-a"},
|
||||
}
|
||||
got, err := Resolve(claims, "http://internal.example.com/groups")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0] != "role-a" {
|
||||
t.Errorf("got %v, want [role-a]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_SingleStringWrapped pins the normalization: some IdPs
|
||||
// return a single role as a bare string rather than a one-element
|
||||
// array. The resolver wraps it.
|
||||
func TestResolve_SingleStringWrapped(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"role": "admin",
|
||||
}
|
||||
got, err := Resolve(claims, "role")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
want := []string{"admin"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_AlreadyStringSlice covers the rare case where a caller
|
||||
// pre-coerced []interface{} to []string. The resolver returns a copy.
|
||||
func TestResolve_AlreadyStringSlice(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"groups": []string{"a", "b"},
|
||||
}
|
||||
got, err := Resolve(claims, "groups")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, []string{"a", "b"}) {
|
||||
t.Errorf("got %v, want [a b]", got)
|
||||
}
|
||||
// Mutating the result must NOT mutate the input claim.
|
||||
got[0] = "MUTATED"
|
||||
if claims["groups"].([]string)[0] == "MUTATED" {
|
||||
t.Errorf("Resolve returned a slice aliased to the input; mutation leaked back")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_EmptyArrayReturnsEmpty pins the documented edge: an IdP
|
||||
// that returns an empty groups claim is NOT a resolver error; the
|
||||
// caller (Phase 3 service) decides fail-closed semantics.
|
||||
func TestResolve_EmptyArrayReturnsEmpty(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"groups": []interface{}{},
|
||||
}
|
||||
got, err := Resolve(claims, "groups")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Errorf("got %v, want []", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_DeeplyNestedPath pins a 3-segment walk works.
|
||||
func TestResolve_DeeplyNestedPath(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"a": map[string]interface{}{
|
||||
"b": map[string]interface{}{
|
||||
"c": []interface{}{"deep"},
|
||||
},
|
||||
},
|
||||
}
|
||||
got, err := Resolve(claims, "a.b.c")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0] != "deep" {
|
||||
t.Errorf("got %v, want [deep]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Negative paths — every fail-closed branch.
|
||||
// =============================================================================
|
||||
|
||||
func TestResolve_EmptyPathRejected(t *testing.T) {
|
||||
_, err := Resolve(map[string]interface{}{"groups": []interface{}{"x"}}, "")
|
||||
if !errors.Is(err, ErrPathEmpty) {
|
||||
t.Errorf("err = %v; want ErrPathEmpty", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_MissingKeyRejected(t *testing.T) {
|
||||
claims := map[string]interface{}{"other": "thing"}
|
||||
_, err := Resolve(claims, "groups")
|
||||
if !errors.Is(err, ErrSegmentMissing) {
|
||||
t.Errorf("err = %v; want ErrSegmentMissing", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_MissingNestedKeyRejected(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"realm_access": map[string]interface{}{"other": "thing"},
|
||||
}
|
||||
_, err := Resolve(claims, "realm_access.roles")
|
||||
if !errors.Is(err, ErrSegmentMissing) {
|
||||
t.Errorf("err = %v; want ErrSegmentMissing", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_NonObjectIntermediateRejected(t *testing.T) {
|
||||
// "realm_access" resolves to a string, not an object; can't walk
|
||||
// further into it.
|
||||
claims := map[string]interface{}{
|
||||
"realm_access": "not-an-object",
|
||||
}
|
||||
_, err := Resolve(claims, "realm_access.roles")
|
||||
if !errors.Is(err, ErrSegmentNotObject) {
|
||||
t.Errorf("err = %v; want ErrSegmentNotObject", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_RejectsBoolValue(t *testing.T) {
|
||||
claims := map[string]interface{}{"groups": true}
|
||||
_, err := Resolve(claims, "groups")
|
||||
if !errors.Is(err, ErrInvalidValueType) {
|
||||
t.Errorf("err = %v; want ErrInvalidValueType", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_RejectsNumberValue(t *testing.T) {
|
||||
claims := map[string]interface{}{"groups": 42}
|
||||
_, err := Resolve(claims, "groups")
|
||||
if !errors.Is(err, ErrInvalidValueType) {
|
||||
t.Errorf("err = %v; want ErrInvalidValueType", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_RejectsObjectValue(t *testing.T) {
|
||||
claims := map[string]interface{}{"groups": map[string]interface{}{"x": "y"}}
|
||||
_, err := Resolve(claims, "groups")
|
||||
if !errors.Is(err, ErrInvalidValueType) {
|
||||
t.Errorf("err = %v; want ErrInvalidValueType", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_RejectsNilValue(t *testing.T) {
|
||||
claims := map[string]interface{}{"groups": nil}
|
||||
_, err := Resolve(claims, "groups")
|
||||
if !errors.Is(err, ErrInvalidValueType) {
|
||||
t.Errorf("err = %v; want ErrInvalidValueType", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve_RejectsArrayWithNonStringElement(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"groups": []interface{}{"a", 42, "c"}, // 42 is not a string
|
||||
}
|
||||
_, err := Resolve(claims, "groups")
|
||||
if !errors.Is(err, ErrInvalidValueType) {
|
||||
t.Errorf("err = %v; want ErrInvalidValueType", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolve_URLShapeWithDotsInPathTreatedAsLiteral pins the
|
||||
// disambiguation: a URL-shape path like
|
||||
// `https://example.com/team.id` must NOT be split on the dot in
|
||||
// "team.id"; it's a single literal key.
|
||||
func TestResolve_URLShapeWithDotsInPathTreatedAsLiteral(t *testing.T) {
|
||||
claims := map[string]interface{}{
|
||||
"https://example.com/team.id": []interface{}{"sales"},
|
||||
}
|
||||
got, err := Resolve(claims, "https://example.com/team.id")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0] != "sales" {
|
||||
t.Errorf("got %v, want [sales]", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user