Files
romm/backend/tests/endpoints/test_library_audit.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

245 lines
7.2 KiB
Python

from unittest.mock import patch
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from tests.audit_events import recorded_events
from tests.auth_helpers import bearer
from config.config_manager import config_manager as cm
from handler.database import (
db_collection_handler,
db_rom_handler,
)
from handler.filesystem import fs_firmware_handler, fs_resource_handler
from models.collection import Collection
from models.firmware import Firmware
from models.platform import Platform
from models.rom import Rom
from models.user import User
def _collection(user: User, *, favorite: bool = False) -> Collection:
return db_collection_handler.add_collection(
Collection(
name="Favorites" if favorite else "Shelf",
description="",
is_public=False,
is_favorite=favorite,
user_id=user.id,
)
)
class TestRomUpdate:
def test_an_edit_records_what_changed(
self, client: TestClient, access_token: str, rom: Rom
):
response = client.put(
f"/api/roms/{rom.id}",
headers=bearer(access_token),
data={"name": "Metroid"},
)
assert response.status_code == status.HTTP_200_OK
[event] = recorded_events()
assert event.action == "rom.edit"
assert event.target_name == "Metroid"
assert event.data["changed"] == ["name"]
assert event.data["name"] == {"from": "test_rom", "to": "Metroid"}
def test_a_new_provider_id_is_a_manual_match(
self, client: TestClient, access_token: str, rom: Rom
):
client.put(
f"/api/roms/{rom.id}",
headers=bearer(access_token),
data={"sgdb_id": "4242"},
)
[event] = recorded_events()
assert event.action == "rom.match"
assert event.data["providers"] == {"sgdb_id": 4242}
def test_saving_without_changes_records_nothing(
self, client: TestClient, access_token: str, rom: Rom
):
client.put(
f"/api/roms/{rom.id}",
headers=bearer(access_token),
data={"name": "test_rom"},
)
assert recorded_events() == []
def test_an_unmatch_records_the_ids_it_dropped(
self, client: TestClient, access_token: str, rom: Rom
):
db_rom_handler.update_rom(rom.id, {"sgdb_id": 4242})
client.put(
f"/api/roms/{rom.id}",
params={"unmatch_metadata": True},
headers=bearer(access_token),
)
[event] = recorded_events()
assert event.action == "rom.unmatch"
assert event.data["providers"] == {"sgdb_id": 4242}
def test_a_deleted_rom_keeps_its_name(client: TestClient, access_token: str, rom: Rom):
response = client.post(
"/api/roms/delete",
headers=bearer(access_token),
json={"roms": [rom.id]},
)
assert response.status_code == status.HTTP_200_OK
[event] = recorded_events()
assert event.action == "rom.delete"
assert (event.target_id, event.target_name) == (str(rom.id), "test_rom")
assert event.data["deleted_from_fs"] is False
def test_a_rom_whose_resources_stay_behind_is_still_deleted(
client: TestClient, access_token: str, rom: Rom, mocker
):
mocker.patch.object(
fs_resource_handler, "remove_directory", side_effect=PermissionError("busy")
)
response = client.post(
"/api/roms/delete",
headers=bearer(access_token),
json={"roms": [rom.id]},
)
assert response.json()["failed_ids"] == [rom.id]
[event] = recorded_events()
assert event.action == "rom.delete"
def test_a_firmware_file_left_on_disk_is_not_deleted_from_it(
client: TestClient, access_token: str, firmware: Firmware, mocker
):
mocker.patch.object(
fs_firmware_handler, "remove_file", side_effect=PermissionError("read-only")
)
client.post(
"/api/firmware/delete",
headers=bearer(access_token),
json={"firmware": [firmware.id], "delete_from_fs": [firmware.id]},
)
[event] = recorded_events()
assert event.action == "firmware.delete"
assert event.data["deleted_from_fs"] is False
def test_a_platform_rename_is_an_edit(
client: TestClient, access_token: str, platform: Platform
):
client.put(
f"/api/platforms/{platform.id}",
headers=bearer(access_token),
json={"custom_name": "Famicom"},
)
[event] = recorded_events()
assert event.action == "platform.edit"
assert event.target_name == "Famicom"
assert event.data["changed"] == ["custom_name"]
def test_a_config_change_names_its_setting(client: TestClient, access_token: str):
with patch.object(cm, "add_exclusion"):
client.post(
"/api/config/exclude",
headers=bearer(access_token),
json={
"exclusion_type": "EXCLUDED_SINGLE_FILES",
"exclusion_value": "README.txt",
},
)
[event] = recorded_events()
assert event.action == "config.update"
assert event.data == {
"setting": "exclusion",
"op": "add",
"type": "EXCLUDED_SINGLE_FILES",
"value": "README.txt",
}
class TestCollections:
def test_creating_one_is_recorded(self, client: TestClient, access_token: str):
client.post(
"/api/collections",
data={"name": "Shelf"},
headers=bearer(access_token),
)
[event] = recorded_events()
assert event.action == "collection.create"
assert event.target_name == "Shelf"
def test_adding_roms_counts_them(
self, client: TestClient, access_token: str, admin_user: User, rom: Rom
):
collection = _collection(admin_user)
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers=bearer(access_token),
)
[event] = recorded_events()
assert event.action == "collection.add_roms"
assert event.data == {"count": 1, "rom_ids": [rom.id]}
@pytest.mark.parametrize("method", ["post", "delete"])
def test_games_that_change_nothing_are_not_recorded(
self,
client: TestClient,
access_token: str,
admin_user: User,
rom: Rom,
method: str,
):
collection = _collection(admin_user)
if method == "post":
db_collection_handler.add_roms_to_collection(collection.id, [rom.id])
client.request(
method.upper(),
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id] if method == "post" else [999999]},
headers=bearer(access_token),
)
assert recorded_events() == []
@pytest.mark.parametrize("method", ["post", "delete"])
def test_a_favourite_toggle_is_not(
self,
client: TestClient,
access_token: str,
admin_user: User,
rom: Rom,
method: str,
):
favorites = _collection(admin_user, favorite=True)
client.request(
method.upper(),
f"/api/collections/{favorites.id}/roms",
json={"rom_ids": [rom.id]},
headers=bearer(access_token),
)
assert recorded_events() == []