Files
romm/backend/utils/client_tokens.py
Georges-Antoine Assi f66950551a fix(sync): bind device tokens to their device; dial only known push-pull hosts (#5460)
* fix(sync): bind device tokens to their device; dial only known push-pull hosts

A client token paired to one device could read, reconfigure, delete, sync
saves for and record play sessions as any other device of the same user.
Device CRUD, sync negotiate/complete, push-pull trigger, the save device
resolver and play-session ingest now treat another device as not found for
a bound token, through a shared require_token_device helper. GET /api/devices
lists only the bound device.

Push-pull let any user with devices.write point ssh_host at any host and
port, and the connection error surfaced through the sync session, so the
worker could be used to probe the internal network. The SSH handler now
refuses a host with no trusted key or CA in the admin's known_hosts before
dialling it, which keeps LAN handhelds working while nothing else is
reached.

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

* fix(device): revoke a deleted device's tokens; scope registration matches

Addresses Greptile review on #5460. Deleting a device now deletes the client
tokens paired to it, since the foreign key's SET NULL turned them into unbound
tokens that reach every device. Registration with a bound token only matches
its own device by fingerprint, so it can no longer reset syncs or overwrite
capabilities on another device.

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

* fix(sync): bind heartbeat, sync session and online reads; pin push-pull ports

pr-ready step 2 (code-review xhigh --fix).

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

* refactor(device): one require_device helper; parse known_hosts once

pr-ready step 3 (simplify).

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

* test(sync): narrow await_args before reading known_hosts

pr-ready step 4 (review-polish).

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

* docs(sync): plainer comments on the push-pull allowlist and token revoke

pr-ready step 5 (humanizer).

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

* fix(device): keep bound tokens off other tokens; cascade tokens with their device

A device-bound token can no longer create tokens, or regenerate, pair or
revoke a token of another device or an unbound one. The save session_id
counter only counts a session of the caller's bound device.

client_tokens.device_id now cascades on device delete (0159), so no path
can leave an unbound token behind, and deleting a device records a
client_token.revoke audit event for each token it takes.

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

* chore(env): drop the push-pull allowlist note from env.template

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:57:33 -05:00

188 lines
6.0 KiB
Python

import json
import secrets
from collections.abc import Iterable
from datetime import datetime, timedelta, timezone
from fastapi import HTTPException, Request, status
from endpoints.responses.client_token import (
ClientTokenAdminSchema,
ClientTokenCreateSchema,
ClientTokenSchema,
)
from handler.audit_handler import AuditTarget, record
from handler.auth.base_handler import auth_handler
from handler.database import db_client_token_handler, db_user_handler
from handler.redis_handler import sync_cache
from models.audit_event import AuditAction, AuditTargetType
from models.client_token import ClientToken
from utils.auth import token_reaches_device
from utils.rate_limit import enforce_rate_limit, get_client_ip
PAIR_CODE_LENGTH = 8
PAIR_CODE_TTL_SECONDS = 60
RATE_LIMIT_MAX_ATTEMPTS = 5
RATE_LIMIT_WINDOW_SECONDS = 60
PAIR_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
EXPIRY_MAP = {
"30d": timedelta(days=30),
"90d": timedelta(days=90),
"1y": timedelta(days=365),
}
def generate_pair_code() -> str:
return "".join(secrets.choice(PAIR_ALPHABET) for _ in range(PAIR_CODE_LENGTH))
def parse_expiry(expires_in: str | None) -> datetime | None:
if expires_in is None or expires_in == "never":
return None
delta = EXPIRY_MAP.get(expires_in)
if delta is None:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail=f"Invalid expires_in value: {expires_in}. "
f"Valid values: {', '.join(EXPIRY_MAP.keys())}, never",
)
return datetime.now(timezone.utc) + delta
def validate_scopes(requested: Iterable[str], caller_scopes: Iterable[str]) -> None:
"""Reject scopes the caller doesn't hold, so a token can't mint a broader one.
Args:
caller_scopes: ``request.auth.scopes``, which for a client or OAuth token
is the token's scopes rather than the whole account's.
"""
invalid = set(requested) - {str(s) for s in caller_scopes}
if invalid:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Requested scopes exceed your permissions: "
f"{', '.join(sorted(invalid))}",
)
def validate_token_within_caller(request: Request, token: ClientToken) -> None:
"""Reject acting on a token that grants scopes the caller doesn't hold."""
validate_scopes(token.effective_scopes(request.user), request.auth.scopes)
def validate_token_device(request: Request, token: ClientToken) -> None:
"""Hide tokens of other devices, and unbound ones, from a device-bound token."""
if not token_reaches_device(request, token.device_id):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Token not found",
)
def record_token_event(
request: Request, action: AuditAction, token: ClientToken
) -> None:
record(
action,
request,
AuditTarget(AuditTargetType.CLIENT_TOKEN, token.id, token.name),
{"owner_id": token.user_id, "scopes": token.scopes.split()},
)
def validate_token_reissue(request: Request, token: ClientToken) -> None:
"""Reject re-issuing a token's secret unless the caller holds every scope it stores.
A stored scope the account has lost comes back if the account regains it.
"""
validate_scopes(token.scopes.split(), request.auth.scopes)
def check_rate_limit(request: Request) -> None:
enforce_rate_limit(
f"client-token-rate:{get_client_ip(request)}",
max_requests=RATE_LIMIT_MAX_ATTEMPTS,
window_seconds=RATE_LIMIT_WINDOW_SECONDS,
detail="Too many exchange attempts. Try again later.",
)
def build_create_schema(token: ClientToken, raw_token: str) -> ClientTokenCreateSchema:
return ClientTokenCreateSchema(
id=token.id,
name=token.name,
scopes=token.scopes.split(),
expires_at=token.expires_at,
last_used_at=token.last_used_at,
created_at=token.created_at,
user_id=token.user_id,
device_id=token.device_id,
raw_token=raw_token,
)
def build_schema(token: ClientToken) -> ClientTokenSchema:
return ClientTokenSchema(
id=token.id,
name=token.name,
scopes=token.scopes.split(),
expires_at=token.expires_at,
last_used_at=token.last_used_at,
created_at=token.created_at,
user_id=token.user_id,
device_id=token.device_id,
)
def build_admin_schema(token: ClientToken) -> ClientTokenAdminSchema:
return ClientTokenAdminSchema(
id=token.id,
name=token.name,
scopes=token.scopes.split(),
expires_at=token.expires_at,
last_used_at=token.last_used_at,
created_at=token.created_at,
user_id=token.user_id,
device_id=token.device_id,
username=token.user.username,
user_avatar_path=token.user.avatar_path,
user_updated_at=token.user.updated_at,
)
def exchange(request: Request, code: str) -> ClientTokenCreateSchema:
check_rate_limit(request)
normalized = code.replace("-", "").upper()
redis_key = f"pair:{normalized}"
data = sync_cache.getdel(redis_key)
if not data:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Invalid or expired pairing code",
)
params = json.loads(data)
user = db_user_handler.get_user(params["user_id"])
if user is None or not user.enabled:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Token owner is disabled",
)
raw_token = auth_handler.generate_client_token()
new_hash = auth_handler.hash_client_token(raw_token)
token = db_client_token_handler.update_hashed_token(
token_id=params["token_id"],
new_hash=new_hash,
user_id=params["user_id"],
)
if token is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Token no longer exists",
)
return build_create_schema(token, raw_token)