feat(backend): paired devices with device tokens, scope, limits and terminal login
Platform v2 step 1.8 (APPS_PLATFORM D-8, section 6.3).
- devices + device_pair_requests tables (Alembic 0007_devices); sessions.device_id
becomes a FK. Device tokens are stored as sha256 only; the plain token is generated
when the device picks it up, once.
- /api/devices: pair-request (public, rate-limited, LAN-only in the proxy) + polling
with a per-request secret; manager approve/list/rename/config/login mode/link/
reassign/revoke (key core.devices.manage); the device's own /me and /me/users.
- Approving or reassigning checks the app's licence and its `devices` limit
(license.limit_reached); after a downgrade the newest devices beyond the limit are
refused, the oldest keep working.
- X-Xenia-Device: core/access/context.py loads the device (device.not_paired /
device.revoked), tags logs with device=, throttles last_seen_at. check() and
module_required() apply the app's scope (device.out_of_scope); require_device(app).
- POST /api/auth/login {client: "terminal"} uses the device's login mode (device ->
auth.default_login_mode -> app's first mode); tap/none only here. The session is
bound to the device (device.required without its header) and replaces the
device's previous user. Revoke/reassign end the device's sessions.
- Registry: a device app with user logins must declare '<app>.access'.
- Proxy: location /api/devices/pair-request LAN-only on the :443 servers (both copies).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"""Access control (APPS_PLATFORM §3, D-7, D-8, D-17).
|
||||
|
||||
allowed(key) = module_of(key) is effective (licence ∪ free) ∩ enabled
|
||||
AND (no device OR key in the device app's scope) step 1.8
|
||||
AND (no device OR key in the device app's scope) devices (D-8)
|
||||
AND (user is superadmin OR user holds key user_permissions
|
||||
OR a valid manager-override token for key) step 1.9
|
||||
|
||||
@@ -10,13 +10,18 @@ Use it through the route markers in core/access/deps.py:
|
||||
require_any("a.b", "c.d") any of several keys
|
||||
signed_in any logged-in user (routers.deps.get_current_user)
|
||||
public() deliberately open (health, login, pairing...)
|
||||
require_device("kds") device-only endpoints (step 1.8)
|
||||
require_device("kds") device-only endpoints: a paired device running kds
|
||||
require_device() any paired device (returns the Device)
|
||||
and inside code with can(user, key) for conditional behaviour (e.g. managers see all orders).
|
||||
|
||||
Every route must carry one of these markers somewhere in its dependencies; the guard
|
||||
tests/guards/test_route_access.py fails otherwise.
|
||||
|
||||
Files: templates.py (role templates from manifests), check.py (the decision),
|
||||
Devices (D-8): a request with header X-Xenia-Device carries a paired device
|
||||
(context.py). Its scope limits both keys (check) and which modules' routes it may reach
|
||||
(module_required), and a user session started on a device only works with that device.
|
||||
|
||||
Files: context.py (device lookup, scope, get_context), templates.py (role templates from manifests), check.py (the decision),
|
||||
deps.py (route markers), legacy.py (temporary v1 perm_* projection for the current
|
||||
frontends, §3.3), queries.py (find users holding a key).
|
||||
"""
|
||||
|
||||
@@ -11,8 +11,8 @@ from core.modules.registry import all_permissions
|
||||
@dataclass
|
||||
class AccessContext:
|
||||
user: Any = None # User row, or the support ghost (step 1.10); None for device-only calls
|
||||
session: Any = None # step 1.6
|
||||
device: Any = None # step 1.8
|
||||
session: Any = None # session id (sid) of the user's login
|
||||
device: Any = None # Device row when the call comes from a paired device (D-8)
|
||||
override_keys: frozenset = frozenset() # step 1.9
|
||||
|
||||
|
||||
@@ -49,7 +49,10 @@ def check(ctx: AccessContext, key: str, db=None) -> None:
|
||||
module = module_of(key)
|
||||
if not is_effective(module, db):
|
||||
raise blocked_error(module, db)
|
||||
# device scope: step 1.8
|
||||
if ctx.device is not None:
|
||||
from core.access.context import in_scope
|
||||
if not in_scope(ctx.device.app_key, key):
|
||||
raise XeniaError("device.out_of_scope", app=ctx.device.app_key, key=key)
|
||||
if holds(ctx.user, key) or key in ctx.override_keys:
|
||||
return
|
||||
raise XeniaError("access.denied", key=key)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""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. SSE/WebSocket (token in the query, browsers
|
||||
can't set headers there) only stream events and are not bound; revisit in phase 3.
|
||||
"""
|
||||
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:
|
||||
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 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)
|
||||
return AccessContext(user=user, session=sid, device=device)
|
||||
@@ -6,10 +6,11 @@ any route without a marker, so "forgot to protect" can't ship.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.access.check import AccessContext, check
|
||||
from core.access.context import current_device
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
|
||||
@@ -25,8 +26,8 @@ def require(key: str):
|
||||
# tests/guards/test_route_access.py checks every marker's key exists.
|
||||
from routers.deps import get_current_user
|
||||
|
||||
def _dep(user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
check(AccessContext(user=user), key, db)
|
||||
def _dep(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
check(AccessContext(user=user, device=current_device(request, db)), key, db)
|
||||
return user
|
||||
|
||||
_dep.__name__ = f"require_{key.replace('.', '_')}"
|
||||
@@ -37,11 +38,12 @@ def require_any(*keys: str):
|
||||
"""The user must hold at least one of `keys` (in an effective module). Returns the user."""
|
||||
from routers.deps import get_current_user
|
||||
|
||||
def _dep(user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
def _dep(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
last = None
|
||||
ctx = AccessContext(user=user, device=current_device(request, db))
|
||||
for k in keys:
|
||||
try:
|
||||
check(AccessContext(user=user), k, db)
|
||||
check(ctx, k, db)
|
||||
return user
|
||||
except XeniaError as e:
|
||||
last = e
|
||||
@@ -58,8 +60,22 @@ def public():
|
||||
return _mark(_dep, "public")
|
||||
|
||||
|
||||
def require_device(app_key: str):
|
||||
"""Device-only endpoint for paired devices running `app_key` (implemented in step 1.8)."""
|
||||
def _dep():
|
||||
raise XeniaError("device.not_paired")
|
||||
return _mark(_dep, "require_device", app_key)
|
||||
def require_device(app_key: str | None = None):
|
||||
"""Device-only endpoint (D-8): the request must carry a valid X-Xenia-Device token.
|
||||
With `app_key`, the device must run that app and the app's module must be effective
|
||||
(licensed and enabled). Without it, any paired device (e.g. GET /api/devices/me, which
|
||||
must answer even when the app is turned off so the screen can say so). Returns the Device."""
|
||||
def _dep(request: Request, db: Session = Depends(get_db)):
|
||||
dev = current_device(request, db)
|
||||
if dev is None:
|
||||
raise XeniaError("device.not_paired")
|
||||
if app_key is not None:
|
||||
if dev.app_key != app_key:
|
||||
raise XeniaError("device.out_of_scope", app=dev.app_key, key=app_key)
|
||||
from core.modules.state import blocked_error, is_effective
|
||||
if not is_effective(app_key, db):
|
||||
raise blocked_error(app_key, db)
|
||||
return dev
|
||||
|
||||
_dep.__name__ = f"require_device_{app_key or 'any'}"
|
||||
return _mark(_dep, "require_device", app_key or "*")
|
||||
|
||||
Reference in New Issue
Block a user