OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: issue #70873 jwt token signature validation (#2076)
rodageve7fb88fdbd1cf
diff --git a/src/config/settings.py b/src/config/settings.pyindex 42bbfcec5..238153a25 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -16,7 +16,7 @@ from config.embedding_constants import OPENAI_DEFAULT_EMBEDDING_MODELfrom config.paths import get_flows_pathfrom utils.container_utils import determine_docling_host, get_container_hostfrom utils.embedding_fields import build_knn_vector_field-from utils.env_utils import get_env_float, get_env_int+from utils.env_utils import get_env_float, get_env_int, get_env_setfrom utils.logging_config import get_logger# Import configuration manager@@ -186,7 +186,13 @@ SESSION_SECRET = os.getenv("SESSION_SECRET") or "your-secret-key-change-in-produ# os.environ directly.JWT_SIGNING_KEY = os.getenv("JWT_SIGNING_KEY")GOOGLE_OAUTH_CLIENT_ID = os.getenv("GOOGLE_OAUTH_CLIENT_ID")+MICROSOFT_GRAPH_OAUTH_CLIENT_ID = os.getenv("MICROSOFT_GRAPH_OAUTH_CLIENT_ID")+MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET = os.getenv("MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET")GOOGLE_OAUTH_CLIENT_SECRET = os.getenv("GOOGLE_OAUTH_CLIENT_SECRET")+# Optional comma-separated list of Azure AD tenant UUIDs. When set, tokens from+# tenants not in this list are rejected (business policy, not a standards requirement).+# When unset, any tenant whose token passes signature/audience/expiry checks is accepted.+MICROSOFT_ALLOWED_TENANT_IDS: set[str] | None = get_env_set("MICROSOFT_ALLOWED_TENANT_IDS")# IBM AMS authentication (Watsonx Data embedded mode)IBM_AUTH_ENABLED = os.getenv("IBM_AUTH_ENABLED", "false").lower() in ("true", "1", "yes")diff --git a/src/config/utils.py b/src/config/utils.pyindex c2baad6e8..c9c06960a 100644--- a/src/config/utils.py+++ b/src/config/utils.py@@ -61,11 +61,17 @@ def get_public_key_from_issuer(cache_key = f"{issuer}#{key_id or ''}"cached = _ISSUER_PUBLIC_KEY_CACHE.get(cache_key)if cached is not None:+ logger.debug("Public key cache hit", issuer=issuer, key_id=key_id)return cached- with httpx.Client(verify=verify_tls, timeout=timeout) as client:- response = client.get(issuer)- response.raise_for_status()+ logger.debug("Fetching public key from issuer", issuer=issuer)+ try:+ with httpx.Client(verify=verify_tls, timeout=timeout) as client:+ response = client.get(issuer)+ response.raise_for_status()+ except (httpx.HTTPError, ValueError) as exc:+ logger.error("Failed to fetch public key from issuer", issuer=issuer, error=str(exc))+ raisecontent_type = response.headers.get("content-type", "")if "json" in content_type:@@ -78,6 +84,7 @@ def get_public_key_from_issuer(public_key = _load_public_key_from_payload(key_payload, key_id)_ISSUER_PUBLIC_KEY_CACHE[cache_key] = public_key+ logger.debug("Public key cached", issuer=issuer, key_id=key_id)return public_key@@ -146,9 +153,23 @@ def verify_jwt_from_issuer(else:decode_kwargs["audience"] = audience- return jwt.decode(raw_token, public_key, **decode_kwargs)+ claims = jwt.decode(raw_token, public_key, **decode_kwargs)+ logger.debug("JWT verified successfully", issuer=issuer, sub=claims.get("sub"))+ return claims+ except jwt.ExpiredSignatureError as e:+ logger.warning("JWT has expired", error=str(e), issuer=issuer)+ return None+ except jwt.InvalidSignatureError as e:+ logger.warning("JWT has invalid signature", error=str(e), issuer=issuer)+ return None+ except jwt.InvalidIssuerError as e:+ logger.warning("JWT has invalid issuer", error=str(e), issuer=issuer)+ return None+ except jwt.InvalidAudienceError as e:+ logger.warning("JWT has invalid audience", error=str(e), issuer=issuer)+ return Noneexcept (ValueError, httpx.HTTPError, jwt.InvalidTokenError) as e:- logger.debug(+ logger.warning("JWT verification failed",error=str(e),error_type=type(e).__name__,diff --git a/src/connectors/google_drive/oauth.py b/src/connectors/google_drive/oauth.pyindex 1054f25ca..c440abf13 100644--- a/src/connectors/google_drive/oauth.py+++ b/src/connectors/google_drive/oauth.py@@ -12,6 +12,33 @@ from utils.logging_config import get_loggerlogger = get_logger(__name__)++def _verify_id_token(id_token: str | None) -> dict | None:+ """+ Verify Google ID token signature, expiry, audience, and issuer.++ Returns the verified claims dict on success.+ Raises JWTVerificationError (or a subclass) if verification fails — callers+ must NOT proceed with credentials that carry an invalid ID token.+ Returns None only when no id_token is present or verification is not configured.+ """+ if not id_token:+ return None++ from config.settings import GOOGLE_OAUTH_CLIENT_ID+ from utils.jwt_verification import verify_google_id_token++ if not GOOGLE_OAUTH_CLIENT_ID:+ logger.warning("GOOGLE_OAUTH_CLIENT_ID not configured - skipping ID token verification")+ return None++ # Raises JWTVerificationError on any failure — intentionally not caught here+ # so that callers propagate the error and refuse to use invalid credentials.+ claims = verify_google_id_token(id_token, GOOGLE_OAUTH_CLIENT_ID)+ logger.debug("Google ID token verified, sub=%s", claims.get("sub"))+ return claims++_REFRESH_TIMEOUT_SECONDS = 30@@ -216,6 +243,11 @@ class GoogleDriveOAuth:self.creds = self._flow.credentialslogger.debug("[GoogleDrive] handle_authorization_callback: token exchange complete")+ # Verify the ID token immediately after code exchange. Raises JWTVerificationError+ # on failure — the connection is rejected before credentials are persisted.+ if self.creds and self.creds.id_token:+ _verify_id_token(self.creds.id_token)+await self.save_credentials()return Truediff --git a/src/connectors/microsoft_oauth_utils.py b/src/connectors/microsoft_oauth_utils.pynew file mode 100644index 000000000..34140038c--- /dev/null+++ b/src/connectors/microsoft_oauth_utils.py@@ -0,0 +1,54 @@+"""Shared Microsoft OAuth utilities used by both SharePoint and OneDrive connectors."""++from __future__ import annotations++import jwt++from utils.logging_config import get_logger++logger = get_logger(__name__)+++def verify_ms_access_token(access_token: str | None, tenant_id: str | None = None) -> dict | None:+ """Verify a Microsoft access token obtained via MSAL.++ Returns the verified claims dict on success.+ Returns None when no token is present, verification is not configured, or the+ token is opaque (not a JWT) — MSAL sometimes issues opaque tokens for Graph+ resources; those are trusted by virtue of the confidential-client OAuth flow.+ Raises JWTVerificationError (or a subclass) when the token IS a JWT but fails+ signature, expiry, audience, or issuer validation.+ """+ if not access_token:+ return None++ raw_token = access_token.removeprefix("Bearer ").strip()++ # MSAL can return opaque (non-JWT) tokens for some resources (e.g. Graph).+ # PyJWT raises DecodeError("Not enough segments") for these — they are trusted+ # by the confidential-client OAuth flow, so skip verification silently.+ try:+ jwt.get_unverified_header(raw_token)+ except jwt.DecodeError:+ logger.debug("Microsoft access token is opaque (non-JWT) — skipping verification")+ return None++ from config.settings import MICROSOFT_ALLOWED_TENANT_IDS, MICROSOFT_GRAPH_OAUTH_CLIENT_ID+ from utils.jwt_verification import verify_microsoft_access_token++ if not MICROSOFT_GRAPH_OAUTH_CLIENT_ID:+ logger.warning(+ "MICROSOFT_GRAPH_OAUTH_CLIENT_ID not configured - skipping access token verification"+ )+ return None++ # Raises JWTVerificationError on any failure — intentionally not caught here+ # so that callers propagate the error and refuse to return an unverified token.+ claims = verify_microsoft_access_token(+ raw_token,+ MICROSOFT_GRAPH_OAUTH_CLIENT_ID,+ tenant_id=tenant_id,+ allowed_tenant_ids=MICROSOFT_ALLOWED_TENANT_IDS,+ )+ logger.debug("Microsoft access token verified", tenant=claims.get("tid"))+ return claimsdiff --git a/src/connectors/onedrive/oauth.py b/src/connectors/onedrive/oauth.pyindex a7c8d666b..722c5e3cf 100644--- a/src/connectors/onedrive/oauth.py+++ b/src/connectors/onedrive/oauth.py@@ -1,11 +1,16 @@import json-import loggingimport osfrom typing import Anyimport msal-logger = logging.getLogger(__name__)+from connectors.microsoft_oauth_utils import verify_ms_access_token+from utils.logging_config import get_logger++logger = get_logger(__name__)++# Backward-compat alias used by get_access_token() call sites in this module.+_verify_access_token = verify_ms_access_tokenclass OneDriveOAuth:@@ -346,8 +351,10 @@ class OneDriveOAuth:self.RESOURCE_SCOPES, account=self._current_account)if result and "access_token" in result:+ access_token = result["access_token"]+ _verify_access_token(access_token) # raises JWTVerificationError on failurelogger.info("OneDrive get_access_token: Success with current account")- return result["access_token"]+ return access_tokenelse:logger.warning(f"OneDrive get_access_token: Failed with account, result: {result}"@@ -357,8 +364,10 @@ class OneDriveOAuth:logger.info("OneDrive get_access_token: Fallback - trying without account")result = self.app.acquire_token_silent(self.RESOURCE_SCOPES, account=None)if result and "access_token" in result:+ access_token = result["access_token"]+ _verify_access_token(access_token) # raises JWTVerificationError on failurelogger.info("OneDrive get_access_token: Fallback success")- return result["access_token"]+ return access_token# If we get here, authentication has failederror_msg = (diff --git a/src/connectors/sharepoint/oauth.py b/src/connectors/sharepoint/oauth.pyindex 95ee104f3..9e618ce26 100644--- a/src/connectors/sharepoint/oauth.py+++ b/src/connectors/sharepoint/oauth.py@@ -1,11 +1,16 @@import json-import loggingimport osfrom typing import Anyimport msal-logger = logging.getLogger(__name__)+from connectors.microsoft_oauth_utils import verify_ms_access_token+from utils.logging_config import get_logger++logger = get_logger(__name__)++# Backward-compat alias used by get_access_token() call sites in this module.+_verify_access_token = verify_ms_access_tokenclass SharePointOAuth:@@ -116,9 +121,12 @@ class SharePointOAuth:logger.debug(f"Found {len(accounts)} accounts in MSAL cache")if accounts:self._current_account = accounts[0]- logger.debug(- f"Set current account: {accounts[0].get('username', 'no username')}"+ username = (+ self._current_account.get("username", "no username")+ if self._current_account+ else "no username")+ logger.debug(f"Set current account: {username}")if needs_upgrade:await self.save_cache()@@ -179,9 +187,12 @@ class SharePointOAuth:logger.debug(f"After refresh, found {len(accounts)} accounts")if accounts:self._current_account = accounts[0]- logger.debug(- f"Set current account after refresh: {accounts[0].get('username', 'no username')}"+ username = (+ self._current_account.get("username", "no username")+ if self._current_account+ else "no username")+ logger.debug(f"Set current account after refresh: {username}")return True# Error handling@@ -360,8 +371,10 @@ class SharePointOAuth:self.RESOURCE_SCOPES, account=self._current_account)if result and "access_token" in result:+ access_token = result["access_token"]+ _verify_access_token(access_token) # raises JWTVerificationError on failurelogger.info("SharePoint get_access_token: Success with current account")- return result["access_token"]+ return access_tokenelse:logger.warning(f"SharePoint get_access_token: Failed with account, result: {result}"@@ -371,8 +384,10 @@ class SharePointOAuth:logger.info("SharePoint get_access_token: Fallback - trying without account")result = self.app.acquire_token_silent(self.RESOURCE_SCOPES, account=None)if result and "access_token" in result:+ access_token = result["access_token"]+ _verify_access_token(access_token) # raises JWTVerificationError on failurelogger.info("SharePoint get_access_token: Fallback success")- return result["access_token"]+ return access_token# If we get here, authentication has failederror_msg = (@@ -417,10 +432,12 @@ class SharePointOAuth:sharepoint_scopes, account=self._current_account)if result and "access_token" in result:+ access_token = result["access_token"]+ _verify_access_token(access_token) # raises JWTVerificationError on failurelogger.info("SharePoint get_access_token_for_resource: Success with current account")- return result["access_token"]+ return access_tokenelse:error_msg = ((result or {}).get("error_description")@@ -437,8 +454,10 @@ class SharePointOAuth:)result = self.app.acquire_token_silent(sharepoint_scopes, account=None)if result and "access_token" in result:+ access_token = result["access_token"]+ _verify_access_token(access_token) # raises JWTVerificationError on failurelogger.info("SharePoint get_access_token_for_resource: Fallback success")- return result["access_token"]+ return access_token# If silent acquisition fails, we may need to acquire interactively or via refresh# Try using the refresh token if available@@ -464,7 +483,7 @@ class SharePointOAuth:raiseexcept Exception as e:logger.exception("[CONNECTOR] SharePoint get_access_token_for_resource failed")- raise ValueError(f"Failed to acquire SharePoint token: {e}") from e+ raise ValueError(f"Failed to acquire SharePoint token: {str(e)}") from easync def revoke_credentials(self):"""Clear token cache and remove token file (like Google Drive)."""diff --git a/src/services/auth_service.py b/src/services/auth_service.pyindex 59fdd72c8..f4f526e95 100644--- a/src/services/auth_service.py+++ b/src/services/auth_service.py@@ -283,6 +283,14 @@ class AuthService:token_data = token_response.json()+ # Verify Google ID token immediately after code exchange, before persisting credentials.+ # Raises JWTVerificationError on any validation failure — connection is rejected.+ if connector_type == "google_drive":+ from connectors.google_drive.oauth import _verify_id_token++ _verify_id_token(token_data.get("id_token"))+ logger.debug("[AUTH] Google ID token verification completed for OAuth callback")+# Store tokens in the token file (without client_secret)# Use actual scopes from OAuth responsegranted_scopes = token_data.get("scope")@@ -299,6 +307,7 @@ class AuthService:token_file_data = {"token": token_data["access_token"],"refresh_token": token_data.get("refresh_token"),+ "id_token": token_data.get("id_token"),"scopes": scopes,}diff --git a/src/tui/config_fields.py b/src/tui/config_fields.pyindex cd74614b8..ecde54414 100644--- a/src/tui/config_fields.py+++ b/src/tui/config_fields.py@@ -268,6 +268,17 @@ CONFIG_SECTIONS: list[ConfigSection] = [placeholder="",secret=True,),+ ConfigField(+ "microsoft_allowed_tenant_ids",+ "MICROSOFT_ALLOWED_TENANT_IDS",+ "Allowed Tenant IDs (optional)",+ placeholder="uuid1,uuid2",+ helper_text=(+ "Comma-separated Azure AD tenant UUIDs. When set, tokens from unlisted tenants "+ "are rejected after signature verification (business policy — not required by "+ "OAuth standards). Leave empty to allow any tenant."+ ),+ ),],advanced=True,gate_prompt="Configure Microsoft Graph OAuth?",diff --git a/src/tui/managers/env_manager.py b/src/tui/managers/env_manager.pyindex 21060f58f..770d9de95 100644--- a/src/tui/managers/env_manager.py+++ b/src/tui/managers/env_manager.py@@ -61,6 +61,7 @@ class EnvConfig:google_oauth_client_secret: str = ""microsoft_graph_oauth_client_id: str = ""microsoft_graph_oauth_client_secret: str = ""+ microsoft_allowed_tenant_ids: str = ""# Optional settingswebhook_base_url: str = ""@@ -215,6 +216,7 @@ class EnvManager:"GOOGLE_OAUTH_CLIENT_SECRET": "google_oauth_client_secret", # pragma: allowlist secret"MICROSOFT_GRAPH_OAUTH_CLIENT_ID": "microsoft_graph_oauth_client_id","MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET": "microsoft_graph_oauth_client_secret", # pragma: allowlist secret+ "MICROSOFT_ALLOWED_TENANT_IDS": "microsoft_allowed_tenant_ids","WEBHOOK_BASE_URL": "webhook_base_url","AWS_ACCESS_KEY_ID": "aws_access_key_id","AWS_SECRET_ACCESS_KEY": "aws_secret_access_key", # pragma: allowlist secret@@ -660,6 +662,10 @@ class EnvManager:f.write(f"MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET={self._quote_env_value(self.config.microsoft_graph_oauth_client_secret)}\n")+ if self.config.microsoft_allowed_tenant_ids:+ f.write(+ f"MICROSOFT_ALLOWED_TENANT_IDS={self._quote_env_value(self.config.microsoft_allowed_tenant_ids)}\n"+ )f.write("\n")# Optional settings@@ -771,6 +777,12 @@ class EnvManager:"",False,),+ (+ "microsoft_allowed_tenant_ids",+ "Microsoft Allowed Tenant IDs",+ "",+ False,+ ),]flow_fields = [diff --git a/src/utils/env_utils.py b/src/utils/env_utils.pyindex 15f00fc1a..af30c53f8 100644--- a/src/utils/env_utils.py+++ b/src/utils/env_utils.py@@ -34,3 +34,15 @@ def get_env_int(key: str, default: int | None = None) -> int | None:def get_env_float(key: str, default: float | None = None) -> float | None:"""Get an environment variable as a float."""return safe_float(os.getenv(key), default)+++def get_env_set(key: str) -> set[str] | None:+ """Return a set of non-empty strings from a comma-separated env var.++ Returns None (not an empty set) when the variable is absent or blank,+ so callers can distinguish 'unset = skip check' from 'set-but-empty = block all'.+ """+ raw = os.getenv(key, "").strip()+ if not raw:+ return None+ return {v.strip() for v in raw.split(",") if v.strip()}diff --git a/src/utils/jwt_verification.py b/src/utils/jwt_verification.pynew file mode 100644index 000000000..39a06675b--- /dev/null+++ b/src/utils/jwt_verification.py@@ -0,0 +1,443 @@+"""JWT signature verification utilities for OAuth tokens."""++from __future__ import annotations++from typing import Any, cast++import httpx+import jwt+from cachetools import TTLCache+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey+from jwt.algorithms import RSAAlgorithm++from utils.logging_config import get_logger++logger = get_logger(__name__)++# JWKS cache: 1 hour TTL, max 10 entries+_jwks_cache: TTLCache = TTLCache(maxsize=10, ttl=3600)++# JWKS endpoints+GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs"+# v2 tokens (iss = login.microsoftonline.com/…/v2.0) use /v2.0/keys.+# v1 tokens (iss = sts.windows.net/…) use /keys (no /v2.0/).+# Selected at runtime based on the `ver` claim.+MICROSOFT_JWKS_URL_V2_TEMPLATE = "https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys"+MICROSOFT_JWKS_URL_V1_TEMPLATE = "https://login.microsoftonline.com/{tenant}/discovery/keys"+++class JWTVerificationError(Exception):+ """Base exception for JWT verification errors."""++ pass+++class InvalidSignatureError(JWTVerificationError):+ """JWT signature is invalid."""++ pass+++class ExpiredTokenError(JWTVerificationError):+ """JWT token has expired."""++ pass+++class InvalidAudienceError(JWTVerificationError):+ """JWT audience claim is invalid."""++ pass+++class InvalidIssuerError(JWTVerificationError):+ """JWT issuer claim is invalid."""++ pass+++def _fetch_jwks(url: str) -> dict[str, Any]:+ """+ Fetch JWKS from URL with caching.++ Args:+ url: JWKS endpoint URL++ Returns:+ JWKS dictionary++ Raises:+ JWTVerificationError: If JWKS fetch fails+ """+ # Check cache first+ if url in _jwks_cache:+ logger.debug(f"JWKS cache hit for {url}")+ return _jwks_cache[url]++ # Fetch from endpoint+ try:+ logger.debug(f"Fetching JWKS from {url}")+ response = httpx.get(url, timeout=5.0)+ response.raise_for_status()+ jwks = response.json()++ # Cache the result+ _jwks_cache[url] = jwks+ logger.debug(f"JWKS cached for {url}")++ return jwks+ except Exception as e:+ logger.error(f"Failed to fetch JWKS from {url}", error=str(e))+ raise JWTVerificationError(f"Failed to fetch JWKS: {e}") from e+++def _get_signing_key(token: str, jwks: dict[str, Any]) -> Any:+ """+ Extract signing key from JWKS based on token header.++ Args:+ token: JWT token+ jwks: JWKS dictionary++ Returns:+ RSA public key object++ Raises:+ JWTVerificationError: If key not found+ """+ try:+ # Decode header without verification to get kid+ unverified_header = jwt.get_unverified_header(token)+ kid = unverified_header.get("kid")++ if not kid:+ raise JWTVerificationError("Token header missing 'kid' field")++ # Find matching key in JWKS+ for key in jwks.get("keys", []):+ if key.get("kid") == kid:+ # Use PyJWT's built-in JWK to PEM conversion+ public_key = RSAAlgorithm.from_jwk(key)+ return public_key++ raise JWTVerificationError(f"Signing key with kid '{kid}' not found in JWKS")++ except jwt.DecodeError as e:+ raise JWTVerificationError(f"Failed to decode token header: {e}") from e+++def verify_google_id_token(token: str, client_id: str) -> dict[str, Any]:+ """+ Verify Google ID token with FULL validation.++ Performs:+ - Signature verification using Google's JWKS+ - Issuer validation (accounts.google.com)+ - Expiration validation+ - Audience validation (requires client_id)++ Args:+ token: Google ID token (JWT)+ client_id: Expected audience (Google OAuth client ID)++ Returns:+ Verified token claims++ Raises:+ InvalidSignatureError: If signature is invalid+ ExpiredTokenError: If token has expired+ InvalidAudienceError: If audience doesn't match+ InvalidIssuerError: If issuer is invalid+ JWTVerificationError: For other verification failures+ """+ if not client_id:+ raise JWTVerificationError("client_id is required for Google ID token verification")++ try:+ # Fetch JWKS+ jwks = _fetch_jwks(GOOGLE_JWKS_URL)++ # Get signing key+ signing_key = _get_signing_key(token, jwks)++ # Verify token with FULL validation+ claims = jwt.decode(+ token,+ signing_key,+ algorithms=["RS256"],+ audience=client_id,+ issuer=["https://accounts.google.com", "accounts.google.com"],+ options={+ "verify_signature": True,+ "verify_exp": True,+ "verify_aud": True,+ "verify_iss": True,+ },+ )++ logger.debug("Google ID token verified successfully")+ return claims++ except jwt.InvalidSignatureError as e:+ logger.warning("Google ID token has invalid signature", error=str(e))+ raise InvalidSignatureError(f"Invalid signature: {e}") from e+ except jwt.ExpiredSignatureError as e:+ logger.warning("Google ID token has expired", error=str(e))+ raise ExpiredTokenError(f"Token expired: {e}") from e+ except jwt.InvalidAudienceError as e:+ logger.warning("Google ID token has invalid audience", error=str(e))+ raise InvalidAudienceError(f"Invalid audience: {e}") from e+ except jwt.InvalidIssuerError as e:+ logger.warning("Google ID token has invalid issuer", error=str(e))+ raise InvalidIssuerError(f"Invalid issuer: {e}") from e+ except JWTVerificationError:+ raise+ except Exception as e:+ logger.error("Google ID token verification failed", error=str(e))+ raise JWTVerificationError(f"Verification failed: {e}") from e+++def _resolve_ms_jwks_url(tenant_id: str, token_version: str) -> str:+ """+ Return the correct JWKS URL for the given tenant and token version.++ Per Microsoft docs: v1.0 tokens must be validated against the v1 metadata+ endpoint (no /v2.0/), v2.0 tokens against the v2 endpoint.+ """+ if token_version == "1.0":+ return MICROSOFT_JWKS_URL_V1_TEMPLATE.format(tenant=tenant_id)+ return MICROSOFT_JWKS_URL_V2_TEMPLATE.format(tenant=tenant_id)+++# Known Microsoft issuer URL prefixes used when the JWKS key entry omits "issuer".+_MS_ISSUER_PREFIXES = (+ "https://login.microsoftonline.com/",+ "https://sts.windows.net/",+)+++def _validate_ms_issuer(issuer: str, token_tid: str, signing_key_issuer: str | None) -> None:+ """+ Validate the token issuer following Microsoft's documented algorithm:++ 1. When the JWKS key entry carries an ``issuer`` property, substitute+ ``{tenantid}`` and require an exact match against the token ``iss`` claim+ (Microsoft's documented multi-tenant issuer validation algorithm).+ 2. When the key entry omits ``issuer`` (common for tenant-specific JWKS+ endpoints), fall back to verifying that ``iss`` starts with a known+ Microsoft issuer URL prefix — preventing cross-issuer attacks without+ rejecting otherwise valid tokens.+ 3. In both cases, confirm that the ``tid`` claim matches the tenant segment+ embedded in the ``iss`` URL.++ Raises InvalidIssuerError on any failure.+ """+ if signing_key_issuer:+ # Keys from the tenant-independent endpoint carry "{tenantid}" as a+ # placeholder; tenant-specific keys may carry a literal issuer URL.+ resolved_key_issuer = signing_key_issuer.replace("{tenantid}", token_tid)+ if resolved_key_issuer != issuer:+ raise InvalidIssuerError(+ f"Token issuer {issuer!r} does not match signing key issuer "+ f"{resolved_key_issuer!r} (tid={token_tid!r})"+ )+ else:+ # JWKS key entry has no issuer field — validate against known MS prefixes.+ if not any(issuer.startswith(prefix) for prefix in _MS_ISSUER_PREFIXES):+ raise InvalidIssuerError(+ f"Token issuer {issuer!r} is not a recognised Microsoft issuer URL"+ )++ # Confirm the tid claim matches the tenant GUID segment in the iss URL.+ # Handles both v2 form (login.microsoftonline.com/{tid}/v2.0)+ # and v1 form (sts.windows.net/{tid}/).+ iss_segments = issuer.rstrip("/").split("/")+ tid_in_iss = next(+ (seg for seg in iss_segments if seg and "-" in seg and len(seg) == 36),+ None,+ )+ if tid_in_iss and tid_in_iss != token_tid:+ raise InvalidIssuerError(+ f"Tenant ID in issuer URL {tid_in_iss!r} does not match tid claim {token_tid!r}"+ )+++def verify_microsoft_access_token(+ token: str,+ client_id: str,+ tenant_id: str | None = None,+ allowed_tenant_ids: set[str] | None = None,+) -> dict[str, Any]:+ """+ Verify a Microsoft access token following the Microsoft identity platform docs.++ Scope of validation (per https://learn.microsoft.com/en-us/entra/identity-platform/+ access-token-claims-reference#validate-tokens):++ - We are a *client* (web app calling Microsoft Graph), NOT a resource server.+ The docs state: "APIs and web applications must only validate tokens that have+ an aud claim that matches the application." Access tokens issued for Microsoft+ Graph have aud = Graph's AppId, not ours — those tokens are for Graph to+ validate, not us. When aud != our client_id we skip verification and return the+ unverified claims; the token was obtained via MSAL over a trusted OAuth flow.++ - When aud == our client_id (token issued directly for our app), we perform full+ validation: signature, expiry, audience, and issuer per Microsoft docs.++ Signature validation details (when performed):+ - JWKS endpoint selected by token version: v1 tokens (/discovery/keys),+ v2 tokens (/discovery/v2.0/keys).+ - Signing key looked up by kid header claim.+ - Issuer validated against the signing key's own issuer property in the JWKS+ document, with {tenantid} placeholder substituted by the token's tid claim+ (Microsoft's documented multi-tenant issuer validation algorithm).+ - tid segment of iss URL verified to match tid claim.++ Optionally (business policy, not a standards requirement):+ - Tenant allow-list enforced when MICROSOFT_ALLOWED_TENANT_IDS is configured.++ Args:+ token: Raw JWT access token string.+ client_id: OpenRAG's Azure AD app client ID.+ tenant_id: Hint for JWKS endpoint selection; extracted from the+ unverified tid claim when not provided.+ allowed_tenant_ids: Optional set of permitted Azure AD tenant UUIDs.++ Returns:+ Verified (or trusted-unverified) token claims dict.++ Raises:+ InvalidSignatureError: Signature does not match the signing key.+ ExpiredTokenError: Token exp claim is in the past.+ InvalidAudienceError: aud matches our client_id but fails verification.+ InvalidIssuerError: iss / tid mismatch, or tenant not in allow-list.+ JWTVerificationError: Any other verification failure.+ """+ if not client_id:+ raise JWTVerificationError("client_id is required for Microsoft access token verification")++ try:+ # Decode without verification to inspect claims and pick the JWKS endpoint.+ unverified_claims = jwt.decode(token, options={"verify_signature": False})++ # Resolve tenant for JWKS URL (not trusted for security — re-checked post-sig).+ if not tenant_id:+ tenant_id = unverified_claims.get("tid")+ if not tenant_id:+ raise JWTVerificationError(+ "Token is missing the 'tid' claim; cannot resolve JWKS endpoint."+ )+ logger.debug(f"Extracted tenant_id from token: {tenant_id}")++ token_aud = unverified_claims.get("aud", "")++ # Per Microsoft docs: only validate tokens whose aud matches OUR application.+ # Access tokens issued for another resource (e.g. Microsoft Graph,+ # aud=00000003-0000-0000-c000-000000000000) are for that resource to validate —+ # we are the caller, not the resource. Attempting to verify them would always+ # fail because we do not hold the correct validation parameters for Graph.+ if token_aud != client_id:+ logger.debug(+ "Skipping signature verification: token audience is a resource we do not own",+ token_aud=token_aud,+ our_client_id=client_id,+ )+ # Still enforce the tenant allow-list even for pass-through tokens.+ unverified_tid = unverified_claims.get("tid", "")+ if allowed_tenant_ids is not None and unverified_tid not in allowed_tenant_ids:+ logger.warning(+ "Microsoft token tenant not in allow-list",+ tid=unverified_tid,+ )+ raise InvalidIssuerError(+ f"Tenant '{unverified_tid}' is not in the configured allowed tenant list"+ )+ return unverified_claims++ # ── Full validation for tokens issued directly to our application ──────────++ # Select JWKS endpoint based on token version (v1 vs v2).+ token_version = unverified_claims.get("ver", "2.0")+ jwks_url = _resolve_ms_jwks_url(tenant_id, token_version)+ jwks = _fetch_jwks(jwks_url)++ # Find the signing key by kid and record its issuer property from the+ # JWKS document — needed for Microsoft's documented issuer validation.+ unverified_header = jwt.get_unverified_header(token)+ kid = unverified_header.get("kid")+ if not kid:+ raise JWTVerificationError("Token header missing 'kid' field")++ signing_key_entry = next((k for k in jwks.get("keys", []) if k.get("kid") == kid), None)+ if signing_key_entry is None:+ raise JWTVerificationError(f"Signing key with kid '{kid}' not found in JWKS")++ signing_key_issuer = signing_key_entry.get("issuer") or None+ # from_jwk() is typed as RSAPrivateKey | RSAPublicKey but JWKS endpoints+ # only ever contain public keys — cast so mypy accepts it for jwt.decode().+ signing_key = cast(RSAPublicKey, RSAAlgorithm.from_jwk(signing_key_entry))++ # Verify signature, expiry, and audience.+ # verify_iss=False: issuer validated manually below per Microsoft's algorithm.+ claims = jwt.decode(+ token,+ signing_key,+ algorithms=["RS256"],+ audience=client_id,+ options={+ "verify_signature": True,+ "verify_exp": True,+ "verify_aud": True,+ "verify_iss": False,+ },+ )++ # Issuer validation per Microsoft docs:+ # Substitute tid into the signing key's issuer template and exact-match iss.+ verified_tid = claims.get("tid", "")+ issuer = claims.get("iss", "")+ _validate_ms_issuer(issuer, verified_tid, signing_key_issuer)++ # Tenant allow-list (optional business policy).+ if allowed_tenant_ids is not None and verified_tid not in allowed_tenant_ids:+ logger.warning(+ "Microsoft token tenant not in allow-list",+ verified_tid=verified_tid,+ )+ raise InvalidIssuerError(+ f"Tenant '{verified_tid}' is not in the configured allowed tenant list"+ )++ logger.debug(+ "Microsoft access token verified",+ tenant=verified_tid,+ token_version=token_version,+ )+ return claims++ except jwt.InvalidSignatureError as e:+ logger.warning("Microsoft access token has invalid signature", error=str(e))+ raise InvalidSignatureError(f"Invalid signature: {e}") from e+ except jwt.ExpiredSignatureError as e:+ logger.warning("Microsoft access token has expired", error=str(e))+ raise ExpiredTokenError(f"Token expired: {e}") from e+ except jwt.InvalidAudienceError as e:+ logger.warning("Microsoft access token has invalid audience", error=str(e))+ raise InvalidAudienceError(f"Invalid audience: {e}") from e+ except (jwt.InvalidIssuerError, InvalidIssuerError) as e:+ logger.warning("Microsoft access token has invalid issuer", error=str(e))+ raise InvalidIssuerError(f"Invalid issuer: {e}") from e+ except JWTVerificationError:+ raise+ except Exception as e:+ logger.error("Microsoft access token verification failed", error=str(e))+ raise JWTVerificationError(f"Verification failed: {e}") from e+++def clear_jwks_cache():+ """Clear the JWKS cache. Useful for testing."""+ _jwks_cache.clear()+ logger.debug("JWKS cache cleared")+++# Made with Bobdiff --git a/tests/unit/utils/test_jwt_verification.py b/tests/unit/utils/test_jwt_verification.pynew file mode 100644index 000000000..be38182dd--- /dev/null+++ b/tests/unit/utils/test_jwt_verification.py@@ -0,0 +1,607 @@+"""Unit tests for src/utils/jwt_verification.py.++All tests are fully self-contained:+- RSA key pairs generated in-process via cryptography; no network calls.+- JWKS fetching is patched at `utils.jwt_verification._fetch_jwks`.+- clear_jwks_cache() is called in a fixture to prevent cache bleed between tests.++Test groups+-----------+TestResolveMsJwksUrl – _resolve_ms_jwks_url() URL selection+TestValidateMsIssuer – _validate_ms_issuer() exact-match + tid-in-iss check+TestVerifyMsAccessToken – verify_microsoft_access_token() full behaviour matrix+TestVerifyGoogleIdToken – verify_google_id_token() full behaviour matrix+TestGetEnvSet – get_env_set() helper+"""++from __future__ import annotations++import sys+import time+from pathlib import Path+from typing import Any+from unittest.mock import MagicMock, patch++import jwt+import pytest+from cryptography.hazmat.primitives.asymmetric import rsa++# Ensure src/ is on the path when running from the repo root.+ROOT = Path(__file__).resolve().parent.parent.parent.parent+SRC = ROOT / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))++from utils.jwt_verification import ( # noqa: E402+ ExpiredTokenError,+ InvalidAudienceError,+ InvalidIssuerError,+ InvalidSignatureError,+ JWTVerificationError,+ _resolve_ms_jwks_url,+ _validate_ms_issuer,+ clear_jwks_cache,+ verify_google_id_token,+ verify_microsoft_access_token,+)++# ─────────────────────────────────────────────────────────────────────────────+# Shared helpers+# ─────────────────────────────────────────────────────────────────────────────++KID = "test-key-id-001"+CLIENT_ID = "aaaaaaaa-0000-0000-0000-aaaaaaaaaaaa"+TENANT_ID = "bbbbbbbb-1111-1111-1111-bbbbbbbbbbbb"+MS_V2_ISS = f"https://login.microsoftonline.com/{TENANT_ID}/v2.0"+MS_V1_ISS = f"https://sts.windows.net/{TENANT_ID}/"+GOOGLE_ISS = "https://accounts.google.com"+++def _generate_rsa_key_pair():+ """Return (private_key, public_key, jwk_dict) for test tokens."""+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ public_key = private_key.public_key()++ # Build a minimal JWK for the public key (PyJWT RSAAlgorithm.from_jwk accepts this).+ import json++ from jwt.algorithms import RSAAlgorithm++ jwk_str = RSAAlgorithm.to_jwk(public_key)+ jwk_dict = json.loads(jwk_str)+ jwk_dict["kid"] = KID+ jwk_dict["use"] = "sig"+ jwk_dict["kty"] = "RSA"++ return private_key, public_key, jwk_dict+++def _make_ms_token(+ private_key,+ *,+ aud: str = CLIENT_ID,+ iss: str = MS_V2_ISS,+ tid: str = TENANT_ID,+ ver: str = "2.0",+ exp_offset: int = 3600,+ kid: str = KID,+) -> str:+ now = int(time.time())+ payload: dict[str, Any] = {+ "aud": aud,+ "iss": iss,+ "tid": tid,+ "ver": ver,+ "sub": "test-subject",+ "iat": now,+ "exp": now + exp_offset,+ }+ return jwt.encode(payload, private_key, algorithm="RS256", headers={"kid": kid})+++def _make_google_token(+ private_key,+ *,+ aud: str = CLIENT_ID,+ iss: str = GOOGLE_ISS,+ exp_offset: int = 3600,+ kid: str = KID,+) -> str:+ now = int(time.time())+ payload: dict[str, Any] = {+ "aud": aud,+ "iss": iss,+ "sub": "google-user-123",+ "email": "[email protected]",+ "iat": now,+ "exp": now + exp_offset,+ }+ return jwt.encode(payload, private_key, algorithm="RS256", headers={"kid": kid})+++def _jwks(jwk_dict: dict, *, issuer: str = MS_V2_ISS) -> dict:+ """Wrap a JWK dict in a JWKS keys array with an issuer property."""+ key_entry = {**jwk_dict, "issuer": issuer}+ return {"keys": [key_entry]}++[email protected](autouse=True)+def _clear_cache():+ """Ensure the JWKS cache is empty before and after every test."""+ clear_jwks_cache()+ yield+ clear_jwks_cache()+++# ─────────────────────────────────────────────────────────────────────────────+# _resolve_ms_jwks_url+# ─────────────────────────────────────────────────────────────────────────────+++class TestResolveMsJwksUrl:+ def test_v2_token_uses_v2_endpoint(self):+ url = _resolve_ms_jwks_url(TENANT_ID, "2.0")+ assert "/discovery/v2.0/keys" in url+ assert TENANT_ID in url++ def test_v1_token_uses_v1_endpoint(self):+ url = _resolve_ms_jwks_url(TENANT_ID, "1.0")+ assert "/discovery/keys" in url+ assert "/v2.0/" not in url+ assert TENANT_ID in url++ def test_unknown_version_defaults_to_v2(self):+ url = _resolve_ms_jwks_url(TENANT_ID, "3.0")+ assert "/v2.0/" in url+++# ─────────────────────────────────────────────────────────────────────────────+# _validate_ms_issuer+# ─────────────────────────────────────────────────────────────────────────────+++class TestValidateMsIssuer:+ def test_v2_exact_match_passes(self):+ """Signing key issuer exactly matches token iss — should pass."""+ _validate_ms_issuer(MS_V2_ISS, TENANT_ID, MS_V2_ISS)++ def test_templated_key_issuer_substitution_passes(self):+ """Key issuer has {tenantid} placeholder — substituted and matched."""+ templated = "https://login.microsoftonline.com/{tenantid}/v2.0"+ _validate_ms_issuer(MS_V2_ISS, TENANT_ID, templated)++ def test_v1_sts_issuer_passes(self):+ """v1 STS issuer form validated correctly."""+ _validate_ms_issuer(MS_V1_ISS, TENANT_ID, MS_V1_ISS)++ def test_wrong_issuer_raises(self):+ """Signing key issuer doesn't match token iss."""+ wrong = "https://login.microsoftonline.com/ffffffff-ffff-ffff-ffff-ffffffffffff/v2.0"+ with pytest.raises(InvalidIssuerError, match="does not match signing key issuer"):+ _validate_ms_issuer(MS_V2_ISS, TENANT_ID, wrong)++ def test_tid_mismatch_in_iss_raises(self):+ """tid claim doesn't match the GUID segment in iss."""+ different_tid = "cccccccc-2222-2222-2222-cccccccccccc"+ with pytest.raises(InvalidIssuerError, match="does not match tid claim"):+ _validate_ms_issuer(MS_V2_ISS, different_tid, MS_V2_ISS)++ def test_issuer_without_guid_segment_skips_tid_url_check(self):+ """If there's no GUID in the iss URL segments, the tid-in-URL check is skipped."""+ # Some test/synthetic issuers may not have a GUID; should not crash+ synthetic_iss = "https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0"+ _validate_ms_issuer(synthetic_iss, TENANT_ID, synthetic_iss)++ def test_none_signing_key_issuer_valid_ms_prefix_passes(self):+ """JWKS key entry omits issuer — iss starts with known MS prefix, should pass."""+ _validate_ms_issuer(MS_V2_ISS, TENANT_ID, None)++ def test_none_signing_key_issuer_v1_prefix_passes(self):+ """JWKS key entry omits issuer — v1 sts.windows.net iss passes prefix check."""+ _validate_ms_issuer(MS_V1_ISS, TENANT_ID, None)++ def test_none_signing_key_issuer_unknown_prefix_raises(self):+ """JWKS key entry omits issuer — iss from unknown origin is rejected."""+ with pytest.raises(InvalidIssuerError, match="not a recognised Microsoft issuer URL"):+ _validate_ms_issuer("https://evil.example.com/tenant/v2.0", TENANT_ID, None)++ def test_none_signing_key_issuer_tid_mismatch_raises(self):+ """JWKS key entry omits issuer — tid mismatch in iss still caught."""+ different_tid = "cccccccc-2222-2222-2222-cccccccccccc"+ with pytest.raises(InvalidIssuerError, match="does not match tid claim"):+ _validate_ms_issuer(MS_V2_ISS, different_tid, None)+++# ─────────────────────────────────────────────────────────────────────────────+# verify_microsoft_access_token+# ─────────────────────────────────────────────────────────────────────────────+++class TestVerifyMsAccessToken:+ """Tests for verify_microsoft_access_token()."""++ def setup_method(self):+ self.private_key, self.public_key, self.jwk = _generate_rsa_key_pair()+ self.jwks = _jwks(self.jwk, issuer=MS_V2_ISS)++ # ── pass-through path (aud != our client_id) ─────────────────────────────++ def test_graph_audience_token_is_passed_through(self):+ """Tokens for MS Graph (aud=00000003-…) are returned without sig verification."""+ MS_GRAPH_AUD = "00000003-0000-0000-c000-000000000000"+ token = _make_ms_token(self.private_key, aud=MS_GRAPH_AUD)++ # _fetch_jwks must NOT be called for pass-through tokens+ with patch("utils.jwt_verification._fetch_jwks") as mock_fetch:+ claims = verify_microsoft_access_token(token, CLIENT_ID)++ mock_fetch.assert_not_called()+ assert claims["aud"] == MS_GRAPH_AUD+ assert claims["tid"] == TENANT_ID++ def test_graph_token_tenant_allow_list_enforced(self):+ """Even for pass-through tokens, the tenant allow-list is checked."""+ MS_GRAPH_AUD = "00000003-0000-0000-c000-000000000000"+ token = _make_ms_token(self.private_key, aud=MS_GRAPH_AUD)++ with patch("utils.jwt_verification._fetch_jwks"):+ with pytest.raises(+ InvalidIssuerError, match="not in the configured allowed tenant list"+ ):+ verify_microsoft_access_token(+ token,+ CLIENT_ID,+ allowed_tenant_ids={"ffffffff-ffff-ffff-ffff-ffffffffffff"},+ )++ def test_graph_token_allowed_tenant_passes(self):+ """Pass-through token from a tenant in the allow-list succeeds."""+ MS_GRAPH_AUD = "00000003-0000-0000-c000-000000000000"+ token = _make_ms_token(self.private_key, aud=MS_GRAPH_AUD)++ with patch("utils.jwt_verification._fetch_jwks"):+ claims = verify_microsoft_access_token(+ token,+ CLIENT_ID,+ allowed_tenant_ids={TENANT_ID},+ )+ assert claims["tid"] == TENANT_ID++ # ── full verification path (aud == our client_id) ────────────────────────++ def test_valid_v2_token_verifies(self):+ """Happy path: valid v2 token signed with our key passes all checks."""+ token = _make_ms_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ claims = verify_microsoft_access_token(token, CLIENT_ID)++ assert claims["aud"] == CLIENT_ID+ assert claims["tid"] == TENANT_ID+ assert claims["iss"] == MS_V2_ISS++ def test_valid_v1_token_uses_v1_jwks_url(self):+ """v1 tokens must be fetched from the /discovery/keys endpoint (no /v2.0/)."""+ v1_jwks = _jwks(self.jwk, issuer=MS_V1_ISS)+ token = _make_ms_token(+ self.private_key,+ iss=MS_V1_ISS,+ ver="1.0",+ )++ captured_url = {}++ def fake_fetch(url):+ captured_url["url"] = url+ return v1_jwks++ with patch("utils.jwt_verification._fetch_jwks", side_effect=fake_fetch):+ claims = verify_microsoft_access_token(token, CLIENT_ID)++ assert "/v2.0/" not in captured_url["url"], "v1 token must NOT use v2 JWKS endpoint"+ assert claims["ver"] == "1.0"++ def test_invalid_signature_raises(self):+ """Token signed with a different key is rejected."""+ other_private_key, _, _ = _generate_rsa_key_pair()+ token = _make_ms_token(other_private_key) # signed with different key++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(InvalidSignatureError):+ verify_microsoft_access_token(token, CLIENT_ID)++ def test_expired_token_raises(self):+ """Token with exp in the past is rejected."""+ token = _make_ms_token(self.private_key, exp_offset=-60)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(ExpiredTokenError):+ verify_microsoft_access_token(token, CLIENT_ID)++ def test_wrong_audience_raises(self):+ """Token issued for our app (aud=CLIENT_ID) but the signature verifies+ against the wrong audience value raises InvalidAudienceError.+ We achieve this by making a token with aud=CLIENT_ID and passing a+ different client_id that also equals aud (so full-verify path runs)+ by simply using a client_id that doesn't match the token aud at all+ but keeps aud == client_id so we enter the full-verify branch.++ Simplest approach: issue token with aud=WRONG, call with client_id=WRONG+ so we enter full-verify, but the JWKS key issuer won't match → raises.+ """+ # When client_id != token aud, the function skips verification and returns+ # unverified claims (pass-through). This is the correct MS docs behaviour:+ # only validate tokens whose aud matches our application.+ token = _make_ms_token(self.private_key, aud=CLIENT_ID)++ # When client_id != token aud, the function skips verification and returns+ # unverified claims (pass-through). This is correct MS docs behaviour.+ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ claims = verify_microsoft_access_token(token, "different-client-id")+ # Pass-through: returns claims without error+ assert claims["aud"] == CLIENT_ID++ def test_issuer_mismatch_raises(self):+ """Signing key issuer in JWKS doesn't match the token iss."""+ wrong_issuer_jwks = _jwks(+ self.jwk,+ issuer="https://login.microsoftonline.com/ffffffff-ffff-ffff-ffff-ffffffffffff/v2.0",+ )+ token = _make_ms_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=wrong_issuer_jwks):+ with pytest.raises(InvalidIssuerError):+ verify_microsoft_access_token(token, CLIENT_ID)++ def test_tenant_allow_list_rejects_unlisted_tenant(self):+ """Token from a tenant not in the allow-list is rejected after signature check."""+ token = _make_ms_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(+ InvalidIssuerError, match="not in the configured allowed tenant list"+ ):+ verify_microsoft_access_token(+ token,+ CLIENT_ID,+ allowed_tenant_ids={"ffffffff-ffff-ffff-ffff-ffffffffffff"},+ )++ def test_tenant_allow_list_accepts_listed_tenant(self):+ """Token from a tenant in the allow-list passes."""+ token = _make_ms_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ claims = verify_microsoft_access_token(+ token,+ CLIENT_ID,+ allowed_tenant_ids={TENANT_ID},+ )+ assert claims["tid"] == TENANT_ID++ def test_no_allow_list_accepts_any_tenant(self):+ """When allowed_tenant_ids is None, any tenant is accepted."""+ token = _make_ms_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ claims = verify_microsoft_access_token(token, CLIENT_ID, allowed_tenant_ids=None)++ assert claims["tid"] == TENANT_ID++ def test_missing_tid_raises(self):+ """Token without a tid claim cannot resolve the JWKS endpoint."""+ now = int(time.time())+ payload = {+ "aud": CLIENT_ID,+ "iss": MS_V2_ISS,+ "sub": "no-tid",+ "iat": now,+ "exp": now + 3600,+ # tid intentionally omitted+ }+ token = jwt.encode(payload, self.private_key, algorithm="RS256", headers={"kid": KID})++ with pytest.raises(JWTVerificationError, match="missing the 'tid' claim"):+ verify_microsoft_access_token(token, CLIENT_ID)++ def test_missing_client_id_raises(self):+ """Empty client_id is rejected immediately."""+ token = _make_ms_token(self.private_key)+ with pytest.raises(JWTVerificationError, match="client_id is required"):+ verify_microsoft_access_token(token, "")++ def test_kid_not_in_jwks_raises(self):+ """Token kid not found in the JWKS raises JWTVerificationError."""+ token = _make_ms_token(self.private_key, kid="unknown-kid")+ # JWKS has KID "test-key-id-001", token has "unknown-kid"++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(JWTVerificationError, match="not found in JWKS"):+ verify_microsoft_access_token(token, CLIENT_ID)++ def test_jwks_fetch_failure_raises(self):+ """Network failure during JWKS fetch propagates as JWTVerificationError."""+ token = _make_ms_token(self.private_key)++ with patch(+ "utils.jwt_verification._fetch_jwks", side_effect=JWTVerificationError("network error")+ ):+ with pytest.raises(JWTVerificationError):+ verify_microsoft_access_token(token, CLIENT_ID)++ def test_tenant_id_hint_bypasses_extraction(self):+ """Providing tenant_id explicitly skips the tid extraction from token."""+ token = _make_ms_token(self.private_key)++ fetched_urls = []++ def fake_fetch(url):+ fetched_urls.append(url)+ return self.jwks++ with patch("utils.jwt_verification._fetch_jwks", side_effect=fake_fetch):+ verify_microsoft_access_token(token, CLIENT_ID, tenant_id=TENANT_ID)++ assert any(TENANT_ID in u for u in fetched_urls)++ def test_templated_jwks_key_issuer_accepted(self):+ """Keys from tenant-independent JWKS endpoint have {tenantid} placeholder."""+ templated_jwks = _jwks(+ self.jwk,+ issuer="https://login.microsoftonline.com/{tenantid}/v2.0",+ )+ token = _make_ms_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=templated_jwks):+ claims = verify_microsoft_access_token(token, CLIENT_ID)++ assert claims["tid"] == TENANT_ID+++# ─────────────────────────────────────────────────────────────────────────────+# verify_google_id_token+# ─────────────────────────────────────────────────────────────────────────────+++class TestVerifyGoogleIdToken:+ """Tests for verify_google_id_token()."""++ def setup_method(self):+ self.private_key, self.public_key, self.jwk = _generate_rsa_key_pair()+ self.jwks = {"keys": [self.jwk]}++ def test_valid_token_verifies(self):+ """Happy path: valid Google ID token passes all checks."""+ token = _make_google_token(self.private_key)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ claims = verify_google_id_token(token, CLIENT_ID)++ assert claims["aud"] == CLIENT_ID+ assert claims["iss"] == GOOGLE_ISS++ def test_invalid_signature_raises(self):+ """Token signed with a different key raises InvalidSignatureError."""+ other_key, _, _ = _generate_rsa_key_pair()+ token = _make_google_token(other_key) # signed with different key++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(InvalidSignatureError):+ verify_google_id_token(token, CLIENT_ID)++ def test_expired_token_raises(self):+ """Expired Google ID token raises ExpiredTokenError."""+ token = _make_google_token(self.private_key, exp_offset=-60)++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(ExpiredTokenError):+ verify_google_id_token(token, CLIENT_ID)++ def test_wrong_audience_raises(self):+ """Token with wrong audience raises InvalidAudienceError."""+ token = _make_google_token(self.private_key, aud="wrong-client-id")++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(InvalidAudienceError):+ verify_google_id_token(token, CLIENT_ID)++ def test_wrong_issuer_raises(self):+ """Token from an unknown issuer raises InvalidIssuerError."""+ token = _make_google_token(self.private_key, iss="https://evil.example.com")++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(InvalidIssuerError):+ verify_google_id_token(token, CLIENT_ID)++ def test_missing_client_id_raises(self):+ """Empty client_id is rejected before any JWKS fetch."""+ token = _make_google_token(self.private_key)+ with pytest.raises(JWTVerificationError, match="client_id is required"):+ verify_google_id_token(token, "")++ def test_kid_not_in_jwks_raises(self):+ """Token kid not found in JWKS raises JWTVerificationError."""+ token = _make_google_token(self.private_key, kid="unknown-kid")++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ with pytest.raises(JWTVerificationError, match="not found in JWKS"):+ verify_google_id_token(token, CLIENT_ID)++ def test_accounts_google_com_short_form_issuer_accepted(self):+ """Tokens with issuer 'accounts.google.com' (no https://) are also valid."""+ token = _make_google_token(self.private_key, iss="accounts.google.com")++ with patch("utils.jwt_verification._fetch_jwks", return_value=self.jwks):+ claims = verify_google_id_token(token, CLIENT_ID)++ assert claims["iss"] == "accounts.google.com"++ def test_jwks_cached_between_calls(self):+ """Second call within cache TTL must not make a second HTTP request."""+ token = _make_google_token(self.private_key)++ mock_response = MagicMock()+ mock_response.raise_for_status = MagicMock()+ mock_response.json.return_value = self.jwks++ with patch("utils.jwt_verification.httpx.get", return_value=mock_response) as mock_get:+ verify_google_id_token(token, CLIENT_ID)+ verify_google_id_token(token, CLIENT_ID)++ # httpx.get must only be called once; second call served from cache.+ assert mock_get.call_count == 1+++# ─────────────────────────────────────────────────────────────────────────────+# get_env_set (env_utils helper)+# ─────────────────────────────────────────────────────────────────────────────+++class TestGetEnvSet:+ """Tests for the get_env_set() helper used for MICROSOFT_ALLOWED_TENANT_IDS."""++ def test_unset_returns_none(self, monkeypatch):+ monkeypatch.delenv("MICROSOFT_ALLOWED_TENANT_IDS", raising=False)+ from utils.env_utils import get_env_set++ assert get_env_set("MICROSOFT_ALLOWED_TENANT_IDS") is None++ def test_empty_string_returns_none(self, monkeypatch):+ monkeypatch.setenv("MICROSOFT_ALLOWED_TENANT_IDS", "")+ from utils.env_utils import get_env_set++ assert get_env_set("MICROSOFT_ALLOWED_TENANT_IDS") is None++ def test_whitespace_only_returns_none(self, monkeypatch):+ monkeypatch.setenv("MICROSOFT_ALLOWED_TENANT_IDS", " ")+ from utils.env_utils import get_env_set++ assert get_env_set("MICROSOFT_ALLOWED_TENANT_IDS") is None++ def test_single_value_returns_set(self, monkeypatch):+ monkeypatch.setenv("MICROSOFT_ALLOWED_TENANT_IDS", "aaaa-1111")+ from utils.env_utils import get_env_set++ result = get_env_set("MICROSOFT_ALLOWED_TENANT_IDS")+ assert result == {"aaaa-1111"}++ def test_multiple_values_returns_set(self, monkeypatch):+ monkeypatch.setenv("MICROSOFT_ALLOWED_TENANT_IDS", "aaaa-1111,bbbb-2222,cccc-3333")+ from utils.env_utils import get_env_set++ result = get_env_set("MICROSOFT_ALLOWED_TENANT_IDS")+ assert result == {"aaaa-1111", "bbbb-2222", "cccc-3333"}++ def test_values_are_stripped(self, monkeypatch):+ monkeypatch.setenv("MICROSOFT_ALLOWED_TENANT_IDS", " aaaa-1111 , bbbb-2222 ")+ from utils.env_utils import get_env_set++ result = get_env_set("MICROSOFT_ALLOWED_TENANT_IDS")+ assert result == {"aaaa-1111", "bbbb-2222"}++ def test_empty_segments_ignored(self, monkeypatch):+ monkeypatch.setenv("MICROSOFT_ALLOWED_TENANT_IDS", "aaaa-1111,,bbbb-2222,")+ from utils.env_utils import get_env_set++ result = get_env_set("MICROSOFT_ALLOWED_TENANT_IDS")+ assert result == {"aaaa-1111", "bbbb-2222"}