"""Apple and Google ID-token verification (signature against the provider's JWKS, issuer, audience, expiry).""" import asyncio from dataclasses import dataclass from functools import lru_cache from typing import Any, Protocol import jwt from app.core.config import Settings, get_settings APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys" GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs" ISSUERS = { "apple": ("https://appleid.apple.com",), "google": ("accounts.google.com", "https://accounts.google.com"), } class InvalidSocialToken(Exception): pass @dataclass(frozen=True) class SocialIdentity: subject: str email: str | None email_verified: bool class SigningKeySource(Protocol): def get_signing_key_from_jwt(self, token: str) -> Any: ... class SocialTokenVerifier: def __init__(self, settings: Settings, key_sources: dict[str, SigningKeySource] | None = None): self.audiences = {"apple": list(settings.apple_client_ids), "google": list(settings.google_client_ids)} self.key_sources = key_sources or { "apple": jwt.PyJWKClient(APPLE_JWKS_URL, cache_keys=True), "google": jwt.PyJWKClient(GOOGLE_JWKS_URL, cache_keys=True), } async def verify(self, provider: str, id_token: str) -> SocialIdentity: """Returns the verified identity; raises InvalidSocialToken for any bad, expired or foreign token.""" if provider not in ISSUERS or not self.audiences[provider]: raise InvalidSocialToken(f"{provider} sign-in is not configured") try: # PyJWKClient fetches keys over blocking HTTP. signing_key = await asyncio.to_thread(self.key_sources[provider].get_signing_key_from_jwt, id_token) claims = jwt.decode( id_token, signing_key.key, algorithms=["RS256"], audience=self.audiences[provider], options={"require": ["iss", "sub", "aud", "exp"]}, ) except (jwt.PyJWTError, KeyError, ValueError) as exc: raise InvalidSocialToken(str(exc)) from exc if claims["iss"] not in ISSUERS[provider]: raise InvalidSocialToken("wrong issuer") email = claims.get("email") verified = claims.get("email_verified") in (True, "true") # Apple sends the string "true" return SocialIdentity(subject=str(claims["sub"]), email=email.strip().lower() if email else None, email_verified=bool(email) and verified) @lru_cache def get_social_verifier() -> SocialTokenVerifier: return SocialTokenVerifier(get_settings())