File size: 2,613 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""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())