Files
romm/backend/tests/handler/auth/test_permissions_resolver.py
Georges-Antoine Assi e813e4d666 chore(coherence): adopt Coherence with specs, invariants and a PR report (#5584)
* chore(coherence): adopt Coherence with specs, invariants and a PR report

Install @posthog/coherence as a frontend dev dependency and wire its
Claude Code hooks into the committed .claude/settings.json, so every
agent session in the repo gets the vocabulary, specs, journal and checks.
The hooks call the binary under frontend/ through $CLAUDE_PROJECT_DIR.

Declare 23 components and the entrances that carry outside trust, and
six invariants, each refuted with a deliberate break before it counted:

- every /api route requires auth and its scopes, except a named public
  list (new route sweep in tests/endpoints/test_route_guards.py)
- a hidden rom, platform or firmware answers every id route exactly as
  a missing id would (new sweep over every method of every id route)
- the unscoped save, state and screenshot fetches by id are reached only
  from their own routers (chokepoints)
- validate_path never resolves outside its base folder

The PR workflow runs in comment mode: one report comment, failing only
when Coherence itself breaks. Trunk skips Prettier and markdownlint on
*.spec.md and *.practice.md, since Prettier escapes their globs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(routes): satisfy mypy in the route guard sweep

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(coherence): record the worktree test database enactment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(roms): answer a hidden rom like a missing one on file routes; tighten route sweeps

Addresses Greptile's review on #5584.

The rom file delete and reading-progress routes answered "File not found"
for a hidden rom but "Rom with id N not found" for a missing one, so a
caller could tell them apart. They now raise the same not-found.

The route sweeps now reach the checks they claim to test: a protected
route with no scopes counts as public (its guard admits anyone), write
requests carry a body and upload name so validation can't answer first,
RomFile-keyed routes get a real file id, error bodies are compared with
the id normalized, and the rom routes are swept with the rom hidden
directly, through its platform, and by the unrated filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(coherence): tighten route guard sweeps and isolate oracle test databases (code-review)

- Count a route as protected only when its endpoint is the scope-checking
  wrapper with non-empty scopes, not just when it declares the bearer scopes.
- Treat 401 and 403 like 422 as never reaching the visibility check, and
  sweep /api/streaming/states/{rom_id}.
- Run pytest oracles with a per-run ROMM_TEST_DB_TAG unless one is set.
- Use the shared setup-frontend action and ubuntu-24.04 in the workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(tests): simplify route guard sweeps and path tests (simplify)

- Mark scope-guard wrappers with required_scopes so the auth sweep reads a
  public attribute instead of the private closure.
- Derive the entity regex from one segment list, ask each missing id once,
  and run the three hide scenarios through one sweep helper.
- Fold the new validate_path inputs into the existing valid, traversal and
  absolute path tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(coherence): trim workflow comments (review-polish)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(filesystem): restore the validate_path property test the paths invariant cites

Filesystem.spec.md names test_validate_path_never_escapes_its_base as the
invariant's evidence, and Coherence selects it by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(coherence): run hooks from the local binary instead of npx

Each hook calls frontend/node_modules/.bin/coherence directly and exits 0
when it isn't installed, so sessions without frontend deps (fresh
worktrees, backend-only setups, cloud setup still installing) don't report
a hook error on every tool call, and no hook pays npx's startup.

Also commits the journal and run records left by earlier sessions, which
.coherence/.gitignore keeps as durable records.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(tests): share the bearer, user token and hide helpers

Tests built the same Authorization headers and HiddenEntity rows in about
40 local copies, and two modules imported private helpers from other test
files. They now use bearer, user_headers and hide from tests/auth_helpers.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(endpoints): one 404 for a missing or hidden rom, platform or firmware

Each route wrote the missing-row 404 and the hidden-row 404 separately and
had to keep them identical by hand. visible_rom_or_404,
visible_platform_or_404 and visible_firmware_or_404 take the lookup result
and raise one answer for both, either the standard not-found or a bespoke
detail. Re-reads after a write keep a plain not-found check, so an edit that
hides the row doesn't turn into a 404 after it succeeded.

The RomFile-keyed routes (/roms/{file_id}/files, .../files/content/{name},
/roms/{file_id}/patch) name their path parameter file_id instead of id, so
the route sweep reads which id a route takes from its path and drops its
hand-kept list. URLs are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(setup): develop inside WSL on Windows

