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

294 lines
9.8 KiB
Python

from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock
import pytest
from fastapi import status
from tests.auth_helpers import bearer
from handler.auth.base_handler import oauth_handler
from handler.database import db_notification_handler
from handler.socket_handler import socket_handler
from models.notification import (
MAX_NOTIFICATIONS_PER_USER,
Notification,
NotificationKind,
NotificationLevel,
)
from models.user import User
def _add(user: User, minutes_ago: int = 0, **overrides) -> Notification:
[stored] = db_notification_handler.add_notifications(
[
Notification(
user_id=user.id,
kind=NotificationKind.TASK_COMPLETED,
level=NotificationLevel.SUCCESS,
data={"task": "cleanup_missing_roms"},
created_at=datetime.now(timezone.utc) - timedelta(minutes=minutes_ago),
**overrides,
)
]
)
return stored
@pytest.fixture
def emit(mocker):
return mocker.patch.object(socket_handler, "emit_to_user", AsyncMock())
class TestListNotifications:
def test_lists_only_the_callers_newest_first(
self, client, access_token, admin_user, viewer_user
):
older = _add(admin_user, minutes_ago=5)
newer = _add(admin_user, minutes_ago=1, actor_id=viewer_user.id)
_add(viewer_user)
response = client.get("/api/notifications", headers=bearer(access_token))
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert [n["id"] for n in body] == [newer.id, older.id]
assert body[0]["actor"]["username"] == viewer_user.username
assert body[0]["kind"] == "task_completed"
assert body[0]["read_at"] is None
assert body[1]["actor"] is None
class TestMarkRead:
def test_marks_the_given_ids(self, client, access_token, admin_user, emit):
first = _add(admin_user)
second = _add(admin_user)
response = client.post(
"/api/notifications/read",
json={"ids": [first.id]},
headers=bearer(access_token),
)
assert response.status_code == status.HTTP_200_OK
read = {
n.id: n.read_at
for n in db_notification_handler.get_notifications(admin_user.id)
}
assert read[first.id] is not None
assert read[second.id] is None
emit.assert_awaited_once_with(
admin_user.id, "notifications:read", {"ids": [first.id]}
)
def test_null_marks_everything(self, client, access_token, admin_user, emit):
_add(admin_user)
_add(admin_user)
client.post(
"/api/notifications/read", json={"ids": None}, headers=bearer(access_token)
)
assert all(
n.read_at for n in db_notification_handler.get_notifications(admin_user.id)
)
def test_leaves_other_users_alone(
self, client, access_token, admin_user, viewer_user, emit
):
theirs = _add(viewer_user)
client.post(
"/api/notifications/read",
json={"ids": [theirs.id]},
headers=bearer(access_token),
)
[unchanged] = db_notification_handler.get_notifications(viewer_user.id)
assert unchanged.read_at is None
class TestDismiss:
def test_dismisses_one_for_good(self, client, access_token, admin_user, emit):
gone = _add(admin_user)
kept = _add(admin_user)
response = client.delete(
f"/api/notifications/{gone.id}", headers=bearer(access_token)
)
assert response.status_code == status.HTTP_200_OK
remaining = db_notification_handler.get_notifications(admin_user.id)
assert [n.id for n in remaining] == [kept.id]
emit.assert_awaited_once_with(
admin_user.id, "notifications:dismissed", {"ids": [gone.id]}
)
def test_someone_elses_is_not_found(self, client, access_token, viewer_user, emit):
theirs = _add(viewer_user)
response = client.delete(
f"/api/notifications/{theirs.id}", headers=bearer(access_token)
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert len(db_notification_handler.get_notifications(viewer_user.id)) == 1
emit.assert_not_awaited()
def test_dismisses_all_of_the_callers(
self, client, access_token, admin_user, viewer_user, emit
):
_add(admin_user)
_add(admin_user)
_add(viewer_user)
response = client.delete("/api/notifications", headers=bearer(access_token))
assert response.status_code == status.HTTP_200_OK
assert db_notification_handler.get_notifications(admin_user.id) == []
assert len(db_notification_handler.get_notifications(viewer_user.id)) == 1
emit.assert_awaited_once_with(
admin_user.id, "notifications:dismissed", {"ids": None}
)
def test_an_inbox_keeps_only_the_newest(admin_user):
oldest = _add(admin_user, minutes_ago=MAX_NOTIFICATIONS_PER_USER + 1)
for minutes_ago in range(MAX_NOTIFICATIONS_PER_USER, 0, -1):
_add(admin_user, minutes_ago=minutes_ago)
remaining = db_notification_handler.get_notifications(admin_user.id)
assert len(remaining) == MAX_NOTIFICATIONS_PER_USER
assert oldest.id not in {n.id for n in remaining}
class TestCreateNotification:
def test_a_user_notifies_themselves(
self, client, viewer_access_token, viewer_user, emit
):
response = client.post(
"/api/notifications",
json={
"title": "Sync finished",
"body": "12 saves uploaded",
"kind": "argosy.sync_done",
"level": "success",
"link": "/rom/12",
"icon": "mdi-sync",
"data": {"device": "deck"},
},
headers=bearer(viewer_access_token),
)
assert response.status_code == status.HTTP_201_CREATED
[sent] = response.json()
assert sent["title"] == "Sync finished"
assert sent["kind"] == "argosy.sync_done"
assert sent["actor"] is None
[stored] = db_notification_handler.get_notifications(viewer_user.id)
assert (stored.link, stored.data) == ("/rom/12", {"device": "deck"})
emit.assert_awaited_once()
def test_only_an_admin_notifies_others(
self, client, viewer_access_token, admin_user, emit
):
response = client.post(
"/api/notifications",
json={"title": "Hello", "recipients": [admin_user.id]},
headers=bearer(viewer_access_token),
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert db_notification_handler.get_notifications(admin_user.id) == []
def test_an_admin_notifies_everyone_as_the_sender(
self, client, access_token, admin_user, viewer_user, editor_user, emit
):
response = client.post(
"/api/notifications",
json={
"title": "Maintenance tonight",
"level": "warning",
"recipients": "all",
},
headers=bearer(access_token),
)
assert response.status_code == status.HTTP_201_CREATED
assert len(response.json()) == 3
[to_viewer] = db_notification_handler.get_notifications(viewer_user.id)
assert to_viewer.actor_id == admin_user.id
[to_self] = db_notification_handler.get_notifications(admin_user.id)
assert to_self.actor_id is None
def test_an_admin_notifies_only_the_admins(
self, client, access_token, admin_user, viewer_user, emit
):
client.post(
"/api/notifications",
json={"title": "Disk almost full", "recipients": "admins"},
headers=bearer(access_token),
)
assert len(db_notification_handler.get_notifications(admin_user.id)) == 1
assert db_notification_handler.get_notifications(viewer_user.id) == []
def test_an_unknown_recipient_is_not_found(
self, client, access_token, viewer_user, emit
):
response = client.post(
"/api/notifications",
json={"title": "Hello", "recipients": [viewer_user.id, 999_999]},
headers=bearer(access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert db_notification_handler.get_notifications(viewer_user.id) == []
@pytest.mark.parametrize(
"field",
[
{"kind": "role_changed"},
{"link": "https://example.com"},
{"link": "//example.com/login"},
{"link": "/\\example.com"},
{"icon": "not-an-icon"},
{"title": ""},
{"data": {"blob": "x" * 5000}},
{"title": "nul\u0000byte"},
{"recipients": []},
],
)
def test_rejects_what_a_client_may_not_send(
self, client, access_token, admin_user, field, emit
):
response = client.post(
"/api/notifications",
json={"title": "Hello", **field},
headers=bearer(access_token),
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
assert db_notification_handler.get_notifications(admin_user.id) == []
def test_an_admin_token_without_users_write_notifies_only_itself(
client, admin_user, viewer_user, emit
):
token = oauth_handler.create_access_token(
data={
"sub": admin_user.username,
"iss": "romm:oauth",
"scopes": "me.read me.write",
},
expires_delta=timedelta(minutes=5),
)
response = client.post(
"/api/notifications",
json={"title": "Hello", "recipients": "all"},
headers=bearer(token),
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert db_notification_handler.get_notifications(viewer_user.id) == []