mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +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>
327 lines
11 KiB
Python
327 lines
11 KiB
Python
from collections.abc import Awaitable
|
|
from functools import cache
|
|
from typing import TypeVar
|
|
|
|
from fastapi import HTTPException, Request, status
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.notification_channel import (
|
|
AppriseServiceSchema,
|
|
AppriseUrlFieldsSchema,
|
|
AppriseUrlPayload,
|
|
NotificationChannelCodePayload,
|
|
NotificationChannelCreatePayload,
|
|
NotificationChannelSchema,
|
|
NotificationChannelTestResult,
|
|
NotificationChannelUpdatePayload,
|
|
)
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import assert_admin
|
|
from handler.database import db_notification_channel_handler
|
|
from handler.email_handler import EmailError
|
|
from handler.notification_channels import apprise_channel, channels
|
|
from handler.notification_channels.channels import ChannelError
|
|
from handler.notification_channels.confirmation import CodeCooldownError
|
|
from models.notification_channel import NotificationChannel, NotificationChannelType
|
|
from models.user import User
|
|
from utils.router import APIRouter
|
|
|
|
router = APIRouter(
|
|
prefix="/notification-channels",
|
|
tags=["notification-channels"],
|
|
)
|
|
|
|
_T = TypeVar("_T")
|
|
|
|
|
|
def _get_or_404(channel_id: int, user: User) -> NotificationChannel:
|
|
channel = db_notification_channel_handler.get_channel(channel_id, user.id)
|
|
if channel is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Notification channel not found",
|
|
)
|
|
return channel
|
|
|
|
|
|
async def _as_http(action: Awaitable[_T]) -> _T:
|
|
"""Await a channel action, turning its errors into the matching HTTP status."""
|
|
try:
|
|
return await action
|
|
except ChannelError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
|
) from exc
|
|
except CodeCooldownError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail=str(exc)
|
|
) from exc
|
|
except EmailError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)
|
|
) from exc
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.ME_READ])
|
|
def get_notification_channels(request: Request) -> list[NotificationChannelSchema]:
|
|
"""The caller's notification channels."""
|
|
return [
|
|
NotificationChannelSchema.from_channel(channel)
|
|
for channel in db_notification_channel_handler.get_channels(request.user.id)
|
|
]
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/apprise-services",
|
|
[Scope.ME_READ],
|
|
responses={
|
|
status.HTTP_403_FORBIDDEN: {"description": "The caller is not an admin."},
|
|
},
|
|
)
|
|
def get_apprise_services(request: Request) -> list[AppriseServiceSchema]:
|
|
"""Every service an admin's Apprise channel can go out on, with its fields."""
|
|
assert_admin(request)
|
|
return _apprise_catalog()
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/apprise-services/parse",
|
|
[Scope.ME_READ],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": (
|
|
"Apprise cannot read the URL, or the URL is for a service RomM does"
|
|
" not offer."
|
|
)
|
|
},
|
|
status.HTTP_403_FORBIDDEN: {"description": "The caller is not an admin."},
|
|
},
|
|
)
|
|
def parse_apprise_url(
|
|
request: Request, payload: AppriseUrlPayload
|
|
) -> AppriseUrlFieldsSchema:
|
|
"""Read a service's own URL (a Discord webhook's) or an Apprise URL into its fields."""
|
|
assert_admin(request)
|
|
try:
|
|
service, fields = apprise_channel.fields_from_url(payload.url)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
|
) from exc
|
|
return AppriseUrlFieldsSchema(service=service.id, fields=fields)
|
|
|
|
|
|
@cache
|
|
def _apprise_catalog() -> list[AppriseServiceSchema]:
|
|
return [AppriseServiceSchema.from_service(s) for s in apprise_channel.services()]
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"",
|
|
[Scope.ME_WRITE],
|
|
status_code=status.HTTP_201_CREATED,
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": (
|
|
"The channel's target is missing or invalid, email is not set up on"
|
|
" the server, a caller who is not an admin asks for an Apprise"
|
|
" channel, or the caller already has the maximum number of channels."
|
|
)
|
|
},
|
|
status.HTTP_429_TOO_MANY_REQUESTS: {
|
|
"description": (
|
|
"A confirmation code went to the caller or to this address less than"
|
|
" a minute ago."
|
|
)
|
|
},
|
|
status.HTTP_502_BAD_GATEWAY: {
|
|
"description": "The mail server could not send the confirmation code."
|
|
},
|
|
},
|
|
)
|
|
async def create_notification_channel(
|
|
request: Request, payload: NotificationChannelCreatePayload
|
|
) -> NotificationChannelSchema:
|
|
"""Add a channel; an email address gets a code to confirm it with first."""
|
|
# What each type sends it to: a URL and secret, an address, or a service's fields.
|
|
target = payload.model_dump(exclude={"type", "name", "min_level", "topics"})
|
|
created = channels.create_channel(
|
|
request.user,
|
|
NotificationChannelType(payload.type),
|
|
payload.name,
|
|
payload.min_level,
|
|
payload.topics,
|
|
**target,
|
|
)
|
|
return NotificationChannelSchema.from_channel(await _as_http(created))
|
|
|
|
|
|
@protected_route(
|
|
router.patch,
|
|
"/{channel_id}",
|
|
[Scope.ME_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": (
|
|
"The new target is invalid, a new email address is given but email"
|
|
" is not set up on the server, a caller who is not an admin edits an"
|
|
" Apprise channel, or a webhook's URL changes to another origin and"
|
|
" the request does not send its secret again."
|
|
)
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no notification channel with this ID."
|
|
},
|
|
status.HTTP_429_TOO_MANY_REQUESTS: {
|
|
"description": (
|
|
"A confirmation code went to the caller or to this address less than"
|
|
" a minute ago."
|
|
)
|
|
},
|
|
status.HTTP_502_BAD_GATEWAY: {
|
|
"description": "The mail server could not send the confirmation code."
|
|
},
|
|
},
|
|
)
|
|
async def update_notification_channel(
|
|
request: Request,
|
|
channel_id: int,
|
|
payload: NotificationChannelUpdatePayload,
|
|
) -> NotificationChannelSchema:
|
|
"""Change a channel; a new email address has to be confirmed again."""
|
|
changes = {
|
|
field: value
|
|
for field, value in payload.model_dump(
|
|
include={"name", "enabled", "min_level"}
|
|
).items()
|
|
if value is not None
|
|
}
|
|
if "topics" in payload.model_fields_set:
|
|
changes["topics"] = payload.topics
|
|
|
|
updated = await _as_http(
|
|
channels.update_channel(
|
|
_get_or_404(channel_id, request.user),
|
|
request.user,
|
|
changes,
|
|
url=payload.url,
|
|
secret=payload.secret,
|
|
secret_given="secret" in payload.model_fields_set,
|
|
address=payload.address,
|
|
fields=payload.fields,
|
|
)
|
|
)
|
|
return NotificationChannelSchema.from_channel(updated)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{channel_id}",
|
|
[Scope.ME_WRITE],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no notification channel with this ID."
|
|
}
|
|
},
|
|
)
|
|
def delete_notification_channel(request: Request, channel_id: int) -> None:
|
|
"""Delete one of the caller's notification channels."""
|
|
if not db_notification_channel_handler.delete_channel(channel_id, request.user.id):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Notification channel not found",
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{channel_id}/test",
|
|
[Scope.ME_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "The channel's email address is not confirmed yet."
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no notification channel with this ID."
|
|
},
|
|
},
|
|
)
|
|
async def test_notification_channel(
|
|
request: Request, channel_id: int
|
|
) -> NotificationChannelTestResult:
|
|
"""Send a sample notification out on the channel right away."""
|
|
channel = _get_or_404(channel_id, request.user)
|
|
try:
|
|
error = await channels.send_sample(channel, request.user)
|
|
except ChannelError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
|
) from exc
|
|
return NotificationChannelTestResult(ok=error is None, error=error)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{channel_id}/confirm",
|
|
[Scope.ME_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": (
|
|
"The code is wrong or has expired, or the channel has had too many"
|
|
" wrong attempts."
|
|
)
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no notification channel with this ID."
|
|
},
|
|
},
|
|
)
|
|
async def confirm_notification_channel(
|
|
request: Request,
|
|
channel_id: int,
|
|
payload: NotificationChannelCodePayload,
|
|
) -> NotificationChannelSchema:
|
|
"""Confirm an email address with the code sent to it."""
|
|
channel = _get_or_404(channel_id, request.user)
|
|
try:
|
|
confirmed = await channels.confirm_channel(channel, request.user, payload.code)
|
|
except ChannelError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
|
|
) from exc
|
|
return NotificationChannelSchema.from_channel(confirmed)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{channel_id}/resend-code",
|
|
[Scope.ME_WRITE],
|
|
status_code=status.HTTP_204_NO_CONTENT,
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": (
|
|
"The channel is not an unconfirmed email channel, the channel has no"
|
|
" email address, or email is not set up on the server."
|
|
)
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "The caller has no notification channel with this ID."
|
|
},
|
|
status.HTTP_429_TOO_MANY_REQUESTS: {
|
|
"description": (
|
|
"A confirmation code went to the caller or to this address less than"
|
|
" a minute ago."
|
|
)
|
|
},
|
|
status.HTTP_502_BAD_GATEWAY: {
|
|
"description": "The mail server could not send the confirmation code."
|
|
},
|
|
},
|
|
)
|
|
async def resend_notification_channel_code(request: Request, channel_id: int) -> None:
|
|
"""Send a new confirmation code to the channel's email address."""
|
|
await _as_http(channels.resend_code(_get_or_404(channel_id, request.user)))
|