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>
164 lines
5.4 KiB
Python
164 lines
5.4 KiB
Python
import asyncio
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
from fastapi import status
|
|
from tests.auth_helpers import bearer
|
|
|
|
from endpoints.logs import MAX_LOG_LIMIT
|
|
from endpoints.sockets.logs import (
|
|
FORWARDER_LOCK_KEY,
|
|
get_recent_logs,
|
|
start_log_forwarder,
|
|
)
|
|
from utils import json_module
|
|
|
|
SAMPLE_ENTRY = {"ts": 1, "level": "INFO", "module": "startup", "message": "hello"}
|
|
|
|
|
|
def test_get_logs_requires_auth(client):
|
|
response = client.get("/api/logs")
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
|
|
|
|
def test_get_logs_forbidden_without_logs_read(client, viewer_access_token):
|
|
# Viewers lack the `logs.read` (admin-only) scope the endpoint requires.
|
|
response = client.get("/api/logs", headers=bearer(viewer_access_token))
|
|
assert response.status_code == status.HTTP_403_FORBIDDEN
|
|
|
|
|
|
def test_get_logs_returns_entries_for_admin(client, access_token):
|
|
with patch(
|
|
"endpoints.logs.get_recent_logs",
|
|
new_callable=AsyncMock,
|
|
return_value=[SAMPLE_ENTRY],
|
|
):
|
|
response = client.get("/api/logs", headers=bearer(access_token))
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.json() == [SAMPLE_ENTRY]
|
|
|
|
|
|
def test_get_logs_disabled_returns_not_found(client, access_token):
|
|
# When DISABLE_LOGS_VIEWER is set, the endpoint is gone even for admins.
|
|
with patch("endpoints.logs.DISABLE_LOGS_VIEWER", True):
|
|
response = client.get("/api/logs", headers=bearer(access_token))
|
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
|
|
|
|
|
def test_get_logs_clamps_limit(client, access_token):
|
|
with patch(
|
|
"endpoints.logs.get_recent_logs",
|
|
new_callable=AsyncMock,
|
|
return_value=[],
|
|
) as mock_recent:
|
|
# Above the cap → clamped down to MAX_LOG_LIMIT.
|
|
client.get(
|
|
f"/api/logs?limit={MAX_LOG_LIMIT + 5000}", headers=bearer(access_token)
|
|
)
|
|
mock_recent.assert_awaited_with(MAX_LOG_LIMIT)
|
|
|
|
# Below 1 → clamped up to 1.
|
|
mock_recent.reset_mock()
|
|
client.get("/api/logs?limit=0", headers=bearer(access_token))
|
|
mock_recent.assert_awaited_with(1)
|
|
|
|
# In range → passed through unchanged.
|
|
mock_recent.reset_mock()
|
|
client.get("/api/logs?limit=25", headers=bearer(access_token))
|
|
mock_recent.assert_awaited_with(25)
|
|
|
|
|
|
def test_get_recent_logs_returns_oldest_first_and_skips_malformed():
|
|
# The ring buffer is newest-first (LPUSH); get_recent_logs must return
|
|
# oldest-first and drop any unparseable entry.
|
|
newest_first = [
|
|
json_module.dumps({"ts": 3, "level": "INFO", "module": "m", "message": "c"}),
|
|
"not-json",
|
|
json_module.dumps({"ts": 2, "level": "INFO", "module": "m", "message": "b"}),
|
|
json_module.dumps({"ts": 1, "level": "INFO", "module": "m", "message": "a"}),
|
|
]
|
|
mock_cache = MagicMock()
|
|
mock_cache.lrange = AsyncMock(return_value=newest_first)
|
|
|
|
with patch("endpoints.sockets.logs.async_cache", mock_cache):
|
|
result = asyncio.run(get_recent_logs(10))
|
|
|
|
assert [entry["ts"] for entry in result] == [1, 2, 3]
|
|
|
|
|
|
def _fake_lock_cache() -> MagicMock:
|
|
"""A str-valued lock store, since the test fakeredis returns bytes."""
|
|
store: dict[str, Any] = {}
|
|
|
|
async def set_(key, value, nx=False, ex=None):
|
|
if nx and key in store:
|
|
return None
|
|
store[key] = value
|
|
return True
|
|
|
|
async def get(key):
|
|
return store.get(key)
|
|
|
|
async def delete(key):
|
|
store.pop(key, None)
|
|
|
|
cache = MagicMock()
|
|
cache.store = store
|
|
cache.set = AsyncMock(side_effect=set_)
|
|
cache.get = AsyncMock(side_effect=get)
|
|
cache.delete = AsyncMock(side_effect=delete)
|
|
return cache
|
|
|
|
|
|
def test_log_forwarder_resumes_after_a_redis_error():
|
|
broken = MagicMock()
|
|
broken.subscribe = AsyncMock(side_effect=ConnectionError("valkey restarted"))
|
|
broken.aclose = AsyncMock()
|
|
|
|
healthy = MagicMock()
|
|
healthy.subscribe = AsyncMock()
|
|
healthy.aclose = AsyncMock()
|
|
messages = [{"data": json_module.dumps(SAMPLE_ENTRY)}]
|
|
|
|
async def get_message(**kwargs):
|
|
if messages:
|
|
return messages.pop()
|
|
await asyncio.sleep(kwargs["timeout"])
|
|
return None
|
|
|
|
healthy.get_message = AsyncMock(side_effect=get_message)
|
|
|
|
cache = _fake_lock_cache()
|
|
cache.pubsub = MagicMock(side_effect=[broken, healthy])
|
|
manager = MagicMock()
|
|
|
|
async def run() -> None:
|
|
forwarded = asyncio.Event()
|
|
manager.emit = AsyncMock(side_effect=lambda *a, **kw: forwarded.set())
|
|
task = asyncio.create_task(start_log_forwarder())
|
|
await asyncio.wait_for(forwarded.wait(), timeout=5)
|
|
task.cancel()
|
|
try:
|
|
await task
|
|
except asyncio.CancelledError:
|
|
pass
|
|
|
|
with (
|
|
patch("endpoints.sockets.logs.DISABLE_LOGS_VIEWER", False),
|
|
patch("endpoints.sockets.logs.FORWARDER_LOCK_TTL", 0.03),
|
|
patch("endpoints.sockets.logs.async_cache", cache),
|
|
patch(
|
|
"endpoints.sockets.logs.socket_handler.write_manager",
|
|
return_value=manager,
|
|
),
|
|
):
|
|
asyncio.run(run())
|
|
|
|
manager.emit.assert_any_await("logs:entry", SAMPLE_ENTRY, room="admin")
|
|
# The dead connection is closed even though it never subscribed.
|
|
broken.aclose.assert_awaited_once()
|
|
healthy.aclose.assert_awaited_once()
|
|
# Cancelling releases the lock so a restart picks up straight away.
|
|
assert FORWARDER_LOCK_KEY not in cache.store
|