Spaces:
Sleeping

File size: 4,029 Bytes
73ecc58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793dbf7
 
73ecc58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793dbf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73ecc58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Firebase sign-in check and per-user rate limits for the chat routes."""

from __future__ import annotations

import os
import time
from collections import defaultdict, deque
from typing import Callable

import jwt
from jwt import PyJWKClient

FIREBASE_PROJECT_ID = os.environ.get("FIREBASE_PROJECT_ID", "smallconfidence")
FIREBASE_JWKS_URL = (
    "https://www.googleapis.com/service_accounts/v1/jwk/"
    "securetoken@system.gserviceaccount.com"
)


class AuthError(Exception):
    pass


_jwks_client: PyJWKClient | None = None


def _default_jwks() -> PyJWKClient:
    global _jwks_client
    if _jwks_client is None:
        _jwks_client = PyJWKClient(FIREBASE_JWKS_URL, cache_keys=True)
    return _jwks_client


def verify_firebase_token(
    token: str,
    jwks: PyJWKClient | None = None,
    project_id: str = FIREBASE_PROJECT_ID,
) -> str:
    """Returns the Firebase uid for a valid ID token, else raises AuthError."""
    if not token:
        raise AuthError("Sign in to chat.")
    if os.environ.get("FIREBASE_AUTH_EMULATOR_HOST"):
        return _verify_emulator_token(token, project_id)
    try:
        key = (jwks or _default_jwks()).get_signing_key_from_jwt(token)
        claims = jwt.decode(
            token,
            key.key,
            algorithms=["RS256"],
            audience=project_id,
            issuer=f"https://securetoken.google.com/{project_id}",
            options={"require": ["exp", "iat", "sub"]},
            leeway=30,
        )
    except Exception as exc:  # noqa: BLE001
        raise AuthError("Your sign-in has expired. Please sign in again.") from exc
    uid = claims.get("sub")
    if not isinstance(uid, str) or not uid:
        raise AuthError("Your sign-in has expired. Please sign in again.")
    return uid


def _verify_emulator_token(token: str, project_id: str) -> str:
    """Local Firebase Auth emulator only (`./run.sh --local` in the app).

    The emulator signs nothing, so only the claims are checked. Never active on
    the Space: it runs only when FIREBASE_AUTH_EMULATOR_HOST is set, as with
    firebase-admin.
    """
    try:
        claims = jwt.decode(
            token,
            options={
                "verify_signature": False,
                "verify_exp": True,
                "verify_aud": True,
                "verify_iss": True,
                "require": ["exp", "iat", "sub"],
            },
            audience=project_id,
            issuer=f"https://securetoken.google.com/{project_id}",
            leeway=30,
        )
    except Exception as exc:  # noqa: BLE001
        raise AuthError("Your sign-in has expired. Please sign in again.") from exc
    uid = claims.get("sub")
    if not isinstance(uid, str) or not uid:
        raise AuthError("Your sign-in has expired. Please sign in again.")
    return uid


def bearer_token(header: str | None) -> str:
    if not header:
        return ""
    scheme, _, value = header.partition(" ")
    return value.strip() if scheme.lower() == "bearer" else ""


class RateLimiter:
    """Sliding-window limits per key (uid). In memory: the Space runs one process."""

    def __init__(
        self,
        per_minute: int,
        per_day: int,
        clock: Callable[[], float] = time.monotonic,
    ):
        self.per_minute = per_minute
        self.per_day = per_day
        self._clock = clock
        self._hits: dict[str, deque[float]] = defaultdict(deque)

    def check(self, key: str) -> str | None:
        """Records a hit and returns None, or returns why it is refused."""
        now = self._clock()
        hits = self._hits[key]
        while hits and now - hits[0] >= 86400:
            hits.popleft()
        if len(hits) >= self.per_day:
            return "You've reached today's message limit. Let's pick this up tomorrow."
        recent = sum(1 for t in hits if now - t < 60)
        if recent >= self.per_minute:
            return "You're sending messages quickly. Take a breath and try again in a minute."
        hits.append(now)
        return None