|
| 1 | +"""P1-8: Sign in with Apple — server-side identity-token verification and |
| 2 | +(credential-gated) token revocation for account deletion. |
| 3 | +
|
| 4 | +The iOS app sends Apple's ``identityToken`` (a JWT signed by Apple). We verify |
| 5 | +it against Apple's published JWKS: RS256 signature, ``iss`` == Apple, ``aud`` == |
| 6 | +our bundle id, and ``exp``. Revocation on account deletion needs a client-secret |
| 7 | +JWT signed with the team's ``.p8`` — only performed when those credentials are |
| 8 | +configured; otherwise local data is still deleted and revocation is skipped with |
| 9 | +a WARNING. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import logging |
| 15 | +import time |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +APPLE_ISSUER = "https://appleid.apple.com" |
| 21 | +APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys" |
| 22 | +APPLE_REVOKE_URL = "https://appleid.apple.com/auth/revoke" |
| 23 | +_JWKS_TTL_SECONDS = 3600 |
| 24 | + |
| 25 | + |
| 26 | +class AppleAuthError(Exception): |
| 27 | + """Identity-token verification failed (generic — no internal detail leaks).""" |
| 28 | + |
| 29 | + |
| 30 | +class AppleAuthNotConfigured(Exception): |
| 31 | + """auth.apple.bundle_id is unset — the route must fail closed (503).""" |
| 32 | + |
| 33 | + |
| 34 | +class AppleJWKSCache: |
| 35 | + """Fetches and TTL-caches Apple's JWKS. ``fetcher`` is injectable for tests.""" |
| 36 | + |
| 37 | + def __init__(self, fetcher=None, ttl: float = _JWKS_TTL_SECONDS) -> None: |
| 38 | + self._fetcher = fetcher or _default_fetch_jwks |
| 39 | + self._ttl = ttl |
| 40 | + self._keys: dict[str, Any] = {} |
| 41 | + self._fetched_at: float = 0.0 |
| 42 | + |
| 43 | + async def get_key(self, kid: str, *, now: float): |
| 44 | + if not self._keys or (now - self._fetched_at) > self._ttl: |
| 45 | + raw = await self._fetcher() |
| 46 | + self._keys = {k["kid"]: k for k in raw.get("keys", [])} |
| 47 | + self._fetched_at = now |
| 48 | + return self._keys.get(kid) |
| 49 | + |
| 50 | + |
| 51 | +async def _default_fetch_jwks() -> dict: |
| 52 | + import aiohttp |
| 53 | + |
| 54 | + async with aiohttp.ClientSession() as session: |
| 55 | + async with session.get(APPLE_JWKS_URL, timeout=aiohttp.ClientTimeout(total=10)) as r: |
| 56 | + return await r.json() |
| 57 | + |
| 58 | + |
| 59 | +def apple_bundle_id(config: dict) -> str: |
| 60 | + auth = ((config or {}).get("auth") or {}).get("apple") or {} |
| 61 | + return str(auth.get("bundle_id", "")).strip() |
| 62 | + |
| 63 | + |
| 64 | +async def verify_apple_identity_token( |
| 65 | + identity_token: str, |
| 66 | + *, |
| 67 | + config: dict, |
| 68 | + jwks_cache: AppleJWKSCache, |
| 69 | + now: float | None = None, |
| 70 | +) -> dict: |
| 71 | + """Verify Apple's identity token; return its claims or raise. |
| 72 | +
|
| 73 | + Fail-closed: if bundle_id is unconfigured we NEVER verify against a wildcard |
| 74 | + audience — the caller returns 503. |
| 75 | + """ |
| 76 | + bundle_id = apple_bundle_id(config) |
| 77 | + if not bundle_id: |
| 78 | + raise AppleAuthNotConfigured() |
| 79 | + |
| 80 | + try: |
| 81 | + import jwt |
| 82 | + from jwt.algorithms import RSAAlgorithm |
| 83 | + except Exception as exc: # PyJWT / cryptography missing |
| 84 | + raise AppleAuthError("jwt library unavailable") from exc |
| 85 | + |
| 86 | + now = time.time() if now is None else now |
| 87 | + try: |
| 88 | + header = jwt.get_unverified_header(identity_token) |
| 89 | + except Exception as exc: |
| 90 | + raise AppleAuthError("malformed token") from exc |
| 91 | + |
| 92 | + kid = header.get("kid") |
| 93 | + jwk = await jwks_cache.get_key(kid, now=now) |
| 94 | + if jwk is None: |
| 95 | + raise AppleAuthError("unknown signing key") |
| 96 | + |
| 97 | + try: |
| 98 | + public_key = RSAAlgorithm.from_jwk(jwk) |
| 99 | + claims = jwt.decode( |
| 100 | + identity_token, |
| 101 | + public_key, |
| 102 | + algorithms=["RS256"], |
| 103 | + audience=bundle_id, |
| 104 | + issuer=APPLE_ISSUER, |
| 105 | + options={"require": ["exp", "iss", "aud"]}, |
| 106 | + ) |
| 107 | + except Exception as exc: |
| 108 | + raise AppleAuthError("token verification failed") from exc |
| 109 | + return claims |
| 110 | + |
| 111 | + |
| 112 | +def apple_revocation_configured(config: dict) -> bool: |
| 113 | + auth = ((config or {}).get("auth") or {}).get("apple") or {} |
| 114 | + return bool(auth.get("team_id") and auth.get("key_id") and auth.get("private_key_p8")) |
0 commit comments