Files
romm/backend/utils/device_auth.py
Sam Dornan 6b13fd1698 chore(deps): bump redis to 8.1 and fakeredis to 2.38, drop types-redis (#4844)
* chore(deps): bump redis to 8.1 and fakeredis to 2.38

redis-py 6.2.0 -> 8.1.0 and fakeredis 2.30.1 -> 2.38.0. RQ 2.12
(redis!=6,>=3.5) and fakeredis (redis>=4.3) both accept redis 8.

fakeredis 2.38 types FakeServer's version argument as a tuple, so pass
(7,) instead of 7. Behaviour is unchanged since fakeredis normalises an
int to a one-element tuple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wzuPg8vDEjsQ8xqvZgFwx

* chore(deps): drop types-redis in favour of redis-py's own types

types-redis only covers redis 4.6 and shadowed the inline types that
redis 8 ships, so mypy was checking calls against a stale API. Removing
it also drops its transitive stub packages (types-cffi, types-pyopenssl,
types-setuptools), which nothing else uses.

redis-py's types differ from the stubs in three ways:
- Redis, AsyncRedis and Pipeline are not generic, so drop the [str] and
  [bytes] parameters.
- Responses are typed bytes | str regardless of decode_responses, so cast
  at the few call sites that rely on the decoded (or raw) type.
- watch, unwatch, multi, aclose and execute_command are unannotated, so
  add redis to untyped_calls_exclude, as is done for rq and apprise.

Also replace setex, deprecated in redis 8, with set(..., ex=...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wzuPg8vDEjsQ8xqvZgFwx

* fix(device-auth): replace deprecated GETSET with SET ... GET

code-review step. GETSET is deprecated since Redis 6.2 in favour of
SET with GET. Using it with ex= also sets the poll key's TTL in the same
command, instead of a separate EXPIRE that a crash could skip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wzuPg8vDEjsQ8xqvZgFwx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 13:28:09 -05:00

207 lines
6.6 KiB
Python

"""Redis-backed state, codes, and rate limits for the device authorization flow.
RFC 8628-style: a client polls a token endpoint while the user approves the
pairing out-of-band through the web UI. State lives entirely in Redis; nothing
about a pending request touches the database until the user approves.
"""
import json
import secrets
from datetime import datetime, timedelta, timezone
from typing import Any, Final, cast
from fastapi import Request
from yarl import URL
from handler.redis_handler import sync_cache
from utils.client_tokens import PAIR_ALPHABET
from utils.rate_limit import enforce_rate_limit, get_client_ip
DEVICE_CODE_BYTES: Final[int] = 32 # -> 64 hex chars
USER_CODE_LENGTH: Final[int] = 8
PENDING_TTL_SECONDS: Final[int] = 600 # 10-minute hard ceiling
DENIED_TTL_SECONDS: Final[int] = 60 # shrink window after explicit deny
POLL_DEFAULT_INTERVAL_SECONDS: Final[int] = 5
AUTHORIZE_RATE_LIMIT: Final[int] = 10
TOKEN_POLL_RATE_LIMIT: Final[int] = 60
RATE_LIMIT_WINDOW_SECONDS: Final[int] = 60
_KEY_DC = "device_auth:dc:{}"
_KEY_UC = "device_auth:uc:{}"
_KEY_POLL_LAST = "device_auth:poll_last:{}"
_KEY_AUTHORIZE_RATE = "device_auth:rate:authorize:{}"
_KEY_TOKEN_RATE = (
"device_auth:rate:token:{}" # nosec B105 -- redis key template, not a secret
)
class FlowStatus:
PENDING = "pending"
APPROVED = "approved"
DENIED = "denied"
def normalize_user_code(code: str) -> str:
"""Strip separators and uppercase a user-typed pairing code."""
return code.replace("-", "").replace(" ", "").upper()
def generate_device_code() -> str:
return secrets.token_hex(DEVICE_CODE_BYTES)
def generate_user_code() -> str:
return "".join(secrets.choice(PAIR_ALPHABET) for _ in range(USER_CODE_LENGTH))
def build_verification_paths(user_code: str) -> tuple[str, str]:
"""Return the web-UI approval paths.
Only a fixed relative path is returned; the client joins it with the origin
it was configured to reach, so the server stays origin-agnostic (in
development the web UI and API run on different ports). The path is a server
constant and never incorporates client input.
"""
verification_path = "/pair/device"
verification_path_complete = str(
URL(verification_path).with_query(user_code=user_code)
)
return verification_path, verification_path_complete
def check_authorize_rate_limit(request: Request) -> None:
enforce_rate_limit(
_KEY_AUTHORIZE_RATE.format(get_client_ip(request)),
max_requests=AUTHORIZE_RATE_LIMIT,
window_seconds=RATE_LIMIT_WINDOW_SECONDS,
detail="Too many authorize attempts. Try again later.",
)
def check_token_poll_rate_limit(request: Request) -> None:
enforce_rate_limit(
_KEY_TOKEN_RATE.format(get_client_ip(request)),
max_requests=TOKEN_POLL_RATE_LIMIT,
window_seconds=RATE_LIMIT_WINDOW_SECONDS,
detail="Too many polling attempts. Try again later.",
)
def polled_too_fast(device_code: str, interval_seconds: int) -> bool:
"""Per-device_code poll pacing check.
Records the wall-clock ms of this call and returns True if the caller
polled inside ``interval_seconds`` of the previous poll.
"""
key = _KEY_POLL_LAST.format(device_code)
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
prev_raw = sync_cache.set(
key, str(now_ms), ex=max(interval_seconds * 4, 30), get=True
)
if prev_raw is None:
return False
try:
prev_ms = int(prev_raw.decode() if isinstance(prev_raw, bytes) else prev_raw)
except ValueError, AttributeError:
return False
return (now_ms - prev_ms) < (interval_seconds * 1000)
def store_pending(device_code: str, user_code: str, data: dict[str, Any]) -> None:
payload = {
**data,
"status": FlowStatus.PENDING,
"user_code": user_code,
}
sync_cache.set(
_KEY_DC.format(device_code), json.dumps(payload), ex=PENDING_TTL_SECONDS
)
sync_cache.set(_KEY_UC.format(user_code), device_code, ex=PENDING_TTL_SECONDS)
def load_pending(device_code: str) -> dict[str, Any] | None:
raw = sync_cache.get(_KEY_DC.format(device_code))
if not raw:
return None
return cast(dict[str, Any] | None, json.loads(raw))
def resolve_device_code_from_user_code(user_code: str) -> str | None:
raw = sync_cache.get(_KEY_UC.format(user_code))
if not raw:
return None
return raw.decode() if isinstance(raw, bytes) else raw
def pending_expires_at(device_code: str) -> datetime:
"""Derive a pending request's deadline from the current Redis TTL."""
remaining = sync_cache.ttl(_KEY_DC.format(device_code))
if remaining is None or remaining < 0:
remaining = 0
return datetime.now(timezone.utc) + timedelta(seconds=int(remaining))
def mark_approved(
device_code: str,
*,
raw_token: str,
device_id: str,
scopes: list[str],
expires_at: datetime | None,
) -> None:
pending = load_pending(device_code)
if pending is None:
return
user_code = pending.get("user_code")
approved = {
"status": FlowStatus.APPROVED,
"raw_token": raw_token,
"device_id": device_id,
"scopes": scopes,
"expires_at": expires_at.isoformat() if expires_at else None,
}
remaining = sync_cache.ttl(_KEY_DC.format(device_code))
if remaining is None or remaining < 1:
remaining = PENDING_TTL_SECONDS
sync_cache.set(
_KEY_DC.format(device_code),
json.dumps(approved),
ex=min(remaining, PENDING_TTL_SECONDS),
)
if user_code:
sync_cache.delete(_KEY_UC.format(user_code))
def mark_denied(device_code: str) -> None:
pending = load_pending(device_code)
if pending is None:
return
user_code = pending.get("user_code")
denied = {"status": FlowStatus.DENIED}
sync_cache.set(
_KEY_DC.format(device_code), json.dumps(denied), ex=DENIED_TTL_SECONDS
)
if user_code:
sync_cache.delete(_KEY_UC.format(user_code))
def consume_approved(device_code: str) -> dict[str, Any] | None:
"""One-shot read of an approved blob. Deletes the key on success.
Callers MUST have already established via ``load_pending`` that the status
is approved; this helper is defensive and will refuse to return a non-
approved payload (and will reinsert it so a subsequent flow can proceed).
"""
raw = sync_cache.getdel(_KEY_DC.format(device_code))
if not raw:
return None
data = json.loads(raw)
if data.get("status") != FlowStatus.APPROVED:
sync_cache.set(
_KEY_DC.format(device_code), json.dumps(data), ex=PENDING_TTL_SECONDS
)
return None
return cast(dict[str, Any], data)