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>
376 lines
11 KiB
Python
376 lines
11 KiB
Python
from pathlib import Path
|
|
from typing import Annotated
|
|
|
|
from fastapi import Body, File, HTTPException, Query, Request, UploadFile, status
|
|
from fastapi.responses import FileResponse
|
|
|
|
from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses import BulkOperationResponse
|
|
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
|
|
from handler.audit_handler import (
|
|
AuditActor,
|
|
AuditDraft,
|
|
AuditTarget,
|
|
record,
|
|
record_many,
|
|
)
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import (
|
|
assert_can,
|
|
get_permissions,
|
|
visible_firmware_or_404,
|
|
visible_platform_or_404,
|
|
)
|
|
from handler.database import db_firmware_handler, db_platform_handler
|
|
from handler.filesystem import fs_firmware_handler
|
|
from handler.scan_handler import scan_firmware
|
|
from logger.formatter import BLUE
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction
|
|
from models.firmware import Firmware
|
|
from models.permission import PermAction, PermEntity
|
|
from utils.router import APIRouter
|
|
|
|
router = APIRouter(
|
|
prefix="/firmware",
|
|
tags=["firmware"],
|
|
)
|
|
|
|
|
|
@protected_route(router.post, "", [Scope.FIRMWARE_WRITE])
|
|
async def add_firmware(
|
|
request: Request,
|
|
platform_id: int,
|
|
files: list[UploadFile] = File(...), # noqa: B008
|
|
) -> AddFirmwareResponse:
|
|
"""Upload firmware files endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
platform_slug (str): Slug of the platform where to upload the files
|
|
files (list[UploadFile], optional): List of files to upload
|
|
|
|
Raises:
|
|
HTTPException
|
|
|
|
Returns:
|
|
AddFirmwareResponse: Standard message response
|
|
"""
|
|
|
|
# Platform-hide cascades to firmware; 404-mask uploads to hidden platforms.
|
|
db_platform = visible_platform_or_404(
|
|
request,
|
|
db_platform_handler.get_platform(platform_id),
|
|
f"Platform with ID {platform_id} not found",
|
|
)
|
|
|
|
# write_file stores each upload under its sanitized basename, so the lookup,
|
|
# scan and row must use that same name. Check them all before writing any.
|
|
uploads: list[tuple[UploadFile, str]] = []
|
|
for file in files:
|
|
if not file.filename:
|
|
log.warning("Empty filename, skipping")
|
|
continue
|
|
try:
|
|
file_name = fs_firmware_handler._sanitize_filename(file.filename)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Invalid upload filename: {exc}",
|
|
) from exc
|
|
uploads.append((file, file_name))
|
|
|
|
uploaded_firmware = []
|
|
firmware_path = fs_firmware_handler.get_firmware_fs_structure(db_platform.fs_slug)
|
|
|
|
for file, file_name in uploads:
|
|
log.info(
|
|
f"Uploading firmware {hl(file_name)} to {hl(db_platform.custom_name or db_platform.name, color=BLUE)}"
|
|
)
|
|
|
|
await fs_firmware_handler.write_file(
|
|
file=file, path=firmware_path, filename=file_name
|
|
)
|
|
|
|
db_firmware = db_firmware_handler.get_firmware_by_filename(
|
|
platform_id=db_platform.id, file_name=file_name
|
|
)
|
|
# Scan or update firmware
|
|
scanned_firmware = await scan_firmware(
|
|
platform=db_platform,
|
|
file_name=file_name,
|
|
firmware=db_firmware,
|
|
)
|
|
|
|
is_verified = Firmware.verify_file_hashes(
|
|
platform_slug=db_platform.slug,
|
|
file_name=file_name,
|
|
file_size_bytes=scanned_firmware.file_size_bytes,
|
|
md5_hash=scanned_firmware.md5_hash,
|
|
sha1_hash=scanned_firmware.sha1_hash,
|
|
crc_hash=scanned_firmware.crc_hash,
|
|
)
|
|
|
|
if db_firmware:
|
|
db_firmware_handler.update_firmware(
|
|
db_firmware.id,
|
|
{
|
|
"file_size_bytes": scanned_firmware.file_size_bytes,
|
|
"is_verified": is_verified,
|
|
},
|
|
)
|
|
continue
|
|
|
|
scanned_firmware.platform_id = db_platform.id
|
|
scanned_firmware.is_verified = is_verified
|
|
db_firmware_handler.add_firmware(scanned_firmware)
|
|
uploaded_firmware.append(scanned_firmware)
|
|
|
|
record(
|
|
AuditAction.FIRMWARE_UPLOAD,
|
|
request,
|
|
AuditTarget.of_platform(db_platform),
|
|
{"file_names": [file_name for _, file_name in uploads]},
|
|
)
|
|
|
|
return {
|
|
"uploaded": len(files),
|
|
"firmware": [
|
|
FirmwareSchema.model_validate(f)
|
|
for f in db_firmware_handler.list_firmware(
|
|
platform_ids=[platform_id] if platform_id else None
|
|
)
|
|
],
|
|
}
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.FIRMWARE_READ])
|
|
def get_platform_firmware(
|
|
request: Request,
|
|
platform_id: int | None = None,
|
|
missing: Annotated[
|
|
bool | None,
|
|
Query(description="Whether the firmware is missing from the filesystem."),
|
|
] = None,
|
|
) -> list[FirmwareSchema]:
|
|
"""Get firmware endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
list[FirmwareSchema]: Firmware stored in the database
|
|
"""
|
|
perms = get_permissions(request)
|
|
return [
|
|
FirmwareSchema.model_validate(f)
|
|
for f in db_firmware_handler.list_firmware(
|
|
platform_ids=[platform_id] if platform_id else None,
|
|
missing=missing,
|
|
hidden_platform_ids=perms.hidden_platform_ids,
|
|
)
|
|
]
|
|
|
|
|
|
@protected_route(router.get, "/identifiers", [Scope.FIRMWARE_READ])
|
|
def get_firmware_identifiers(
|
|
request: Request,
|
|
) -> list[int]:
|
|
"""Get firmware identifiers endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
|
|
Returns:
|
|
list[int]: List of firmware IDs
|
|
"""
|
|
perms = get_permissions(request)
|
|
return db_firmware_handler.list_firmware_ids(
|
|
hidden_platform_ids=perms.hidden_platform_ids,
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
|
|
)
|
|
def get_firmware(request: Request, id: int) -> FirmwareSchema:
|
|
"""Get firmware endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Firmware internal id
|
|
|
|
Returns:
|
|
FirmwareSchema: Firmware stored in the database
|
|
"""
|
|
firmware = visible_firmware_or_404(
|
|
request, db_firmware_handler.get_firmware(id), id
|
|
)
|
|
|
|
return FirmwareSchema.model_validate(firmware)
|
|
|
|
|
|
def _resolve_firmware_content(request: Request, id: int) -> tuple[Firmware, Path]:
|
|
"""Resolve a firmware row and the readable file backing it.
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Firmware internal id
|
|
|
|
Returns:
|
|
tuple[Firmware, Path]: The firmware row and its absolute path on disk
|
|
"""
|
|
|
|
firmware = visible_firmware_or_404(
|
|
request, db_firmware_handler.get_firmware(id), id
|
|
)
|
|
|
|
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
|
# A row can outlive its file: the scan marks it missing, or it was moved
|
|
# away without one. Either way FileResponse would raise a 500.
|
|
if firmware.missing_from_fs or not firmware_path.is_file():
|
|
error = f"Firmware file '{firmware.file_name}' is missing from filesystem"
|
|
log.error(error)
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
|
|
|
return firmware, firmware_path
|
|
|
|
|
|
@protected_route(
|
|
router.head,
|
|
"/{id}/content/{file_name}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
|
|
)
|
|
def head_firmware_content(request: Request, id: int, file_name: str) -> FileResponse:
|
|
"""Head firmware content endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Rom internal id
|
|
file_name (str): Required due to a bug in emulatorjs
|
|
|
|
Returns:
|
|
FileResponse: Returns the response with headers
|
|
"""
|
|
|
|
firmware, firmware_path = _resolve_firmware_content(request, id)
|
|
|
|
return FileResponse(
|
|
path=firmware_path,
|
|
filename=file_name,
|
|
headers={
|
|
"Content-Length": str(firmware.file_size_bytes),
|
|
},
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}/content/{file_name}",
|
|
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
|
|
)
|
|
def get_firmware_content(
|
|
request: Request,
|
|
id: int,
|
|
file_name: str,
|
|
) -> FileResponse:
|
|
"""Download firmware endpoint
|
|
|
|
Args:
|
|
request (Request): Fastapi Request object
|
|
id (int): Rom internal id
|
|
file_name (str): Required due to a bug in emulatorjs
|
|
|
|
Returns:
|
|
FileResponse: Returns the firmware file
|
|
"""
|
|
|
|
firmware, firmware_path = _resolve_firmware_content(request, id)
|
|
|
|
return FileResponse(path=firmware_path, filename=firmware.file_name)
|
|
|
|
|
|
@protected_route(router.post, "/delete", [Scope.FIRMWARE_WRITE])
|
|
async def delete_firmware(
|
|
request: Request,
|
|
firmware: Annotated[
|
|
list[int],
|
|
Body(
|
|
description="List of firmware ids to delete from database.",
|
|
embed=True,
|
|
),
|
|
],
|
|
delete_from_fs: Annotated[
|
|
list[int],
|
|
Body(
|
|
description="List of firmware ids to delete from filesystem.",
|
|
default_factory=list,
|
|
embed=True,
|
|
),
|
|
],
|
|
) -> BulkOperationResponse:
|
|
"""Delete firmware."""
|
|
|
|
perms = get_permissions(request)
|
|
assert_can(perms, PermEntity.FIRMWARE, PermAction.DELETE)
|
|
|
|
successful_items = 0
|
|
failed_ids = []
|
|
errors = []
|
|
actor = AuditActor.from_request(request)
|
|
audit_drafts: list[AuditDraft] = []
|
|
|
|
for id in firmware:
|
|
fw = db_firmware_handler.get_firmware(id)
|
|
# Treat firmware on a hidden platform as non-existent for this caller.
|
|
if not fw or not perms.can_see_platform(fw.platform_id):
|
|
failed_ids.append(id)
|
|
errors.append(f"Firmware with ID {id} not found")
|
|
continue
|
|
|
|
deleted = removed = False
|
|
try:
|
|
log.info(f"Deleting {hl(fw.file_name)} from database")
|
|
db_firmware_handler.delete_firmware(id)
|
|
deleted = True
|
|
|
|
if id in delete_from_fs:
|
|
log.info(f"Deleting {hl(fw.file_name)} from filesystem")
|
|
try:
|
|
file_path = f"{fw.file_path}/{fw.file_name}"
|
|
await fs_firmware_handler.remove_file(file_path=file_path)
|
|
removed = True
|
|
except FileNotFoundError:
|
|
error = f"Firmware file {hl(fw.file_name)} not found for platform {hl(fw.platform.slug)}"
|
|
log.error(error)
|
|
errors.append(error)
|
|
failed_ids.append(id)
|
|
continue
|
|
|
|
successful_items += 1
|
|
except Exception as e:
|
|
failed_ids.append(id)
|
|
errors.append(f"Failed to delete firmware {id}: {str(e)}")
|
|
finally:
|
|
# The row is gone whatever became of its file.
|
|
if deleted:
|
|
audit_drafts.append(
|
|
AuditDraft(
|
|
AuditAction.FIRMWARE_DELETE,
|
|
actor,
|
|
AuditTarget.of_firmware(fw),
|
|
{"deleted_from_fs": removed},
|
|
)
|
|
)
|
|
|
|
record_many(audit_drafts)
|
|
return {
|
|
"successful_items": successful_items,
|
|
"failed_ids": failed_ids,
|
|
"errors": errors,
|
|
}
|