Files
romm/backend/utils/device_auth.py
Georges-Antoine Assi 0f75e6aaf4 fix(client-tokens): let a client token revoke itself without me.write (#5419)
* fix(client-tokens): let a client token revoke itself without me.write

A device that signs out or re-pairs had no way to revoke its own token
unless it held me.write, which also lets it mint tokens and approve
pairings. DELETE /api/client-tokens/{id} now skips the me.write check
when the id is the token authenticating the request.

Fixes #5274

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(client-tokens): code-review pass on self-revoke

Annotate raise_auth_error as NoReturn, trim the delete_token docstring, and
cover a me.write token revoking a sibling, the revoked token failing to
authenticate, and socket closure on self-revoke.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(client-tokens): revoke the calling token through DELETE /current

Self-revoke moves to an id-less route so a device never needs to know its
token id, and DELETE /{token_id} keeps me.write in its decorator and in
OpenAPI. The device-authorization token response now also returns token_id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(client-tokens): simplify pass, reuse raise_auth_error for /current

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* revert(client-tokens): drop DELETE /current and the device-flow token_id

Self-revoke stays on DELETE /{token_id} with the in-handler check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(device-auth): return the issued token's id from the device token poll

A device paired through the device-authorization flow can now revoke its
own token with DELETE /api/client-tokens/{id}, as tokens from /exchange can.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Update docs/BACKEND_ARCHITECTURE.md

* docs: format client tokens table

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 19:05:52 -04:00

214 lines
6.9 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 as_text, 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 or isinstance(prev_raw, bool):
return False
try:
prev_ms = int(as_text(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,
}
with sync_cache.pipeline() as pipe:
pipe.set(
_KEY_DC.format(device_code), json.dumps(payload), ex=PENDING_TTL_SECONDS
)
pipe.set(_KEY_UC.format(user_code), device_code, ex=PENDING_TTL_SECONDS)
pipe.execute()
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 as_text(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,
token_id: int,
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,
"token_id": token_id,
"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
_finish_flow(
device_code, user_code, approved, ttl=min(remaining, PENDING_TTL_SECONDS)
)
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}
_finish_flow(device_code, user_code, denied, ttl=DENIED_TTL_SECONDS)
def _finish_flow(
device_code: str, user_code: str | None, result: dict[str, Any], *, ttl: int
) -> None:
"""Store a flow's outcome and retire its user code in one transaction."""
with sync_cache.pipeline() as pipe:
pipe.set(_KEY_DC.format(device_code), json.dumps(result), ex=ttl)
if user_code:
pipe.delete(_KEY_UC.format(user_code))
pipe.execute()
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)