Files
romm/backend/tests/endpoints/test_netplay.py
Zach Clendenen 1f6b4d11ca feat(permissions): gate emulator streaming and in-browser play behind group permissions (#5185)
* feat(permissions): gate emulator streaming behind a group permission

Add a streaming permission entity. Read shows streaming and allows joining
a session; write allows starting one. Users without read get a disabled
streaming config, so every streaming surface hides.

Migration 0152 grants read and write to every existing group, so nobody
loses access on upgrade. Groups created afterwards start without it.
Owner-scoped session controls (save, exit, release) stay ungated so a
revoked user can still leave a running game without losing saves.

* fix(streaming): pr-ready code-review fixes for the streaming grant

Own-only read no longer joins other users' sessions, the config refetches on permissions:changed, the store skips the joinable request when streaming is off, and tests clean up the groups they create.

* refactor(streaming): pr-ready simplify pass on the streaming grant

Collapse the streaming permission helpers onto assert_can/can_access, return an empty joinable list instead of 403, skip the permission resolve when streaming is off, and add a stream.start action key so the UI hides Stream (but keeps Join) for users without the write grant.

* docs(streaming): pr-ready review-polish pass on the streaming grant

Trim the 0152 migration docstring to a single summary line, matching 0150 and 0151.

* docs(streaming): pr-ready humanizer pass on the streaming grant

Plainer wording for the stream.start action key comment and the Permission Groups paragraph, which now says an own-only read shows streaming without the join.

* feat(permissions): gate in-browser emulation behind a group permission

Adds an emulation entity next to streaming. Read plays in the browser
(EmulatorJS, Ruffle, js-dos, PICO-8, EasyRPG) and joins netplay rooms,
write hosts them. Migration 0152 now backfills both entities onto every
existing group.

* fix(streaming): address Greptile review on PR 5185

- Pin the claimed container in the stream player, so a permission refresh
  that turns streaming off mid-game keeps save, load and disc swap until
  the session ends.
- Empty the Join list when a refreshed config turns streaming off, and
  discard any joinable request still in flight.
- Update the installPermissionsHydration doc to name every layout that
  calls it.

* fix(migrations): renumber play permissions migration to 0153 after master's 0152

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(permissions): drop redundant PermEntity comments

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(streaming): drop the live config refresh on permission changes

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 14:47:11 -04:00

130 lines
4.0 KiB
Python

"""The netplay room listing must not reveal rooms for a hidden rom."""
from datetime import timedelta
from typing import cast
from unittest.mock import AsyncMock, Mock
import pytest
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
from handler.auth.base_handler import oauth_handler
from handler.auth.constants import Scope
from handler.database.base_handler import sync_session
from handler.netplay_handler import NetplayPlayerInfo, NetplayRoom, netplay_handler
from models.permission import (
HiddenEntity,
PermAction,
PermEntity,
UserPermissionOverride,
)
from models.user import User
def _auth(user: User, scopes: list[Scope] | None = None) -> dict[str, str]:
# Re-reads the user's current (projected) scopes each call.
token = oauth_handler.create_access_token(
data={
"sub": user.username,
"iss": "romm:oauth",
"scopes": " ".join(scopes if scopes is not None else user.oauth_scopes),
},
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
)
return {"Authorization": f"Bearer {token}"}
def _hide(entity: PermEntity, entity_id: int, user_id: int) -> None:
with sync_session.begin() as s:
s.add(HiddenEntity(entity=entity, entity_id=entity_id, user_id=user_id))
def _room(rom_id: int) -> NetplayRoom:
return NetplayRoom(
owner="sid",
players={
"p": NetplayPlayerInfo(
socketId="sid",
player_name="Player p",
userid=None,
playerId="p",
)
},
peers=[],
room_name="Room",
game_id=str(rom_id),
domain=None,
password=None,
max_players=4,
)
@pytest.fixture
def rooms(mocker) -> Mock:
return cast(
Mock,
mocker.patch.object(netplay_handler, "get_all", AsyncMock(return_value={})),
)
def test_listing_shows_rooms_for_a_visible_rom(client, viewer_user, rom, rooms):
rooms.return_value = {"room-1": _room(rom.id)}
resp = client.get(f"/api/netplay/list?game_id={rom.id}", headers=_auth(viewer_user))
assert resp.status_code == 200
assert "room-1" in resp.json()
def test_listing_hides_rooms_for_a_hidden_rom(client, viewer_user, rom, rooms):
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
rooms.return_value = {"room-1": _room(rom.id)}
resp = client.get(f"/api/netplay/list?game_id={rom.id}", headers=_auth(viewer_user))
assert resp.status_code == 404
rooms.assert_not_awaited()
def test_listing_of_a_missing_rom_is_not_found(client, viewer_user, rooms):
resp = client.get("/api/netplay/list?game_id=999999", headers=_auth(viewer_user))
assert resp.status_code == 404
rooms.assert_not_awaited()
def test_listing_needs_the_rom_read_scope(client, viewer_user, rooms):
"""The listing answers about a rom, so asset access alone is not enough."""
headers = _auth(viewer_user, scopes=[Scope.ASSETS_READ])
resp = client.get("/api/netplay/list?game_id=1", headers=headers)
assert resp.status_code == 403
rooms.assert_not_awaited()
def _override_emulation_read(user: User, *, own_only: bool = False) -> None:
with sync_session.begin() as s:
s.add(
UserPermissionOverride(
user_id=user.id,
entity=PermEntity.EMULATION,
action=PermAction.READ,
granted=own_only,
own_only=own_only,
)
)
@pytest.mark.parametrize("own_only", [False, True], ids=["revoked", "own-only"])
def test_listing_is_empty_without_a_full_emulation_read(
client, viewer_user, rom, rooms, own_only
):
"""Every listed room is someone else's, so only a library-wide grant shows them."""
_override_emulation_read(viewer_user, own_only=own_only)
rooms.return_value = {"room-1": _room(rom.id)}
resp = client.get(f"/api/netplay/list?game_id={rom.id}", headers=_auth(viewer_user))
assert resp.status_code == 200
assert resp.json() == {}