"""Who is calling: the request's device and user (APPS_PLATFORM ยง3.1, D-8, step 1.8). - current_device(request, db): the paired device named by header `X-Xenia-Device`, or None when the header is absent. Unknown token -> device.not_paired; revoked -> device.revoked; beyond its app's `devices` limit -> license.limit_reached. Cached on request.state, so the several dependencies that need it look it up once per request. - get_context: FastAPI dependency -> AccessContext(user | None, session sid | None, device | None). For endpoints that accept a device alone or a device + user. - Device scope (D-8): a device may only use permission keys of its own app plus the patterns in its manifest's DeviceApp.scope (in_scope), and only routes of those modules (module_in_scope, applied by core.modules.state.module_required to every non-core router). Core routes stay reachable (login, /me, bootstrap, live events); keyed core routes are still checked key by key. Agent notes: - The token is a long random secret; only its sha256 is stored (models/device.py). - last_seen_at is written at most every LAST_SEEN_EVERY_S. - A user session started on a device (client "terminal") is bound to it: routers.deps. get_current_user refuses it without that device's header (device.required), so scope can't be escaped by dropping the header. The WebSocket (routers/ws.py, 3.1a) applies the same rule with the device token in its first frame; the legacy SSE stream doesn't (it goes in phase 4). """ from __future__ import annotations import hashlib from datetime import timedelta from fnmatch import fnmatchcase from typing import Optional from fastapi import Depends, Request from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from sqlalchemy.orm import Session from core.access.check import AccessContext from core.errors import XeniaError from core.timeutil import utcnow from database import get_db DEVICE_HEADER = "X-Xenia-Device" LAST_SEEN_EVERY_S = 60 _NO_DEVICE = object() _optional_bearer = HTTPBearer(auto_error=False) def hash_token(token: str) -> str: return hashlib.sha256(token.encode()).hexdigest() def device_app(app_key: str): """The DeviceApp of an app module, or None.""" from core.modules.registry import registry m = registry().get(app_key) return m.device_app if m is not None else None def scope_patterns(app_key: str) -> tuple[str, ...]: da = device_app(app_key) return (f"{app_key}.*",) + (tuple(da.scope) if da else ()) def in_scope(app_key: str, key: str) -> bool: """May a device running `app_key` use permission `key`?""" return any(fnmatchcase(key, p) for p in scope_patterns(app_key)) def module_in_scope(app_key: str, module: str) -> bool: """May a device running `app_key` call routes of `module` at all?""" return module == app_key or any(p.split(".", 1)[0] == module for p in scope_patterns(app_key)) def over_limit(db, device) -> Optional[int]: """The app's device limit if this device is beyond it (oldest devices keep working after a downgrade, D-6), else None.""" from core.modules import entitlements from models.device import Device cap = entitlements.limit(device.app_key, "devices") if cap is None: return None older = db.query(Device).filter(Device.app_key == device.app_key, Device.revoked_at.is_(None), Device.id < device.id).count() return cap if older >= cap else None def lookup_device(db, token: str): """The Device for a raw token, applying revocation and the limit. Raises XeniaError.""" from core.logging import set_log_context from models.device import Device dev = db.query(Device).filter(Device.token_hash == hash_token(token)).first() if dev is None: raise XeniaError("device.not_paired") if dev.revoked_at is not None: raise XeniaError("device.revoked") cap = over_limit(db, dev) if cap is not None: from routers.devices import notify_limit notify_limit(dev.app_key, "devices", cap, db) raise XeniaError("license.limit_reached", module=dev.app_key, limit="devices", max=cap) set_log_context(device=dev.id) now = utcnow() if dev.last_seen_at is None or now - dev.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S): dev.last_seen_at = now db.commit() # runs before the endpoint body, so nothing else is pending yet return dev def current_device(request: Request, db) -> Optional[object]: cached = getattr(request.state, "xenia_device", _NO_DEVICE) if cached is not _NO_DEVICE: return cached token = request.headers.get(DEVICE_HEADER) dev = lookup_device(db, token) if token else None request.state.xenia_device = dev return dev def check_device_scope(device, module: str) -> None: if device is not None and not module_in_scope(device.app_key, module): raise XeniaError("device.out_of_scope", app=device.app_key, key=module) def context_for(request: Request, user, db) -> AccessContext: """AccessContext of a request whose user is already known (require() and inline checks).""" from core.access.override import HEADER return AccessContext(user=user, session=getattr(request.state, "xenia_sid", None), device=current_device(request, db), override_token=request.headers.get(HEADER), target=f"{request.method} {request.url.path}") def authorize(request: Request, db, user, key: str, target: str | None = None): """check() from inside an endpoint (module, device scope, key, manager override). Returns the AccessOverride row when a manager approved it, else None.""" from core.access.check import check ctx = context_for(request, user, db) if target: ctx.target = target return check(ctx, key, db) def get_context(request: Request, db: Session = Depends(get_db), credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer)) -> AccessContext: """Device (if any) + user (if a bearer token is sent). An invalid token is an error here: endpoints that want "anonymous unless valid" (bootstrap) handle that themselves.""" from routers.deps import user_from_token device = current_device(request, db) user = sid = None if credentials: user, sid = user_from_token(credentials.credentials, request, db) from core.access.override import HEADER return AccessContext(user=user, session=sid, device=device, override_token=request.headers.get(HEADER), target=f"{request.method} {request.url.path}")