@posthog/coherence installs only on Linux and macOS, so npm install in
frontend/ fails on native Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(coherence): record the whole-repo chokepoint run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(types): regenerate API types for the file_id patch route

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:53:46 -05:00

219 lines
8.2 KiB
Python

"""Resolver + projection behavior: precedence, overrides, own_only, hiding, kiosk.
Complements ``test_permissions_parity.py`` (which proves the static matrices).
Here we exercise ``resolve_permissions`` / ``compute_oauth_scopes`` end-to-end
against the DB: group membership, per-user overrides, ownership scoping, hidden
entities, and the KIOSK_MODE anonymous-visitor cap.
"""
import pytest
from tests.auth_helpers import hide
from handler.auth.constants import EDIT_SCOPES, FULL_SCOPES, READ_SCOPES, WRITE_SCOPES
from handler.auth.permissions import resolve_permissions
from handler.database import db_user_handler
from handler.database.base_handler import sync_session
from models.permission import (
PermAction,
PermEntity,
PermissionGroup,
PermissionGroupGrant,
SystemGroupKey,
UserPermissionOverride,
)
from models.rom import RomVisibility
from models.user import User
@pytest.fixture(autouse=True)
def _cleanup_non_system_groups():
# clear_database (conftest) deletes users, cascading overrides + user-hidden
# rows via FK. Non-system groups created by these tests are not user-bound,
# so drop them (cascading their grants + group-hidden rows) after each test.
yield
with sync_session.begin() as s:
s.query(PermissionGroup).filter(PermissionGroup.system_key.is_(None)).delete(
synchronize_session="evaluate"
)
def _make_group(name, grants, *, is_default=False):
with sync_session.begin() as s:
group = PermissionGroup(name=name, is_default=is_default)
s.add(group)
s.flush()
gid = group.id
for entity, action, own_only in grants:
s.add(
PermissionGroupGrant(
group_id=gid, entity=entity, action=action, own_only=own_only
)
)
return gid
def _set_group(user: User, group_id: int) -> User:
db_user_handler.update_user(user.id, {"permission_group_id": group_id})
refreshed = db_user_handler.get_user(user.id)
assert refreshed is not None
return refreshed
def _add_override(user_id, entity, action, *, granted, own_only=False):
with sync_session.begin() as s:
s.add(
UserPermissionOverride(
user_id=user_id,
entity=entity,
action=action,
granted=granted,
own_only=own_only,
)
)
# --- Projection parity through the live property (group-less users) ----------
def test_property_parity_for_group_less_users(admin_user, editor_user, viewer_user):
assert set(admin_user.oauth_scopes) == set(FULL_SCOPES)
assert set(editor_user.oauth_scopes) == set(EDIT_SCOPES)
assert set(viewer_user.oauth_scopes) == set(WRITE_SCOPES)
# --- Kiosk mode: the anonymous visitor is capped, accounts are not -----------
@pytest.fixture
def kiosk_mode(monkeypatch):
monkeypatch.setattr("handler.auth.permissions.KIOSK_MODE", True)
def test_kiosk_leaves_logged_in_users_alone(
kiosk_mode, admin_user, editor_user, viewer_user
):
# Kiosk mode locks down anonymous visitors, not accounts someone logged
# into: every user keeps exactly what their group and overrides grant.
assert set(viewer_user.oauth_scopes) == set(WRITE_SCOPES)
assert set(editor_user.oauth_scopes) == set(EDIT_SCOPES)
assert set(admin_user.oauth_scopes) == set(FULL_SCOPES)
def test_kiosk_honors_write_override_on_logged_in_user(kiosk_mode, viewer_user):
_add_override(viewer_user.id, PermEntity.ROMS, PermAction.WRITE, granted=True)
user = db_user_handler.get_user(viewer_user.id)
assert user is not None
assert "roms.write" in {s.value for s in user.oauth_scopes}
assert resolve_permissions(user).allows(PermEntity.ROMS, PermAction.WRITE)
def test_kiosk_guest_is_capped_to_read(kiosk_mode):
# The default group grants writes, so the cap is what keeps the shared
# synthetic visitor (id=-1) from uploading assets or editing collections.
guest = User.kiosk_mode_user()
assert set(guest.oauth_scopes) == set(READ_SCOPES)
perms = resolve_permissions(guest)
assert not perms.is_admin
assert {g.action for g in perms.grants} == {PermAction.READ}
assert perms.allows(PermEntity.ROMS, PermAction.READ)
assert not perms.allows(PermEntity.ASSETS, PermAction.WRITE)
# --- Precedence: group > legacy role fallback --------------------------------
def test_explicit_group_overrides_role_fallback(editor_user):
# A read-only group assigned to an (legacy) editor strips write access.
gid = _make_group("readonly", [(PermEntity.ROMS, PermAction.READ, False)])
user = _set_group(editor_user, gid)
scopes = {s.value for s in user.oauth_scopes}
assert "roms.read" in scopes
assert "roms.write" not in scopes # role said editor, group says read-only
# Self-service scopes are always present regardless of group.
assert {"me.read", "me.write", "roms.user.read", "roms.user.write"} <= scopes
# --- Per-user overrides add and revoke ---------------------------------------
def test_override_grants_extra_capability(viewer_user):
_add_override(viewer_user.id, PermEntity.ROMS, PermAction.WRITE, granted=True)
user = db_user_handler.get_user(viewer_user.id)
assert user is not None
assert "roms.write" in {s.value for s in user.oauth_scopes}
perms = resolve_permissions(user)
assert perms.allows(PermEntity.ROMS, PermAction.WRITE)
def test_override_revokes_group_capability(viewer_user):
# Viewer matrix grants collections.write (own); a revoke override removes it.
_add_override(
viewer_user.id, PermEntity.COLLECTIONS, PermAction.WRITE, granted=False
)
user = db_user_handler.get_user(viewer_user.id)
assert user is not None
assert "collections.write" not in {s.value for s in user.oauth_scopes}
# --- Admin bypass and own_only semantics -------------------------------------
def test_admin_bypass(admin_user):
perms = resolve_permissions(admin_user)
assert perms.is_admin
assert perms.allows(PermEntity.USERS, PermAction.DELETE)
assert perms.allows(PermEntity.ROMS, PermAction.WRITE, owned=False)
def test_own_only_requires_ownership(viewer_user):
perms = resolve_permissions(viewer_user)
# collections.write is own_only in the viewer matrix.
assert perms.allows(PermEntity.COLLECTIONS, PermAction.WRITE, owned=True)
assert not perms.allows(PermEntity.COLLECTIONS, PermAction.WRITE, owned=False)
assert not perms.allows(PermEntity.COLLECTIONS, PermAction.WRITE)
# collections.read is library-wide (own_only False) -> always allowed.
assert perms.allows(PermEntity.COLLECTIONS, PermAction.READ)
# --- Hidden entities (user and group principals) -----------------------------
def test_user_hidden_platform_and_rom_cascade(viewer_user):
hide(PermEntity.PLATFORMS, 5, user_id=viewer_user.id)
hide(PermEntity.ROMS, 99, user_id=viewer_user.id)
perms = resolve_permissions(viewer_user)
assert perms.hidden_platform_ids == frozenset({5})
assert perms.hidden_rom_ids == frozenset({99})
assert not perms.can_see_platform(5)
assert perms.can_see_platform(6)
# Rom on a hidden platform is hidden even if the rom itself isn't listed.
assert not perms.can_see_rom(RomVisibility(id=1, platform_id=5, min_age=None))
assert not perms.can_see_rom(RomVisibility(id=99, platform_id=6, min_age=None))
assert perms.can_see_rom(RomVisibility(id=1, platform_id=6, min_age=None))
def test_group_hidden_applies_to_members(viewer_user):
gid = _make_group("kids", [(PermEntity.ROMS, PermAction.READ, False)])
user = _set_group(viewer_user, gid)
hide(PermEntity.PLATFORMS, 7, group_id=gid)
perms = resolve_permissions(user)
assert 7 in perms.hidden_platform_ids
assert not perms.can_see_platform(7)
def test_admin_sees_everything_despite_hides(admin_user):
hide(PermEntity.PLATFORMS, 5, user_id=admin_user.id)
perms = resolve_permissions(admin_user)
assert perms.can_see_platform(5)
def test_default_group_is_viewer():
from handler.database import db_permission_handler
group_id = db_permission_handler.get_default_group_id()
assert group_id is not None
group = db_permission_handler.get_group(group_id)
assert group is not None
assert group.system_key == SystemGroupKey.VIEWER