Files
romm/backend/tests/endpoints/test_activity.py
T
Georges-Antoine AssiandClaude Opus 5.5 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

394 lines
13 KiB
Python

from collections.abc import Iterator
from datetime import timedelta
from typing import Any
from unittest.mock import AsyncMock, patch
import httpx2
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from tests.factories import make_device_token
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
from handler.auth.base_handler import oauth_handler
from handler.database import db_device_handler
from handler.database.base_handler import sync_session
from handler.socket_handler import socket_handler
from models.device import Device
from models.permission import HiddenEntity, PermEntity
from models.platform import Platform
from models.rom import Rom
from models.user import User
def _auth(user: User, scopes: list[str] | None = None) -> dict[str, str]:
token = oauth_handler.create_access_token(
data={
"sub": user.username,
"iss": "romm:oauth",
"scopes": " ".join(user.oauth_scopes if scopes is None else scopes),
},
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
)
return {"Authorization": f"Bearer {token}"}
def _device(user: User, device_id: str, client: str | None = "grout") -> Device:
return db_device_handler.add_device(
Device(id=device_id, user_id=user.id, client=client)
)
def _hide(entity: PermEntity, entity_id: int, user: User) -> None:
with sync_session.begin() as session:
session.add(HiddenEntity(entity=entity, entity_id=entity_id, user_id=user.id))
@pytest.fixture
def emit() -> Iterator[AsyncMock]:
with patch.object(
socket_handler.socket_server, "emit", new_callable=AsyncMock
) as emit:
yield emit
def _heartbeat(
client: TestClient, user: User, device_id: str, rom_id: int
) -> httpx2.Response:
return client.post(
"/api/activity/heartbeat",
headers=_auth(user),
json={"rom_id": rom_id, "device_id": device_id},
)
class TestHeartbeat:
def test_publishes_the_session_for_a_registered_device(
self, client: TestClient, admin_user: User, rom: Rom, emit: AsyncMock
):
_device(admin_user, "deck")
response = _heartbeat(client, admin_user, "deck", rom.id)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body["user_id"] == admin_user.id
assert body["rom_id"] == rom.id
assert body["device_id"] == "deck"
assert body["device_type"] == "grout"
emit.assert_awaited_once_with(
"activity:update", body, to=[f"user:{admin_user.id}"]
)
listed = client.get("/api/activity", headers=_auth(admin_user)).json()
assert listed == [body]
def test_marks_the_device_as_seen(
self, client: TestClient, admin_user: User, rom: Rom, emit: AsyncMock
):
_device(admin_user, "deck")
_heartbeat(client, admin_user, "deck", rom.id)
device = db_device_handler.get_device(device_id="deck", user_id=admin_user.id)
assert device is not None
assert device.last_seen is not None
def test_a_repeat_heartbeat_keeps_the_start_time(
self, client: TestClient, admin_user: User, rom: Rom, emit: AsyncMock
):
_device(admin_user, "deck")
first = _heartbeat(client, admin_user, "deck", rom.id).json()
second = _heartbeat(client, admin_user, "deck", rom.id).json()
assert second["started_at"] == first["started_at"]
def test_a_device_without_a_client_is_unknown(
self, client: TestClient, admin_user: User, rom: Rom, emit: AsyncMock
):
_device(admin_user, "deck", client=None)
body = _heartbeat(client, admin_user, "deck", rom.id).json()
assert body["device_type"] == "unknown"
def test_another_users_device_is_not_found(
self,
client: TestClient,
admin_user: User,
viewer_user: User,
rom: Rom,
emit: AsyncMock,
):
_device(viewer_user, "their-deck")
response = _heartbeat(client, admin_user, "their-deck", rom.id)
assert response.status_code == status.HTTP_404_NOT_FOUND
emit.assert_not_awaited()
assert client.get("/api/activity", headers=_auth(admin_user)).json() == []
def test_an_unknown_rom_is_not_found(
self, client: TestClient, admin_user: User, emit: AsyncMock
):
_device(admin_user, "deck")
response = _heartbeat(client, admin_user, "deck", 999_999)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json()["detail"] == "ROM 999999 not found"
emit.assert_not_awaited()
device = db_device_handler.get_device(device_id="deck", user_id=admin_user.id)
assert device is not None
assert device.last_seen is None
def test_a_rom_hidden_from_the_player_is_not_found(
self, client: TestClient, viewer_user: User, rom: Rom, emit: AsyncMock
):
# Hidden ROMs answer 404 everywhere else, so the heartbeat must not
# hand back the name and cover of one.
_device(viewer_user, "deck")
_hide(PermEntity.ROMS, rom.id, viewer_user)
response = _heartbeat(client, viewer_user, "deck", rom.id)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json()["detail"] == f"ROM {rom.id} not found"
emit.assert_not_awaited()
@pytest.mark.parametrize(
"payload",
[
{"rom_id": 0, "device_id": "deck"},
{"rom_id": 1, "device_id": ""},
{"rom_id": 1, "device_id": "d" * 256},
{"device_id": "deck"},
],
ids=["rom_zero", "empty_device", "long_device", "no_rom"],
)
def test_an_invalid_payload_is_rejected(
self,
client: TestClient,
admin_user: User,
emit: AsyncMock,
payload: dict[str, Any],
):
response = client.post(
"/api/activity/heartbeat", headers=_auth(admin_user), json=payload
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
emit.assert_not_awaited()
def test_needs_the_write_scope(
self, client: TestClient, admin_user: User, rom: Rom, emit: AsyncMock
):
_device(admin_user, "deck")
response = client.post(
"/api/activity/heartbeat",
headers=_auth(admin_user, ["roms.user.read"]),
json={"rom_id": rom.id, "device_id": "deck"},
)
assert response.status_code == status.HTTP_403_FORBIDDEN
emit.assert_not_awaited()
class TestClear:
def test_ends_the_callers_session(
self, client: TestClient, admin_user: User, rom: Rom, emit: AsyncMock
):
_device(admin_user, "deck")
_heartbeat(client, admin_user, "deck", rom.id)
emit.reset_mock()
response = client.delete(
"/api/activity/heartbeat",
headers=_auth(admin_user),
params={"device_id": "deck"},
)
assert response.status_code == status.HTTP_204_NO_CONTENT
emit.assert_awaited_once_with(
"activity:clear",
{"user_id": admin_user.id, "device_id": "deck", "rom_id": rom.id},
to=[f"user:{admin_user.id}"],
)
assert client.get("/api/activity", headers=_auth(admin_user)).json() == []
def test_leaves_another_users_session_alone(
self,
client: TestClient,
admin_user: User,
editor_user: User,
rom: Rom,
emit: AsyncMock,
):
_device(admin_user, "deck")
_heartbeat(client, admin_user, "deck", rom.id)
emit.reset_mock()
response = client.delete(
"/api/activity/heartbeat",
headers=_auth(editor_user),
params={"device_id": "deck"},
)
assert response.status_code == status.HTTP_204_NO_CONTENT
emit.assert_not_awaited()
listed = client.get("/api/activity", headers=_auth(admin_user)).json()
assert [entry["user_id"] for entry in listed] == [admin_user.id]
def test_clearing_nothing_broadcasts_nothing(
self, client: TestClient, admin_user: User, emit: AsyncMock
):
response = client.delete(
"/api/activity/heartbeat",
headers=_auth(admin_user),
params={"device_id": "idle"},
)
assert response.status_code == status.HTTP_204_NO_CONTENT
emit.assert_not_awaited()
class TestDeviceTokenBinding:
@pytest.fixture
def bound_headers(self, admin_user: User) -> dict[str, str]:
_device(admin_user, "deck")
_device(admin_user, "tv-box")
_, raw_token = make_device_token(
admin_user, "deck", scopes="roms.user.read roms.user.write"
)
return {"Authorization": f"Bearer {raw_token}"}
def test_cannot_heartbeat_as_another_device(
self,
client: TestClient,
admin_user: User,
rom: Rom,
emit: AsyncMock,
bound_headers: dict[str, str],
):
response = client.post(
"/api/activity/heartbeat",
headers=bound_headers,
json={"rom_id": rom.id, "device_id": "tv-box"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
emit.assert_not_awaited()
device = db_device_handler.get_device(device_id="tv-box", user_id=admin_user.id)
assert device is not None
assert device.last_seen is None
def test_cannot_clear_another_devices_session(
self,
client: TestClient,
admin_user: User,
rom: Rom,
emit: AsyncMock,
bound_headers: dict[str, str],
):
_heartbeat(client, admin_user, "tv-box", rom.id)
emit.reset_mock()
response = client.delete(
"/api/activity/heartbeat",
headers=bound_headers,
params={"device_id": "tv-box"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
emit.assert_not_awaited()
listed = client.get("/api/activity", headers=_auth(admin_user)).json()
assert [entry["device_id"] for entry in listed] == ["tv-box"]
class TestListing:
@pytest.fixture
def playing(
self,
client: TestClient,
admin_user: User,
editor_user: User,
rom: Rom,
second_rom: Rom,
emit: AsyncMock,
) -> None:
_device(admin_user, "deck")
_device(editor_user, "handheld")
_heartbeat(client, admin_user, "deck", rom.id)
_heartbeat(client, editor_user, "handheld", second_rom.id)
def test_lists_every_users_sessions(
self,
client: TestClient,
viewer_user: User,
admin_user: User,
editor_user: User,
playing: None,
):
listed = client.get("/api/activity", headers=_auth(viewer_user)).json()
assert {(e["user_id"], e["device_id"]) for e in listed} == {
(admin_user.id, "deck"),
(editor_user.id, "handheld"),
}
def test_lists_one_roms_sessions(
self,
client: TestClient,
viewer_user: User,
admin_user: User,
rom: Rom,
playing: None,
):
listed = client.get(
f"/api/activity/rom/{rom.id}", headers=_auth(viewer_user)
).json()
assert [(e["user_id"], e["rom_id"]) for e in listed] == [
(admin_user.id, rom.id)
]
def test_a_hidden_rom_is_left_out_for_that_user_only(
self,
client: TestClient,
viewer_user: User,
admin_user: User,
rom: Rom,
second_rom: Rom,
playing: None,
):
_hide(PermEntity.ROMS, rom.id, viewer_user)
for_viewer = client.get("/api/activity", headers=_auth(viewer_user)).json()
for_admin = client.get("/api/activity", headers=_auth(admin_user)).json()
rom_for_viewer = client.get(
f"/api/activity/rom/{rom.id}", headers=_auth(viewer_user)
).json()
assert [e["rom_id"] for e in for_viewer] == [second_rom.id]
assert {e["rom_id"] for e in for_admin} == {rom.id, second_rom.id}
assert rom_for_viewer == []
def test_a_hidden_platform_hides_its_roms_sessions(
self,
client: TestClient,
viewer_user: User,
platform: Platform,
playing: None,
):
_hide(PermEntity.PLATFORMS, platform.id, viewer_user)
listed = client.get("/api/activity", headers=_auth(viewer_user)).json()
assert listed == []
def test_needs_the_read_scope(self, client: TestClient, viewer_user: User):
response = client.get("/api/activity", headers=_auth(viewer_user, []))
assert response.status_code == status.HTTP_403_FORBIDDEN