Files
romm/backend/endpoints/firmware.py
Georges-Antoine Assi 3b14dddd88 chore(prose): fix the prose-check findings on master (#5826)
The scheduled Trunk Check (all files) run fails on 79 prose-check issues
that predate the linter: clipped 'X, else Y' chains, 'internal id' in
API descriptions, and clipped 'Left out, ...' conditionals.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 08:17:01 -05:00

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): The ID of the firmware
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,
}