From 670f4f836dc2829b313c068805b39d883651fad3 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 2 Oct 2026 23:14:39 -0500 Subject: [PATCH] feat(auth): map verified OIDC claims to domain Identity and groups - Map verified claims to typed Identity domain model (sub, email, name) - Extract group memberships from configured claim path with fallback to empty list - Enforce identity origin integrity rejecting unvalidated request-controlled headers - Provide OIDCAuthAdapter fulfilling the AuthPort hexagonal protocol contract - Add unit and live integration test suite verifying admin and guest fixture users --- backend/app/auth/__init__.py | 2 + backend/app/auth/adapter.py | 63 ++++ backend/app/auth/oidc.py | 144 +++++++++- backend/app/config.py | 1 + backend/tests/test_identity_extraction.py | 335 ++++++++++++++++++++++ 5 files changed, 534 insertions(+), 11 deletions(-) create mode 100644 backend/app/auth/adapter.py create mode 100644 backend/tests/test_identity_extraction.py diff --git a/backend/app/auth/__init__.py b/backend/app/auth/__init__.py index 5e183f8..52d3e0e 100644 --- a/backend/app/auth/__init__.py +++ b/backend/app/auth/__init__.py @@ -1,3 +1,4 @@ +from .adapter import OIDCAuthAdapter from .identity import Identity from .oidc import ( AuthorizationRequest, @@ -26,6 +27,7 @@ __all__ = [ "InvalidStateError", "InvalidTokenError", "MismatchedNonceError", + "OIDCAuthAdapter", "OIDCClient", "OIDCConfig", "OIDCError", diff --git a/backend/app/auth/adapter.py b/backend/app/auth/adapter.py new file mode 100644 index 0000000..43400a5 --- /dev/null +++ b/backend/app/auth/adapter.py @@ -0,0 +1,63 @@ +from typing import Optional + +from fastapi import Request, Response +from fastapi.responses import RedirectResponse + +from .identity import Identity +from .oidc import OIDCClient +from .port import AuthPort + + +class OIDCAuthAdapter(AuthPort): + """Hexagonal Adapter binding generic OIDC client to the AuthPort domain contract.""" + + def __init__( + self, + oidc_client: OIDCClient, + session_cookie_name: str = "session_token", + ) -> None: + self.oidc_client = oidc_client + self.session_cookie_name = session_cookie_name + + def current_identity(self, request: Request) -> Optional[Identity]: + """Resolve the validated identity associated with the incoming request. + + Identity Origin Integrity: + Resolves identity strictly from cryptographically verified tokens (Authorization Bearer + header or session cookie). Request-controlled headers (e.g. Remote-User, X-User) are + strictly ignored to prevent identity spoofing. + """ + token: Optional[str] = None + auth_header = request.headers.get("Authorization") + if auth_header and auth_header.startswith("Bearer "): + token = auth_header[7:].strip() + elif self.session_cookie_name in request.cookies: + token = request.cookies[self.session_cookie_name] + + if not token: + return None + + try: + return self.oidc_client.extract_identity_from_token(token) + except Exception: + return None + + def login(self, request: Request) -> Response: + """Initiate the OIDC login flow with 302 redirect.""" + auth_req = self.oidc_client.create_authorization_url() + return RedirectResponse(url=auth_req.url, status_code=302) + + def logout(self, request: Request) -> Response: + """Terminate the session and redirect.""" + end_session = self.oidc_client.end_session_endpoint + target_url = end_session if end_session else "/" + response = RedirectResponse(url=target_url, status_code=302) + response.delete_cookie(self.session_cookie_name) + return response + + def extract_identity(self, claims: dict[str, object]) -> Identity: + """Delegate identity extraction from verified claims to OIDCClient.""" + return self.oidc_client.extract_identity(claims) + + +__all__ = ["OIDCAuthAdapter"] diff --git a/backend/app/auth/oidc.py b/backend/app/auth/oidc.py index 694d6f5..444bf99 100644 --- a/backend/app/auth/oidc.py +++ b/backend/app/auth/oidc.py @@ -79,6 +79,7 @@ class OIDCConfig: client_secret: Optional[str] = None redirect_uri: str = "http://localhost:8000/birthday/api/auth/callback" scopes: list[str] = field(default_factory=lambda: list(DEFAULT_SCOPES)) + groups_claim: str = "groups" def __post_init__(self) -> None: if not isinstance(self.issuer, str) or not self.issuer.strip(): @@ -87,9 +88,22 @@ class OIDCConfig: raise ValueError("OIDC client_id must be a non-empty string") if not isinstance(self.redirect_uri, str) or not self.redirect_uri.strip(): raise ValueError("OIDC redirect_uri must be a non-empty string") + if not isinstance(self.groups_claim, str) or not self.groups_claim.strip(): + raise ValueError("OIDC groups_claim must be a non-empty string") self.issuer = self.issuer.rstrip("/") +def _extract_claim_path(claims: dict[str, Any], path: str) -> Any: + """Extract claim value from dictionary supporting dot-separated paths (e.g. 'realm_access.roles').""" + current: Any = claims + for part in path.split("."): + if isinstance(current, dict): + current = current.get(part) + else: + return None + return current + + @dataclass class OIDCTransaction: """In-flight authentication transaction state.""" @@ -160,6 +174,7 @@ class OIDCClient: client_secret: Optional[str] = None, redirect_uri: Optional[str] = None, scopes: Optional[list[str]] = None, + groups_claim: Optional[str] = None, discovery_doc: Optional[dict[str, Any]] = None, timeout: float = 10.0, max_state_age_seconds: float = 600.0, @@ -175,6 +190,7 @@ class OIDCClient: client_secret=client_secret, redirect_uri=redirect_uri or "http://localhost:8000/birthday/api/auth/callback", scopes=scopes if scopes is not None else list(DEFAULT_SCOPES), + groups_claim=groups_claim or "groups", ) self.timeout = timeout @@ -407,6 +423,7 @@ class OIDCClient: state: Optional[str] = None, code_verifier: Optional[str] = None, nonce: Optional[str] = None, + extra_token_params: Optional[dict[str, str]] = None, ) -> TokenResponse: """Exchange authorization code for tokens using PKCE code_verifier and cryptographically verify ID token.""" if not code or not isinstance(code, str) or not code.strip(): @@ -437,6 +454,8 @@ class OIDCClient: "redirect_uri": self.config.redirect_uri, "code_verifier": resolved_verifier, } + if extra_token_params: + data.update(extra_token_params) auth: Optional[httpx.BasicAuth] = None if self.config.client_secret: @@ -495,25 +514,128 @@ class OIDCClient: ) def extract_identity(self, claims: dict[str, Any]) -> Identity: - """Map validated ID token claims into typed Identity domain model.""" + """Map validated ID token claims into typed Identity domain model. + + Extracts: + - sub -> Identity.subject (non-empty string required) + - email -> Identity.email (falls back to {sub}@{client_id}.local if not present) + - name -> Identity.name (optional string or None) + - groups_claim path -> Identity.groups (list of unique strings, defaults to []) + """ subject = str(claims.get("sub", "")).strip() if not subject: raise InvalidTokenError("ID token missing required 'sub' claim") - email = claims.get("email") - if not email or not str(email).strip(): + email_val = claims.get("email") + if email_val and isinstance(email_val, str) and email_val.strip(): + email = email_val.strip() + else: email = f"{subject}@{self.config.client_id}.local" - name = claims.get("name") - groups = claims.get("groups", []) - if isinstance(groups, str): - groups = [groups] - elif not isinstance(groups, (list, tuple)): + name_val = claims.get("name") + name = str(name_val).strip() if name_val and isinstance(name_val, str) and name_val.strip() else None + + raw_groups = _extract_claim_path(claims, self.config.groups_claim) + if isinstance(raw_groups, str): + groups = [raw_groups.strip()] if raw_groups.strip() else [] + elif isinstance(raw_groups, (list, tuple, set)): + groups = [str(g).strip() for g in raw_groups if isinstance(g, str) and str(g).strip()] + else: groups = [] + # Deduplicate while preserving order + unique_groups = list(dict.fromkeys(groups)) + return Identity( subject=subject, - email=str(email).strip(), - name=str(name).strip() if name else None, - groups=[str(g).strip() for g in groups if isinstance(g, str) and g.strip()], + email=email, + name=name, + groups=unique_groups, ) + + def extract_identity_from_token( + self, + id_token: str, + nonce: Optional[str] = None, + leeway: float = 60.0, + ) -> Identity: + """Cryptographically verify ID token and extract domain Identity with origin integrity.""" + claims = self.verify_id_token(id_token=id_token, nonce=nonce, leeway=leeway) + return self.extract_identity(claims) + + def authenticate_with_password( + self, + username: str, + password: str, + scopes: Optional[list[str]] = None, + ) -> tuple[TokenResponse, Identity]: + """Authenticate using resource owner password credentials against IdP and extract Identity. + + Validates returned ID token cryptographically and maps claims to domain Identity. + """ + if not username or not isinstance(username, str) or not username.strip(): + raise TokenExchangeError("Username must be a non-empty string") + if not password or not isinstance(password, str): + raise TokenExchangeError("Password must be a non-empty string") + + query_scopes = scopes if scopes is not None else self.config.scopes + data: dict[str, str] = { + "grant_type": "password", + "client_id": self.config.client_id, + "username": username, + "password": password, + "scope": " ".join(query_scopes), + } + + auth: Optional[httpx.BasicAuth] = None + if self.config.client_secret: + auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret) + data["client_secret"] = self.config.client_secret + + try: + with httpx.Client(timeout=self.timeout) as client: + if auth is not None: + response = client.post( + self.token_endpoint, + data=data, + auth=auth, + headers={"Accept": "application/json"}, + ) + else: + response = client.post( + self.token_endpoint, + data=data, + headers={"Accept": "application/json"}, + ) + except Exception as e: + raise TokenExchangeError(f"Failed to communicate with token endpoint: {e}") from e + + if response.status_code != 200: + raise TokenExchangeError( + f"Token endpoint returned HTTP {response.status_code}: {response.text}" + ) + + try: + token_data = response.json() + except Exception as e: + raise TokenExchangeError(f"Failed to parse token response JSON: {e}") from e + + if not isinstance(token_data, dict): + raise TokenExchangeError("Token response JSON root must be an object") + + id_token = token_data.get("id_token") + if not id_token or not isinstance(id_token, str): + raise TokenExchangeError("Token response missing 'id_token'") + + claims = self.verify_id_token(id_token) + token_response = TokenResponse( + id_token=id_token, + access_token=token_data.get("access_token"), + refresh_token=token_data.get("refresh_token"), + token_type=token_data.get("token_type"), + expires_in=token_data.get("expires_in"), + raw=token_data, + claims=claims, + ) + identity = self.extract_identity(claims) + return token_response, identity diff --git a/backend/app/config.py b/backend/app/config.py index 2b4a9cd..99769b4 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -14,6 +14,7 @@ class Settings(BaseSettings): OIDC_CLIENT_ID: str = "bdinvite-client" OIDC_CLIENT_SECRET: str = "bdinvite-secret" OIDC_REDIRECT_URI: str = "http://localhost:8000/birthday/api/auth/callback" + OIDC_GROUPS_CLAIM: str = "groups" model_config = SettingsConfigDict(env_file=".env", extra="ignore") diff --git a/backend/tests/test_identity_extraction.py b/backend/tests/test_identity_extraction.py new file mode 100644 index 0000000..c6b66e5 --- /dev/null +++ b/backend/tests/test_identity_extraction.py @@ -0,0 +1,335 @@ +from dataclasses import FrozenInstanceError +from typing import Optional + +from fastapi import Request, Response +from fastapi.responses import RedirectResponse +import httpx +import pytest + +from app.auth import ( + AuthPort, + Identity, + InvalidTokenError, + OIDCAuthAdapter, + OIDCClient, + OIDCConfig, + TokenExchangeError, +) + +LIVE_ISSUER = "http://localhost:8088/default" +CLIENT_ID = "bdinvite-client" +CLIENT_SECRET = "bdinvite-secret" +REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback" + + +@pytest.fixture +def oidc_client() -> OIDCClient: + return OIDCClient( + issuer=LIVE_ISSUER, + client_id=CLIENT_ID, + client_secret=CLIENT_SECRET, + redirect_uri=REDIRECT_URI, + groups_claim="groups", + ) + + +def create_dummy_request( + headers: Optional[dict[str, str]] = None, + cookies: Optional[dict[str, str]] = None, +) -> Request: + raw_headers = [ + (k.lower().encode("latin-1"), v.encode("latin-1")) + for k, v in (headers or {}).items() + ] + if cookies: + cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items()) + raw_headers.append((b"cookie", cookie_header.encode("latin-1"))) + + scope = { + "type": "http", + "method": "GET", + "path": "/birthday/api/admin/rsvps", + "headers": raw_headers, + } + return Request(scope) + + +# ============================================================================== +# 1. Identity Resolution & Mapping Unit Tests +# ============================================================================== + + +def test_identity_resolution_standard_claims(oidc_client: OIDCClient): + """Standard identity claims (sub, email, name, groups) map correctly to Identity domain model.""" + claims = { + "sub": "user-42", + "email": "user42@example.com", + "name": "Douglas Adams", + "groups": ["author", "scifi"], + } + identity = oidc_client.extract_identity(claims) + + assert isinstance(identity, Identity) + assert identity.subject == "user-42" + assert identity.email == "user42@example.com" + assert identity.name == "Douglas Adams" + assert identity.groups == ["author", "scifi"] + assert identity.has_group("author") is True + assert identity.has_group("nonexistent") is False + + +def test_identity_resolution_missing_email_and_name_defaults(oidc_client: OIDCClient): + """Missing email falls back to synthetic local address, and missing name defaults to None.""" + claims = { + "sub": "svc-worker-99", + } + identity = oidc_client.extract_identity(claims) + + assert identity.subject == "svc-worker-99" + assert identity.email == f"svc-worker-99@{CLIENT_ID}.local" + assert identity.name is None + assert identity.groups == [] + + +def test_identity_resolution_missing_subject_raises_invalid_token(oidc_client: OIDCClient): + """Missing or empty sub claim raises InvalidTokenError.""" + with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"): + oidc_client.extract_identity({}) + + with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"): + oidc_client.extract_identity({"sub": " ", "email": "valid@example.com"}) + + +def test_identity_groups_extraction_clean_defaults(oidc_client: OIDCClient): + """Missing, None, non-list, or empty groups claim cleanly defaults to empty list.""" + # Missing groups key + assert oidc_client.extract_identity({"sub": "u1"}).groups == [] + + # None value + assert oidc_client.extract_identity({"sub": "u1", "groups": None}).groups == [] + + # Empty list + assert oidc_client.extract_identity({"sub": "u1", "groups": []}).groups == [] + + # Single string group + assert oidc_client.extract_identity({"sub": "u1", "groups": "single_role"}).groups == ["single_role"] + + # Tuple / Set collections + assert oidc_client.extract_identity({"sub": "u1", "groups": ("admin", "editor")}).groups == ["admin", "editor"] + + # Discard non-string, empty strings, and trim whitespace + claims = {"sub": "u1", "groups": [" admin ", "", " ", 123, None, "editor"]} + assert oidc_client.extract_identity(claims).groups == ["admin", "editor"] + + # Deduplicate while preserving order + claims_dup = {"sub": "u1", "groups": ["alpha", "beta", "alpha", "gamma", "beta"]} + assert oidc_client.extract_identity(claims_dup).groups == ["alpha", "beta", "gamma"] + + +def test_identity_groups_configurable_claim_path(): + """Group extraction respects configured group claim path, including nested paths.""" + # Custom top-level path + custom_client = OIDCClient( + issuer=LIVE_ISSUER, + client_id=CLIENT_ID, + groups_claim="roles", + ) + claims = {"sub": "u1", "roles": ["superadmin", "operator"], "groups": ["ignored"]} + assert custom_client.extract_identity(claims).groups == ["superadmin", "operator"] + + # Nested path (e.g. Keycloak realm_access.roles) + nested_client = OIDCClient( + issuer=LIVE_ISSUER, + client_id=CLIENT_ID, + groups_claim="realm_access.roles", + ) + claims_nested = { + "sub": "u1", + "realm_access": {"roles": ["app_admin", "user"]}, + } + assert nested_client.extract_identity(claims_nested).groups == ["app_admin", "user"] + + # Nested path missing + assert nested_client.extract_identity({"sub": "u1", "realm_access": {}}).groups == [] + assert nested_client.extract_identity({"sub": "u1"}).groups == [] + + +# ============================================================================== +# 2. Seeded Fixture Users Verification (Live Integration) +# ============================================================================== + + +def test_live_fixture_admin_user_authentication(oidc_client: OIDCClient): + """Authenticating with admin@example.com resolves to Identity with bdinvite_admins group.""" + token_resp, identity = oidc_client.authenticate_with_password( + username="admin@example.com", + password="password123", + scopes=["openid", "profile", "email"], + ) + + assert isinstance(identity, Identity) + assert identity.subject == "admin-001" + assert identity.email == "admin@example.com" + assert identity.name == "Admin User" + assert identity.groups == ["bdinvite_admins"] + assert identity.has_group("bdinvite_admins") is True + assert identity.has_group("guests") is False + + # Verify ID token claims match domain model + assert token_resp.claims["sub"] == "admin-001" + assert token_resp.claims["email"] == "admin@example.com" + assert token_resp.claims["groups"] == ["bdinvite_admins"] + + +def test_live_fixture_guest_user_authentication(oidc_client: OIDCClient): + """Authenticating with guest@example.com resolves to Identity with guests group.""" + token_resp, identity = oidc_client.authenticate_with_password( + username="guest@example.com", + password="password123", + scopes=["openid", "profile", "email"], + ) + + assert isinstance(identity, Identity) + assert identity.subject == "guest-001" + assert identity.email == "guest@example.com" + assert identity.name == "Guest User" + assert identity.groups == ["guests"] + assert identity.has_group("guests") is True + assert identity.has_group("bdinvite_admins") is False + + # Verify ID token claims match domain model + assert token_resp.claims["sub"] == "guest-001" + assert token_resp.claims["email"] == "guest@example.com" + assert token_resp.claims["groups"] == ["guests"] + + +# ============================================================================== +# 3. Identity Origin Integrity & Immutability Tests +# ============================================================================== + + +def test_identity_origin_integrity_rejection_of_unvalidated_request_headers(oidc_client: OIDCClient): + """Application adapter rejects constructing Identity from raw request headers or client data.""" + adapter = OIDCAuthAdapter(oidc_client=oidc_client) + + # Attacker passes spoofed Remote-User or X-User headers + spoofed_request = create_dummy_request( + headers={ + "Remote-User": "admin@example.com", + "Remote-Groups": "bdinvite_admins", + "X-Forwarded-User": "admin-001", + } + ) + + # Adapter must strictly refuse to manufacture an Identity from unvalidated request headers + resolved = adapter.current_identity(spoofed_request) + assert resolved is None + + +def test_identity_origin_integrity_rejection_of_tampered_token(oidc_client: OIDCClient): + """Identity cannot be extracted from a tampered or forged token.""" + # Obtain a genuine token for admin + token_resp, _ = oidc_client.authenticate_with_password( + username="admin@example.com", + password="password123", + ) + valid_id_token = token_resp.id_token + + # Case 1: Tampered signature + tampered_sig_token = valid_id_token[:-10] + "FORGED_SIG" + with pytest.raises(InvalidTokenError): + oidc_client.extract_identity_from_token(tampered_sig_token) + + # Case 2: Adapter with tampered token in Authorization header returns None + bad_request = create_dummy_request(headers={"Authorization": f"Bearer {tampered_sig_token}"}) + adapter = OIDCAuthAdapter(oidc_client=oidc_client) + assert adapter.current_identity(bad_request) is None + + +def test_identity_immutability(): + """Identity instance is frozen and cannot be mutated after creation.""" + identity = Identity( + subject="admin-001", + email="admin@example.com", + name="Admin User", + groups=["bdinvite_admins"], + ) + + with pytest.raises(FrozenInstanceError): + identity.groups = ["guests"] # type: ignore[misc] + + with pytest.raises(FrozenInstanceError): + identity.subject = "hacked-sub" # type: ignore[misc] + + with pytest.raises(FrozenInstanceError): + identity.email = "hacked@example.com" # type: ignore[misc] + + +# ============================================================================== +# 4. AuthPort Protocol Conformance & Adapter Tests +# ============================================================================== + + +def test_oidc_auth_adapter_conforms_to_auth_port(oidc_client: OIDCClient): + """OIDCAuthAdapter satisfies the AuthPort protocol runtime contract.""" + adapter = OIDCAuthAdapter(oidc_client=oidc_client) + assert isinstance(adapter, AuthPort) + + +def test_oidc_auth_adapter_current_identity_with_valid_bearer(oidc_client: OIDCClient): + """OIDCAuthAdapter extracts valid Identity from Authorization: Bearer token.""" + token_resp, expected_identity = oidc_client.authenticate_with_password( + username="admin@example.com", + password="password123", + ) + + adapter = OIDCAuthAdapter(oidc_client=oidc_client) + req = create_dummy_request(headers={"Authorization": f"Bearer {token_resp.id_token}"}) + + resolved = adapter.current_identity(req) + assert resolved == expected_identity + assert resolved is not None + assert resolved.subject == "admin-001" + assert resolved.has_group("bdinvite_admins") is True + + +def test_oidc_auth_adapter_current_identity_with_valid_cookie(oidc_client: OIDCClient): + """OIDCAuthAdapter extracts valid Identity from session cookie.""" + token_resp, expected_identity = oidc_client.authenticate_with_password( + username="guest@example.com", + password="password123", + ) + + adapter = OIDCAuthAdapter(oidc_client=oidc_client, session_cookie_name="bdinvite_session") + req = create_dummy_request(cookies={"bdinvite_session": token_resp.id_token}) + + resolved = adapter.current_identity(req) + assert resolved == expected_identity + assert resolved is not None + assert resolved.subject == "guest-001" + assert resolved.has_group("guests") is True + + +def test_oidc_auth_adapter_login_redirect(oidc_client: OIDCClient): + """OIDCAuthAdapter login returns 302 redirect to OIDC authorization endpoint.""" + adapter = OIDCAuthAdapter(oidc_client=oidc_client) + req = create_dummy_request() + + response = adapter.login(req) + assert isinstance(response, Response) + assert response.status_code == 302 + assert "location" in response.headers + assert response.headers["location"].startswith(f"{LIVE_ISSUER}/authorize?") + + +def test_oidc_auth_adapter_logout_redirect_and_clears_cookie(oidc_client: OIDCClient): + """OIDCAuthAdapter logout returns 302 redirect and deletes the session cookie.""" + adapter = OIDCAuthAdapter(oidc_client=oidc_client, session_cookie_name="bdinvite_session") + req = create_dummy_request() + + response = adapter.logout(req) + assert isinstance(response, Response) + assert response.status_code == 302 + # Verify cookie deletion header exists + assert "set-cookie" in response.headers + assert "bdinvite_session" in response.headers["set-cookie"]