mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 10:32:57 +01:00
* 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>
225 lines
7.2 KiB
Python
225 lines
7.2 KiB
Python
import uuid
|
|
from datetime import datetime, timezone
|
|
from typing import Annotated, Any
|
|
|
|
from fastapi import HTTPException, Request, Response, status
|
|
from pydantic import (
|
|
BaseModel,
|
|
Field,
|
|
StrictBool,
|
|
StringConstraints,
|
|
model_validator,
|
|
)
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.device import DeviceCreateResponse, DeviceSchema
|
|
from handler.auth.constants import Scope
|
|
from handler.database import (
|
|
db_client_token_handler,
|
|
db_device_handler,
|
|
db_device_save_sync_handler,
|
|
)
|
|
from handler.device_install import device_install_handler
|
|
from handler.filesystem import get_fs_sync_handler
|
|
from handler.socket_handler import close_client_token_sockets
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction
|
|
from models.device import Device, SyncMode
|
|
from utils.auth import require_device, token_reaches_device
|
|
from utils.client_tokens import record_token_event
|
|
from utils.router import APIRouter
|
|
|
|
from .install import router as install_router
|
|
|
|
router = APIRouter(
|
|
prefix="/devices",
|
|
tags=["devices"],
|
|
)
|
|
|
|
router.include_router(install_router)
|
|
|
|
# Flags a device reports about itself, such as {"remote_install": true}.
|
|
DeviceCapabilities = Annotated[
|
|
dict[Annotated[str, StringConstraints(min_length=1, max_length=64)], StrictBool],
|
|
Field(max_length=32),
|
|
]
|
|
|
|
|
|
class DeviceCreatePayload(BaseModel):
|
|
name: str | None = None
|
|
platform: str | None = None
|
|
client: str | None = None
|
|
client_version: str | None = None
|
|
ip_address: str | None = None
|
|
mac_address: str | None = None
|
|
hostname: str | None = None
|
|
sync_mode: SyncMode | None = None
|
|
sync_config: dict[str, Any] | None = None
|
|
capabilities: DeviceCapabilities | None = None
|
|
allow_existing: bool = True
|
|
allow_duplicate: bool = False
|
|
reset_syncs: bool = False
|
|
|
|
@model_validator(mode="after")
|
|
def _duplicate_disables_existing(self) -> "DeviceCreatePayload":
|
|
if self.allow_duplicate:
|
|
self.allow_existing = False
|
|
return self
|
|
|
|
|
|
class DeviceUpdatePayload(BaseModel):
|
|
name: str | None = None
|
|
platform: str | None = None
|
|
client: str | None = None
|
|
client_version: str | None = None
|
|
ip_address: str | None = None
|
|
mac_address: str | None = None
|
|
hostname: str | None = None
|
|
sync_enabled: bool | None = None
|
|
sync_mode: SyncMode | None = None
|
|
sync_config: dict[str, Any] | None = None
|
|
capabilities: DeviceCapabilities | None = None
|
|
|
|
|
|
@protected_route(router.post, "", [Scope.DEVICES_WRITE])
|
|
def register_device(
|
|
request: Request,
|
|
response: Response,
|
|
payload: DeviceCreatePayload,
|
|
) -> DeviceCreateResponse:
|
|
existing_device = None
|
|
if not payload.allow_duplicate:
|
|
existing_device = db_device_handler.get_device_by_fingerprint(
|
|
user_id=request.user.id,
|
|
mac_address=payload.mac_address,
|
|
hostname=payload.hostname,
|
|
platform=payload.platform,
|
|
)
|
|
if existing_device and not token_reaches_device(request, existing_device.id):
|
|
existing_device = None
|
|
|
|
if existing_device:
|
|
if not payload.allow_existing:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail={
|
|
"error": "device_exists",
|
|
"message": "A device with this fingerprint already exists",
|
|
"device_id": existing_device.id,
|
|
},
|
|
)
|
|
|
|
if payload.reset_syncs:
|
|
db_device_save_sync_handler.delete_syncs_for_device(
|
|
device_id=existing_device.id
|
|
)
|
|
|
|
db_device_handler.update_last_seen(
|
|
device_id=existing_device.id, user_id=request.user.id
|
|
)
|
|
if payload.capabilities is not None:
|
|
db_device_handler.update_device(
|
|
device_id=existing_device.id,
|
|
user_id=request.user.id,
|
|
data={"capabilities": payload.capabilities},
|
|
)
|
|
log.info(
|
|
f"Returned existing device {existing_device.id} for user {request.user.username}"
|
|
)
|
|
|
|
response.status_code = status.HTTP_200_OK
|
|
return DeviceCreateResponse(
|
|
device_id=existing_device.id,
|
|
name=existing_device.name,
|
|
created_at=existing_device.created_at,
|
|
)
|
|
|
|
response.status_code = status.HTTP_201_CREATED
|
|
device_id = str(uuid.uuid4())
|
|
now = datetime.now(timezone.utc)
|
|
|
|
device = Device(
|
|
id=device_id,
|
|
user_id=request.user.id,
|
|
name=payload.name,
|
|
platform=payload.platform,
|
|
client=payload.client,
|
|
client_version=payload.client_version,
|
|
ip_address=payload.ip_address,
|
|
mac_address=payload.mac_address,
|
|
hostname=payload.hostname,
|
|
sync_mode=payload.sync_mode,
|
|
sync_config=payload.sync_config,
|
|
capabilities=payload.capabilities,
|
|
last_seen=now,
|
|
)
|
|
|
|
db_device = db_device_handler.add_device(device)
|
|
log.info(f"Registered device {device_id} for user {request.user.username}")
|
|
|
|
# Auto-create sync folders for file_transfer devices
|
|
if payload.sync_mode == SyncMode.FILE_TRANSFER:
|
|
try:
|
|
get_fs_sync_handler().ensure_device_directories(device_id)
|
|
except Exception:
|
|
log.warning(f"Failed to create sync directories for device {device_id}")
|
|
|
|
return DeviceCreateResponse(
|
|
device_id=db_device.id,
|
|
name=db_device.name,
|
|
created_at=db_device.created_at,
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.DEVICES_READ])
|
|
def get_devices(request: Request) -> list[DeviceSchema]:
|
|
devices = db_device_handler.get_devices(user_id=request.user.id)
|
|
return [
|
|
DeviceSchema.model_validate(device)
|
|
for device in devices
|
|
if token_reaches_device(request, device.id)
|
|
]
|
|
|
|
|
|
@protected_route(router.get, "/{device_id}", [Scope.DEVICES_READ])
|
|
def get_device(request: Request, device_id: str) -> DeviceSchema:
|
|
device = require_device(request, device_id)
|
|
return DeviceSchema.model_validate(device)
|
|
|
|
|
|
@protected_route(router.put, "/{device_id}", [Scope.DEVICES_WRITE])
|
|
def update_device(
|
|
request: Request,
|
|
device_id: str,
|
|
payload: DeviceUpdatePayload,
|
|
) -> DeviceSchema:
|
|
device: Device | None = require_device(request, device_id)
|
|
|
|
update_data = payload.model_dump(exclude_unset=True)
|
|
if update_data:
|
|
device = db_device_handler.update_device(
|
|
device_id=device_id,
|
|
user_id=request.user.id,
|
|
data=update_data,
|
|
)
|
|
|
|
return DeviceSchema.model_validate(device)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{device_id}",
|
|
[Scope.DEVICES_WRITE],
|
|
status_code=status.HTTP_204_NO_CONTENT,
|
|
)
|
|
async def delete_device(request: Request, device_id: str) -> None:
|
|
require_device(request, device_id)
|
|
|
|
tokens = db_client_token_handler.get_tokens_by_device(device_id)
|
|
db_device_handler.delete_device(device_id=device_id, user_id=request.user.id)
|
|
log.info(f"Deleted device {device_id} for user {request.user.username}")
|
|
for token in tokens:
|
|
record_token_event(request, AuditAction.CLIENT_TOKEN_REVOKE, token)
|
|
await close_client_token_sockets([token.id for token in tokens])
|
|
await device_install_handler.discard_for_device(device_id)
|