MrTechie's picture
Deploy backend 33c9c90
3b7f853 verified
Raw History Blame Contribute Delete
2.71 kB
"""Who is asking: the Firebase ID token the web app sends as `Authorization: Bearer <token>`.
The token is a JWT that Firebase Auth signs with Google's keys. It is checked here against those
public keys, the project it was issued for and its expiry, so the server holds no secret. Every
job records the uid that created it, and only that user can see or change it.
"""
from __future__ import annotations
import logging
from collections.abc import Callable
from functools import cache
from typing import Protocol
import jwt
from fastapi import Request
from app.domain.errors import CodedError, ErrorCode
log = logging.getLogger(__name__)
# Firebase Auth's signing keys, as a JSON Web Key Set (Google rotates them; PyJWKClient caches).
KEYS_URL = (
"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"
)
ISSUER = "https://securetoken.google.com/{project}"
LOCAL_USER = "local" # the one user of a server run with auth_required off (tests, local work)
_LEEWAY_SECONDS = 30 # clock drift between Google and this server
class SigningKey(Protocol):
@property
def key(self) -> object: ...
type KeyFor = Callable[[str], SigningKey]
@cache
def _google_keys() -> jwt.PyJWKClient:
return jwt.PyJWKClient(KEYS_URL, cache_keys=True, lifespan=3600)
def google_key_for(token: str) -> SigningKey:
return _google_keys().get_signing_key_from_jwt(token)
def user_of(token: str, project: str, key_for: KeyFor | None = None) -> str:
"""The Firebase uid the token was issued to, once its signature, project and time check.
``key_for``: where the signing key comes from (Google's, looked up when called)."""
try:
key = (key_for or google_key_for)(token).key
claims = jwt.decode(
token,
key=key, # type: ignore[arg-type]
algorithms=["RS256"],
audience=project,
issuer=ISSUER.format(project=project),
leeway=_LEEWAY_SECONDS,
options={"require": ["exp", "iat", "sub", "aud", "iss"]},
)
except (jwt.PyJWTError, ValueError) as error:
# The reason only (expired, wrong project ...), never the token.
log.info("sign-in refused", extra={"reason": type(error).__name__})
raise CodedError(ErrorCode.UNAUTHENTICATED) from error
uid = claims.get("sub")
if not isinstance(uid, str) or not uid:
raise CodedError(ErrorCode.UNAUTHENTICATED)
return uid
def bearer(request: Request) -> str:
scheme, _, token = request.headers.get("authorization", "").partition(" ")
if scheme.lower() != "bearer" or not token.strip():
raise CodedError(ErrorCode.UNAUTHENTICATED)
return token.strip()