mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* test(api): check that routes document the error statuses they raise protected_route now documents the scope guard's 401 and 403 on every route that declares scopes, appending to a route's own description when it has one. tools/route_errors.py follows each route's calls through imports, handler instances, custom exception classes and HTTPException subclasses to the statuses it can raise. test_raised_statuses_are_documented fails on a status the route's responses= leaves out, against a baseline of existing gaps that can only shrink. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for roms routes Describe every 4xx and 5xx the rom routes and their helpers raise in each decorator's responses=, so the OpenAPI schema lists them. A hidden rom, platform or file is described like a missing one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for saves routes Describe every 4xx/5xx the saves, states, screenshots, snapshots, play-sessions and sync routes raise in their responses=, and rewrite the states identifiers docstring that carried Args/Returns blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for devices routes Describe the 4xx/5xx statuses that the device, device auth, install, client token, notification, notification channel, sync channel and heartbeat routes raise, and fill the empty install route entries. Rewrite the setup and heartbeat docstrings that published Args and Returns blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for streaming routes Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for admin routes Describe the 4xx and 5xx statuses the config, permissions, user, auth, tasks, logs, activity and export routes raise, and rewrite their Args/Returns docstrings as plain operation descriptions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): document error responses for library routes Describe the 400/403/404/409/500 statuses the collection, feed, firmware, platform, music, playlist and search routes raise, and replace route docstrings that carried Args/Returns blocks with plain sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): answer like a missing resource for hidden play sessions and private collections DELETE /play-sessions/{id} deleted the caller's session even on a rom hidden from them, so 204 versus 404 showed the session existed. The handler now takes the caller's rom visibility. Another user's private collection, smart collection or playlist answered 403, which showed it existed. It now answers 404 on every route; a public one the caller does not own still answers 403 on write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): describe private collections and playlists as missing Matches #5686, where another user's private collection or playlist answers 404 and a play session on a hidden rom answers like a missing one. The read routes drop their 403, and the write 403 now covers only a public resource another user owns. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(collections): use #5693's docstrings on the routes this PR touches Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): address Greptile review on route error docs Fold the nine multi-paragraph route docstrings into one line, and keep the device-scope 403 descriptions in utils/auth.py next to resolve_device, which raises them, instead of in both saves.py and states.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(api): follow route dependencies in the status analyzer Addresses Greptile's review: route_errors now follows the callable in Depends(...) and Security(...), whether it is a parameter default or inside an Annotated alias, and the module docstring is one line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): tighten wording of route error descriptions Give clipped responses descriptions and helper docstrings their missing subjects and verbs, use 'the caller lacks' and 'is not allowed to' consistently, and replace 'picked' with 'chosen'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(api): drop the route error baseline Every status left in the baseline was one a client cannot get: - The export routes' empty platform list check is dead, since FastAPI answers a missing required list query with 422. Removed. - get_save_layouts went through _restore_error, whose 500 fallback it cannot reach. It raises its 400 and 503 directly now. - The notification test and confirm routes only catch ChannelError, since the cooldown and email errors come from other actions. - The analyzer now skips asyncio.gather(..., return_exceptions=True), which covers search_rom. - A '# route-errors: ignore' marker, with its reason, skips code whose errors never reach the client: the metadata heartbeat probe, the force-release teardowns, and the legacy save adoption. The check now fails on any undocumented status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
366 lines
12 KiB
Python
366 lines
12 KiB
Python
from pathlib import Path
|
|
from typing import Annotated
|
|
|
|
from fastapi import Body, File, HTTPException
|
|
from fastapi import Path as PathVar
|
|
from fastapi import 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"],
|
|
)
|
|
|
|
|
|
FirmwareIdPath = Annotated[int, PathVar(description="The ID of the firmware file.")]
|
|
FirmwareFileNamePath = Annotated[
|
|
str,
|
|
PathVar(
|
|
description="A file name to end the URL with, which EmulatorJS needs because of a bug. It does not change the name of the downloaded file."
|
|
),
|
|
]
|
|
FIRMWARE_CONTENT_404 = "No firmware the caller can see has this ID, or its file is missing from the filesystem."
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"",
|
|
[Scope.FIRMWARE_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "The name of an uploaded file is not a valid file name."
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "No platform the caller can see has this ID."
|
|
},
|
|
},
|
|
)
|
|
async def add_firmware(
|
|
request: Request,
|
|
platform_id: int,
|
|
files: list[UploadFile] = File(...), # noqa: B008
|
|
) -> AddFirmwareResponse:
|
|
"""Upload firmware files to a platform, replacing any file with the same name."""
|
|
|
|
# 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]:
|
|
"""List the firmware the caller can see, from every platform or from `platform_id` only."""
|
|
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]:
|
|
"""List the IDs of the firmware the caller can see."""
|
|
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],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "No firmware the caller can see has this ID."
|
|
}
|
|
},
|
|
)
|
|
def get_firmware(request: Request, id: FirmwareIdPath) -> FirmwareSchema:
|
|
"""Get a firmware file's details."""
|
|
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],
|
|
responses={status.HTTP_404_NOT_FOUND: {"description": FIRMWARE_CONTENT_404}},
|
|
)
|
|
def head_firmware_content(
|
|
request: Request, id: FirmwareIdPath, file_name: FirmwareFileNamePath
|
|
) -> FileResponse:
|
|
"""Get the headers of a firmware file download, without its content."""
|
|
|
|
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],
|
|
responses={status.HTTP_404_NOT_FOUND: {"description": FIRMWARE_CONTENT_404}},
|
|
)
|
|
def get_firmware_content(
|
|
request: Request,
|
|
id: FirmwareIdPath,
|
|
file_name: FirmwareFileNamePath,
|
|
) -> FileResponse:
|
|
"""Download a 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],
|
|
responses={
|
|
status.HTTP_403_FORBIDDEN: {
|
|
"description": "The caller is not allowed to delete firmware."
|
|
}
|
|
},
|
|
)
|
|
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,
|
|
}
|