mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 10:08:40 +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>
219 lines
7.4 KiB
Python
219 lines
7.4 KiB
Python
import base64
|
|
import uuid
|
|
from typing import cast
|
|
from unittest.mock import Mock, 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 endpoints import auth as auth_endpoints
|
|
from endpoints import permissions as permission_endpoints
|
|
from handler.auth.base_handler import auth_handler
|
|
from models.user import User
|
|
from tasks.tasks import TaskSpec, TaskType
|
|
|
|
|
|
def _basic(username: str, password: str) -> dict[str, str]:
|
|
encoded = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
return {"Authorization": f"Basic {encoded}"}
|
|
|
|
|
|
class TestLogin:
|
|
def test_a_session_login_names_its_device(
|
|
self, client: TestClient, admin_user: User
|
|
):
|
|
response = client.post(
|
|
"/api/login", headers=_basic("test_admin", "test_admin_password")
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
[event] = recorded_events()
|
|
assert event.action == "auth.login"
|
|
assert event.actor_id == admin_user.id
|
|
assert event.device_id is not None
|
|
assert event.data == {"method": "password"}
|
|
|
|
def test_repeated_failures_from_one_address_are_one_attempt(
|
|
self, client: TestClient, admin_user: User
|
|
):
|
|
for _ in range(3):
|
|
response = client.post("/api/login", headers=_basic("test_admin", "wrong"))
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
|
|
[event] = recorded_events()
|
|
assert event.action == "auth.login_failed"
|
|
assert event.actor_id == admin_user.id
|
|
assert event.data["reason"] == "credentials"
|
|
|
|
def test_a_failure_for_an_unknown_name_keeps_no_name(self, client: TestClient):
|
|
client.post("/api/login", headers=_basic("hunter2", "wrong"))
|
|
|
|
[event] = recorded_events()
|
|
assert event.actor_kind == "anonymous"
|
|
assert event.data["username"] is None
|
|
|
|
def test_one_address_cycling_usernames_is_capped(self, client: TestClient, mocker):
|
|
mocker.patch.object(auth_endpoints, "LOGIN_FAILURES_PER_ADDRESS", 3)
|
|
|
|
for i in range(6):
|
|
client.post("/api/login", headers=_basic(f"guess{i}", "wrong"))
|
|
|
|
assert len(recorded_events()) == 3
|
|
|
|
def test_repeated_reset_requests_are_one(
|
|
self, client: TestClient, admin_user: User, mocker
|
|
):
|
|
mocker.patch.object(auth_handler, "send_password_reset_link")
|
|
|
|
for _ in range(2):
|
|
client.post("/api/forgot-password", json={"username": "test_admin"})
|
|
|
|
[event] = recorded_events()
|
|
assert event.action == "auth.password_reset_request"
|
|
assert (event.actor_kind, event.target_name) == ("anonymous", "test_admin")
|
|
|
|
def test_a_reset_request_is_recorded_when_its_link_fails(
|
|
self, client: TestClient, admin_user: User, mocker
|
|
):
|
|
mocker.patch.object(
|
|
auth_handler, "send_password_reset_link", side_effect=RuntimeError("smtp")
|
|
)
|
|
|
|
with pytest.raises(RuntimeError):
|
|
client.post("/api/forgot-password", json={"username": "test_admin"})
|
|
|
|
[event] = recorded_events()
|
|
assert event.action == "auth.password_reset_request"
|
|
|
|
def test_a_token_grant_is_a_login(self, client: TestClient, admin_user: User):
|
|
response = client.post(
|
|
"/api/token",
|
|
data={
|
|
"grant_type": "password",
|
|
"username": "test_admin",
|
|
"password": "test_admin_password",
|
|
},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
[event] = recorded_events()
|
|
assert (event.action, event.data["method"]) == ("auth.login", "token")
|
|
|
|
|
|
class TestUsers:
|
|
def test_a_role_change_records_both_roles(
|
|
self, client: TestClient, access_token: str, viewer_user: User
|
|
):
|
|
client.put(
|
|
f"/api/users/{viewer_user.id}",
|
|
data={"role": "admin"},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
[event] = recorded_events()
|
|
assert event.action == "user.edit"
|
|
assert event.target_name == "test_viewer"
|
|
assert event.data["changed"] == ["role"]
|
|
assert event.data["role"] == {"from": "user", "to": "admin"}
|
|
|
|
def test_saving_ui_settings_is_not_an_edit(
|
|
self, client: TestClient, access_token: str, admin_user: User
|
|
):
|
|
client.put(
|
|
f"/api/users/{admin_user.id}",
|
|
data={"ui_settings": '{"theme": "dark"}'},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
assert recorded_events() == []
|
|
|
|
def test_a_deleted_user_keeps_their_name(
|
|
self, client: TestClient, access_token: str, viewer_user: User
|
|
):
|
|
client.delete(f"/api/users/{viewer_user.id}", headers=bearer(access_token))
|
|
|
|
[event] = recorded_events()
|
|
assert (event.action, event.target_name) == ("user.delete", "test_viewer")
|
|
|
|
|
|
@patch("endpoints.tasks.has_live_worker", return_value=True)
|
|
@patch(
|
|
"endpoints.tasks.enqueue_task",
|
|
return_value=Mock(
|
|
id="job-1",
|
|
created_at=None,
|
|
enqueued_at=None,
|
|
**{"get_status.return_value": "queued"},
|
|
),
|
|
)
|
|
def test_a_manual_task_run_is_recorded(
|
|
_enqueue, _worker, client: TestClient, access_token: str
|
|
):
|
|
task = Mock(spec=TaskSpec)
|
|
task.title = "Cleanup"
|
|
task.task_type = TaskType.CLEANUP
|
|
task.can_run_manually = True
|
|
task.single_instance = False
|
|
with patch("endpoints.tasks.RUNNABLE_TASKS", {"cleanup": task}):
|
|
client.post("/api/tasks/run/cleanup", headers=bearer(access_token))
|
|
|
|
[event] = recorded_events()
|
|
assert event.action == "task.run"
|
|
assert (event.target_id, event.target_name) == ("cleanup", "Cleanup")
|
|
assert event.data["job_id"] == "job-1"
|
|
|
|
|
|
class TestClientTokens:
|
|
@pytest.fixture
|
|
def token_id(self, client: TestClient, access_token: str) -> int:
|
|
response = client.post(
|
|
"/api/client-tokens",
|
|
json={"name": "Argosy", "scopes": ["roms.read"]},
|
|
headers=bearer(access_token),
|
|
)
|
|
return cast(int, response.json()["id"])
|
|
|
|
def test_creating_and_revoking_are_recorded(
|
|
self, client: TestClient, access_token: str, token_id: int
|
|
):
|
|
client.delete(f"/api/client-tokens/{token_id}", headers=bearer(access_token))
|
|
|
|
revoke, create = recorded_events()
|
|
assert create.action == "client_token.create"
|
|
assert revoke.action == "client_token.revoke"
|
|
assert revoke.target_name == "Argosy"
|
|
assert revoke.data["scopes"] == ["roms.read"]
|
|
|
|
|
|
def test_a_hide_succeeds_when_naming_it_for_the_log_fails(
|
|
client: TestClient, access_token: str, viewer_user: User, rom, mocker
|
|
):
|
|
mocker.patch.object(
|
|
permission_endpoints, "_principal", side_effect=RuntimeError("db gone")
|
|
)
|
|
|
|
response = client.post(
|
|
"/api/permissions/hidden",
|
|
headers=bearer(access_token),
|
|
json={"entity": "roms", "entity_id": rom.id, "user_id": viewer_user.id},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert recorded_events() == []
|
|
|
|
|
|
def test_a_new_permission_group_is_recorded(client: TestClient, access_token: str):
|
|
# Groups outlive a test, so the name has to be one no earlier run left behind.
|
|
name = f"Kids {uuid.uuid4().hex[:8]}"
|
|
client.post(
|
|
"/api/permissions/groups",
|
|
json={"name": name, "grants": []},
|
|
headers=bearer(access_token),
|
|
)
|
|
|
|
[event] = recorded_events()
|
|
assert (event.action, event.target_name) == ("permission_group.create", name)
|