From 11f6b89dd0d5031b5bfaf797fcc53b8928690d91 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 6 Sep 2026 11:28:05 -0400 Subject: [PATCH 1/2] fix(auth): gate the export endpoints on platforms.write Both export endpoints write into the library -- gamelist.xml and metadata.pegasus.txt in the platform directory, plus media copied into the per-type folders -- but were gated on roms.read, so any Viewer or any roms.read client token could trigger a library write. Since #4368 those writes also merge the file already on disk, which makes a read scope an even poorer fit. platforms.write is the scope that already gates the sibling library configuration writes in endpoints/configs.py, including the PUT /config/scan that toggles the auto-export these endpoints mirror. No UI change: nothing calls exportGamelistXml/exportPegasus, and the generated frontend types carry no paths or scopes. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/export.py | 4 +-- backend/tests/endpoints/test_export.py | 47 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 backend/tests/endpoints/test_export.py diff --git a/backend/endpoints/export.py b/backend/endpoints/export.py index 362728dc5..1e36d55d7 100644 --- a/backend/endpoints/export.py +++ b/backend/endpoints/export.py @@ -18,7 +18,7 @@ router = APIRouter( ) -@protected_route(router.post, "/gamelist-xml", [Scope.ROMS_READ]) +@protected_route(router.post, "/gamelist-xml", [Scope.PLATFORMS_WRITE]) async def export_gamelist_xml( request: Request, platform_ids: Annotated[ @@ -71,7 +71,7 @@ async def export_gamelist_xml( ) from e -@protected_route(router.post, "/pegasus", [Scope.ROMS_READ]) +@protected_route(router.post, "/pegasus", [Scope.PLATFORMS_WRITE]) async def export_pegasus( request: Request, platform_ids: Annotated[ diff --git a/backend/tests/endpoints/test_export.py b/backend/tests/endpoints/test_export.py new file mode 100644 index 000000000..29630ad95 --- /dev/null +++ b/backend/tests/endpoints/test_export.py @@ -0,0 +1,47 @@ +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import status + +from utils.gamelist_exporter import GamelistExporter +from utils.pegasus_exporter import PegasusExporter + +EXPORTERS = { + "/api/export/gamelist-xml": GamelistExporter, + "/api/export/pegasus": PegasusExporter, +} + +with_endpoint = pytest.mark.parametrize("path", list(EXPORTERS)) + + +@with_endpoint +def test_export_rejects_viewer(client, viewer_access_token: str, path: str): + # Both endpoints write into the library, so reading ROMs is not enough. + response = client.post( + f"{path}?platform_ids=1", + headers={"Authorization": f"Bearer {viewer_access_token}"}, + ) + assert response.status_code == status.HTTP_403_FORBIDDEN + + +@with_endpoint +def test_export_rejects_anonymous(client, path: str): + response = client.post(f"{path}?platform_ids=1") + assert response.status_code == status.HTTP_401_UNAUTHORIZED + + +@with_endpoint +def test_export_allows_editor(client, editor_access_token: str, path: str): + with patch.object( + EXPORTERS[path], + "export_platform_to_file", + new_callable=AsyncMock, + return_value=True, + ) as export_mock: + response = client.post( + f"{path}?platform_ids=1", + headers={"Authorization": f"Bearer {editor_access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + export_mock.assert_awaited_once() From cca9f500f159c353733d0979aa63dc7d59be14cb Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 6 Sep 2026 11:40:00 -0400 Subject: [PATCH 2/2] fix(auth): mask hidden platforms from the export endpoints Both routes passed every caller-supplied platform_id straight to the exporter. A permission group can grant platforms.write while hiding individual platforms, so such a caller could export a platform hidden from them -- reading its metadata and rewriting its gamelist.xml or metadata.pegasus.txt. Resolve and check every platform up front, the way update_platform and delete_platform already do, so a rejected request writes nothing at all rather than failing part way through a batch. A missing platform 404s like a hidden one, so the response is not an oracle for whether the platform exists. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/export.py | 20 +++++++++ backend/tests/endpoints/test_export.py | 45 ++++++++++++++++--- .../endpoints/test_permissions_visibility.py | 25 +++++++++++ 3 files changed, 84 insertions(+), 6 deletions(-) diff --git a/backend/endpoints/export.py b/backend/endpoints/export.py index 1e36d55d7..d3e3dc34e 100644 --- a/backend/endpoints/export.py +++ b/backend/endpoints/export.py @@ -4,7 +4,10 @@ from fastapi import HTTPException, Query, Request, status from fastapi.responses import Response from decorators.auth import protected_route +from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException from handler.auth.constants import Scope +from handler.auth.dependencies import assert_platform_visible +from handler.database import db_platform_handler from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log @@ -18,6 +21,19 @@ router = APIRouter( ) +def _assert_platforms_exportable(request: Request, platform_ids: List[int]) -> None: + """Reject the whole request before anything is written to disk. + + A platform hidden from the caller 404s exactly like a missing one, so the + response never reveals that the platform exists. + """ + for platform_id in platform_ids: + platform = db_platform_handler.get_platform(platform_id) + if not platform: + raise PlatformNotFoundInDatabaseException(platform_id) + assert_platform_visible(request, platform) + + @protected_route(router.post, "/gamelist-xml", [Scope.PLATFORMS_WRITE]) async def export_gamelist_xml( request: Request, @@ -35,6 +51,8 @@ async def export_gamelist_xml( detail="At least one platform ID must be provided", ) + _assert_platforms_exportable(request, platform_ids) + try: exporter = GamelistExporter(local_export=local_export) files_written = [] @@ -88,6 +106,8 @@ async def export_pegasus( detail="At least one platform ID must be provided", ) + _assert_platforms_exportable(request, platform_ids) + try: exporter = PegasusExporter(local_export=local_export) files_written = [] diff --git a/backend/tests/endpoints/test_export.py b/backend/tests/endpoints/test_export.py index 29630ad95..a3b871dd2 100644 --- a/backend/tests/endpoints/test_export.py +++ b/backend/tests/endpoints/test_export.py @@ -15,23 +15,23 @@ with_endpoint = pytest.mark.parametrize("path", list(EXPORTERS)) @with_endpoint -def test_export_rejects_viewer(client, viewer_access_token: str, path: str): +def test_export_rejects_viewer(client, viewer_access_token: str, platform, path: str): # Both endpoints write into the library, so reading ROMs is not enough. response = client.post( - f"{path}?platform_ids=1", + f"{path}?platform_ids={platform.id}", headers={"Authorization": f"Bearer {viewer_access_token}"}, ) assert response.status_code == status.HTTP_403_FORBIDDEN @with_endpoint -def test_export_rejects_anonymous(client, path: str): - response = client.post(f"{path}?platform_ids=1") +def test_export_rejects_anonymous(client, platform, path: str): + response = client.post(f"{path}?platform_ids={platform.id}") assert response.status_code == status.HTTP_401_UNAUTHORIZED @with_endpoint -def test_export_allows_editor(client, editor_access_token: str, path: str): +def test_export_allows_editor(client, editor_access_token: str, platform, path: str): with patch.object( EXPORTERS[path], "export_platform_to_file", @@ -39,9 +39,42 @@ def test_export_allows_editor(client, editor_access_token: str, path: str): return_value=True, ) as export_mock: response = client.post( - f"{path}?platform_ids=1", + f"{path}?platform_ids={platform.id}", headers={"Authorization": f"Bearer {editor_access_token}"}, ) assert response.status_code == status.HTTP_200_OK export_mock.assert_awaited_once() + + +@with_endpoint +def test_export_unknown_platform_is_404(client, editor_access_token: str, path: str): + # Matches the 404 a hidden platform gets, so the response is not an oracle + # for whether the platform exists (see test_permissions_visibility). + with patch.object( + EXPORTERS[path], "export_platform_to_file", new_callable=AsyncMock + ) as export_mock: + response = client.post( + f"{path}?platform_ids=99999", + headers={"Authorization": f"Bearer {editor_access_token}"}, + ) + + assert response.status_code == status.HTTP_404_NOT_FOUND + export_mock.assert_not_awaited() + + +@with_endpoint +def test_export_rejects_batch_with_one_unknown_platform( + client, editor_access_token: str, platform, path: str +): + # The whole request is refused up front, so a partial batch never writes. + with patch.object( + EXPORTERS[path], "export_platform_to_file", new_callable=AsyncMock + ) as export_mock: + response = client.post( + f"{path}?platform_ids={platform.id}&platform_ids=99999", + headers={"Authorization": f"Bearer {editor_access_token}"}, + ) + + assert response.status_code == status.HTTP_404_NOT_FOUND + export_mock.assert_not_awaited() diff --git a/backend/tests/endpoints/test_permissions_visibility.py b/backend/tests/endpoints/test_permissions_visibility.py index 3a237e352..af8d98fe1 100644 --- a/backend/tests/endpoints/test_permissions_visibility.py +++ b/backend/tests/endpoints/test_permissions_visibility.py @@ -26,6 +26,8 @@ from models.permission import ( PermissionGroupGrant, ) from models.rom import Rom, RomFile, RomFileCategory +from utils.gamelist_exporter import GamelistExporter +from utils.pegasus_exporter import PegasusExporter def _auth(user): @@ -155,6 +157,29 @@ def test_physical_game_create_on_hidden_platform_is_404_masked( assert db_rom_handler.get_roms_scalar(platform_ids=[platform.id]) == [] +@pytest.mark.parametrize( + ("path", "exporter"), + [ + ("/api/export/gamelist-xml", GamelistExporter), + ("/api/export/pegasus", PegasusExporter), + ], +) +def test_export_of_hidden_platform_is_404_masked( + client, editor_user, platform, monkeypatch, path, exporter +): + # Editor holds platforms write, so the coarse gate passes. The hide must + # mask the export before it reads or rewrites the platform's metadata file. + _hide(PermEntity.PLATFORMS, platform.id, editor_user.id) + + async def _unreachable(*args, **kwargs): + raise AssertionError("exported a hidden platform") + + monkeypatch.setattr(exporter, "export_platform_to_file", _unreachable) + + resp = client.post(f"{path}?platform_ids={platform.id}", headers=_auth(editor_user)) + assert resp.status_code == status.HTTP_404_NOT_FOUND + + def test_hidden_rom_props_update_is_404_masked(client, viewer_user, rom): # ROMS_USER_WRITE is a self-service scope every user holds, so the coarse # gate passes; the hidden rom must still be masked, not confirmed.