mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
* 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>
403 lines
14 KiB
Python
403 lines
14 KiB
Python
import re
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock
|
|
|
|
import pytest
|
|
from fastapi import status
|
|
from tests.auth_helpers import bearer
|
|
|
|
from handler.database import db_notification_channel_handler
|
|
from handler.email_handler import EmailError
|
|
from handler.notification_channels import channels, confirmation
|
|
from models.notification_channel import (
|
|
MAX_CONSECUTIVE_DELIVERY_FAILURES,
|
|
MAX_NOTIFICATION_CHANNELS_PER_USER,
|
|
)
|
|
|
|
API = "/api/notification-channels"
|
|
|
|
|
|
def _webhook(
|
|
url: str = "https://hooks.example.com/romm/token", **fields
|
|
) -> dict[str, Any]:
|
|
return {"type": "webhook", "name": "Hook", "url": url, **fields}
|
|
|
|
|
|
_DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"}
|
|
|
|
|
|
def _apprise(service: str = "discord", **fields) -> dict[str, Any]:
|
|
return {
|
|
"type": "apprise",
|
|
"name": "Discord",
|
|
"service": service,
|
|
"fields": fields or _DISCORD,
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def emailed(mocker):
|
|
mocker.patch.object(channels, "EMAIL_ENABLED", True)
|
|
return mocker.patch.object(confirmation, "send_email")
|
|
|
|
|
|
@pytest.fixture
|
|
def sent(mocker):
|
|
return mocker.patch.object(channels, "send_to_channel", AsyncMock())
|
|
|
|
|
|
class TestCreate:
|
|
def test_a_webhook_hides_its_token(self, client, access_token):
|
|
response = client.post(
|
|
API, json=_webhook(secret="k"), headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
body = response.json()
|
|
assert body["target"] == "https://hooks.example.com/…oken"
|
|
assert body["has_secret"] is True
|
|
assert body["confirmed"] is True
|
|
assert body["topics"] is None
|
|
assert "token" not in response.text
|
|
|
|
def test_an_admin_may_reach_the_local_network(self, client, access_token):
|
|
response = client.post(
|
|
API, json=_webhook("http://192.168.1.2/hook"), headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
|
|
def test_a_user_may_not(self, client, viewer_access_token):
|
|
response = client.post(
|
|
API,
|
|
json=_webhook("http://192.168.1.2/hook"),
|
|
headers=bearer(viewer_access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
def test_an_admin_forwards_through_apprise(self, client, access_token):
|
|
response = client.post(
|
|
API, json=_apprise(**_DISCORD, botname="RomM"), headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
body = response.json()
|
|
assert (body["type"], body["service"], body["service_name"]) == (
|
|
"apprise",
|
|
"discord",
|
|
"Discord",
|
|
)
|
|
assert body["target"] == "discord://RomM@1...0/a...p/"
|
|
assert body["fields"] == {"botname": "RomM"}
|
|
assert body["stored_secrets"] == ["webhook_id", "webhook_token"]
|
|
assert "abcdefghijklmnop" not in response.text
|
|
|
|
def test_a_user_may_not_use_apprise(self, client, viewer_access_token):
|
|
response = client.post(
|
|
API, json=_apprise(), headers=bearer(viewer_access_token)
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
assert response.json()["detail"] == "Only admins can use Apprise channels"
|
|
|
|
@pytest.mark.parametrize(
|
|
"payload",
|
|
[_apprise("syslog", host="localhost"), _apprise(webhook_id="1234567890")],
|
|
)
|
|
def test_fields_apprise_cannot_use_are_refused(self, client, access_token, payload):
|
|
response = client.post(API, json=payload, headers=bearer(access_token))
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
def test_a_user_has_at_most_so_many(self, client, access_token):
|
|
for n in range(MAX_NOTIFICATION_CHANNELS_PER_USER):
|
|
created = client.post(
|
|
API, json=_webhook(name=f"Hook {n}"), headers=bearer(access_token)
|
|
)
|
|
assert created.status_code == status.HTTP_201_CREATED
|
|
|
|
response = client.post(
|
|
API, json=_webhook(name="One more"), headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
assert "at most" in response.json()["detail"]
|
|
|
|
@pytest.mark.parametrize(
|
|
"payload",
|
|
[
|
|
{"type": "sms", "name": "x", "url": "https://example.com"},
|
|
{"type": "email", "name": "x", "address": "not-an-address"},
|
|
{"type": "apprise", "name": "x", "service": "discord"},
|
|
_webhook(topics=["everything"]),
|
|
_webhook(name=""),
|
|
],
|
|
)
|
|
def test_refuses_a_malformed_channel(self, client, access_token, payload):
|
|
response = client.post(API, json=payload, headers=bearer(access_token))
|
|
|
|
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
|
|
|
|
def test_no_email_without_a_mail_server(self, client, access_token, mocker):
|
|
mocker.patch.object(channels, "EMAIL_ENABLED", False)
|
|
|
|
response = client.post(
|
|
API,
|
|
json={"type": "email", "name": "Mail", "address": "a@example.com"},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
def test_an_address_the_server_refuses_is_not_kept(
|
|
self, client, access_token, admin_user, emailed
|
|
):
|
|
emailed.side_effect = EmailError("The SMTP server refused the message")
|
|
|
|
response = client.post(
|
|
API,
|
|
json={"type": "email", "name": "Mail", "address": "a@example.com"},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_502_BAD_GATEWAY
|
|
assert db_notification_channel_handler.get_channels(admin_user.id) == []
|
|
|
|
|
|
class TestAppriseServices:
|
|
def test_an_admin_gets_each_service_with_its_fields(self, client, access_token):
|
|
response = client.get(f"{API}/apprise-services", headers=bearer(access_token))
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
discord = next(s for s in response.json() if s["id"] == "discord")
|
|
token = next(f for f in discord["fields"] if f["key"] == "webhook_token")
|
|
assert discord["name"] == "Discord"
|
|
assert (token["required"], token["private"], token["advanced"]) == (
|
|
True,
|
|
True,
|
|
False,
|
|
)
|
|
|
|
def test_an_admin_pastes_a_discord_webhook(self, client, access_token):
|
|
response = client.post(
|
|
f"{API}/apprise-services/parse",
|
|
json={
|
|
"url": "https://discord.com/api/webhooks/1234567890/abcdefghijklmnop"
|
|
},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.json() == {"service": "discord", "fields": _DISCORD}
|
|
|
|
def test_a_url_it_cant_read_is_refused(self, client, access_token):
|
|
response = client.post(
|
|
f"{API}/apprise-services/parse",
|
|
json={"url": "nowhere://romm"},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
def test_a_user_gets_none(self, client, viewer_access_token):
|
|
listed = client.get(
|
|
f"{API}/apprise-services", headers=bearer(viewer_access_token)
|
|
)
|
|
parsed = client.post(
|
|
f"{API}/apprise-services/parse",
|
|
json={"url": "ntfys://ntfy.sh/romm"},
|
|
headers=bearer(viewer_access_token),
|
|
)
|
|
|
|
assert listed.status_code == status.HTTP_403_FORBIDDEN
|
|
assert parsed.status_code == status.HTTP_403_FORBIDDEN
|
|
|
|
|
|
class TestEmailConfirmation:
|
|
def test_the_emailed_code_confirms_the_address(self, client, access_token, emailed):
|
|
created = client.post(
|
|
API,
|
|
json={"type": "email", "name": "Mail", "address": "a@example.com"},
|
|
headers=bearer(access_token),
|
|
).json()
|
|
match = re.search(r"Your code is (\d{6})", emailed.call_args.args[2])
|
|
assert match is not None
|
|
code = match.group(1)
|
|
wrong = "000000" if code != "000000" else "111111"
|
|
|
|
assert created["confirmed"] is False
|
|
assert created["target"] == "a@example.com"
|
|
refused = client.post(
|
|
f"{API}/{created['id']}/confirm",
|
|
json={"code": wrong},
|
|
headers=bearer(access_token),
|
|
)
|
|
assert refused.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
confirmed = client.post(
|
|
f"{API}/{created['id']}/confirm",
|
|
json={"code": code},
|
|
headers=bearer(access_token),
|
|
)
|
|
assert confirmed.status_code == status.HTTP_200_OK
|
|
assert confirmed.json()["confirmed"] is True
|
|
|
|
def test_a_new_code_has_to_wait(self, client, access_token, emailed):
|
|
created = client.post(
|
|
API,
|
|
json={"type": "email", "name": "Mail", "address": "a@example.com"},
|
|
headers=bearer(access_token),
|
|
).json()
|
|
|
|
response = client.post(
|
|
f"{API}/{created['id']}/resend-code", headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
|
|
|
|
|
|
class TestOwnership:
|
|
def test_each_user_sees_only_their_own(
|
|
self, client, access_token, viewer_access_token
|
|
):
|
|
client.post(API, json=_webhook(), headers=bearer(access_token))
|
|
|
|
response = client.get(API, headers=bearer(viewer_access_token))
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.json() == []
|
|
|
|
@pytest.mark.parametrize(
|
|
"method,suffix",
|
|
[("patch", ""), ("delete", ""), ("post", "/test"), ("post", "/resend-code")],
|
|
)
|
|
def test_someone_elses_is_not_found(
|
|
self, client, access_token, viewer_access_token, method, suffix
|
|
):
|
|
created = client.post(API, json=_webhook(), headers=bearer(access_token)).json()
|
|
|
|
response = client.request(
|
|
method,
|
|
f"{API}/{created['id']}{suffix}",
|
|
json={} if method == "patch" else None,
|
|
headers=bearer(viewer_access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
|
|
|
|
|
class TestUpdate:
|
|
def test_changes_the_filters_and_drops_the_secret(self, client, access_token):
|
|
created = client.post(
|
|
API, json=_webhook(secret="k"), headers=bearer(access_token)
|
|
).json()
|
|
|
|
response = client.patch(
|
|
f"{API}/{created['id']}",
|
|
json={
|
|
"min_level": "warning",
|
|
"topics": ["scans", "tasks"],
|
|
"secret": "",
|
|
"enabled": False,
|
|
},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
body = response.json()
|
|
assert body["min_level"] == "warning"
|
|
assert body["topics"] == ["scans", "tasks"]
|
|
assert body["has_secret"] is False
|
|
assert body["enabled"] is False
|
|
|
|
def test_apprise_secrets_stay_until_given_again(self, client, access_token):
|
|
created = client.post(API, json=_apprise(), headers=bearer(access_token)).json()
|
|
path = f"{API}/{created['id']}"
|
|
|
|
renamed = client.patch(
|
|
path, json={"name": "Phone"}, headers=bearer(access_token)
|
|
)
|
|
retitled = client.patch(
|
|
path,
|
|
json={"fields": {"webhook_id": "1234567890", "botname": "Bot"}},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert renamed.json()["target"] == created["target"]
|
|
assert retitled.json()["target"] == "discord://Bot@1...0/a...p/"
|
|
|
|
def test_null_topics_forwards_everything_again(self, client, access_token):
|
|
created = client.post(
|
|
API, json=_webhook(topics=["scans"]), headers=bearer(access_token)
|
|
).json()
|
|
|
|
response = client.patch(
|
|
f"{API}/{created['id']}",
|
|
json={"topics": None},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert response.json()["topics"] is None
|
|
|
|
|
|
class TestTest:
|
|
def test_a_delivery_is_recorded(self, client, access_token, sent):
|
|
created = client.post(API, json=_webhook(), headers=bearer(access_token)).json()
|
|
|
|
response = client.post(
|
|
f"{API}/{created['id']}/test", headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.json() == {"ok": True, "error": None}
|
|
[listed] = client.get(API, headers=bearer(access_token)).json()
|
|
assert listed["last_delivered_at"] is not None
|
|
|
|
def test_a_failure_is_reported_but_not_counted(self, client, access_token, sent):
|
|
sent.side_effect = EmailError("refused")
|
|
created = client.post(API, json=_webhook(), headers=bearer(access_token)).json()
|
|
|
|
response = client.post(
|
|
f"{API}/{created['id']}/test", headers=bearer(access_token)
|
|
)
|
|
|
|
assert response.json() == {"ok": False, "error": "refused"}
|
|
[listed] = client.get(API, headers=bearer(access_token)).json()
|
|
assert listed["last_error"] == "refused"
|
|
assert listed["consecutive_failures"] == 0
|
|
|
|
|
|
class TestDeliveryBookkeeping:
|
|
def test_turns_off_once_it_failed_too_often(self, client, access_token, admin_user):
|
|
created = client.post(API, json=_webhook(), headers=bearer(access_token)).json()
|
|
|
|
for _ in range(MAX_CONSECUTIVE_DELIVERY_FAILURES - 1):
|
|
db_notification_channel_handler.record_failure(
|
|
created["id"], "boom", counts=True
|
|
)
|
|
assert not db_notification_channel_handler.turn_off_if_failing(created["id"])
|
|
|
|
db_notification_channel_handler.record_failure(
|
|
created["id"], "boom", counts=True
|
|
)
|
|
assert db_notification_channel_handler.turn_off_if_failing(created["id"])
|
|
assert not db_notification_channel_handler.turn_off_if_failing(created["id"])
|
|
assert (
|
|
db_notification_channel_handler.get_deliverable_channels([admin_user.id])
|
|
== []
|
|
)
|
|
|
|
def test_an_unconfirmed_address_gets_nothing(
|
|
self, client, access_token, admin_user, emailed
|
|
):
|
|
client.post(
|
|
API,
|
|
json={"type": "email", "name": "Mail", "address": "a@example.com"},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert (
|
|
db_notification_channel_handler.get_deliverable_channels([admin_user.id])
|
|
== []
|
|
)
|