From ef35ecaea996e5e7cd3f6ff8df1386c356fafeb7 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 4 Apr 2026 14:16:00 -0400 Subject: [PATCH] props rom updte endpoint --- backend/endpoints/roms/__init__.py | 27 +++++-------- backend/tests/endpoints/roms/test_rom.py | 16 ++++---- backend/tests/utils/test_validation.py | 49 ++++++++++++++++++++++++ backend/utils/validation.py | 32 ++++++++++++++-- frontend/src/services/api/rom.ts | 15 ++++---- 5 files changed, 104 insertions(+), 35 deletions(-) diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 622091cdf..97d24d486 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -164,19 +164,6 @@ class RomUserData(BaseModel): ) -class RomUserUpdatePayload(BaseModel): - data: RomUserData = Field( - default_factory=RomUserData, - description="Partial rom user data to update. Only provided fields will be updated.", - ) - update_last_played: bool = Field( - default=False, description="Set last played timestamp to now." - ) - remove_last_played: bool = Field( - default=False, description="Clear the last played timestamp." - ) - - async def parse_rom_update_form( request: Request, igdb_id: str | None = Form(default=None), @@ -1536,7 +1523,13 @@ async def delete_roms( async def update_rom_user( request: Request, id: Annotated[int, PathVar(description="Rom internal id.", ge=1)], - payload: Annotated[RomUserUpdatePayload, Body()], + data: Annotated[RomUserData, Body()], + update_last_played: Annotated[ + bool, Query(description="Set last played timestamp to now.") + ] = False, + remove_last_played: Annotated[ + bool, Query(description="Clear the last played timestamp.") + ] = False, ) -> RomUserSchema: """Update rom data associated to the current user.""" rom = db_rom_handler.get_rom(id) @@ -1548,11 +1541,11 @@ async def update_rom_user( id, request.user.id ) or db_rom_handler.add_rom_user(id, request.user.id) - cleaned_data = payload.data.model_dump(exclude_unset=True) + cleaned_data = data.model_dump(exclude_unset=True) - if payload.update_last_played: + if update_last_played: cleaned_data.update({"last_played": datetime.now(timezone.utc)}) - elif payload.remove_last_played: + elif remove_last_played: cleaned_data.update({"last_played": None}) rom_user = db_rom_handler.update_rom_user(db_rom_user.id, cleaned_data) diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index fc45acba4..13cac6403 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -261,13 +261,13 @@ def test_delete_roms_from_fs_nested( mock_remove_directory.assert_called_once() -def test_update_rom_user_props_with_data_envelope( +def test_update_rom_user_props_flat_payload( client: TestClient, access_token: str, rom: Rom ): response = client.put( f"/api/roms/{rom.id}/props", headers={"Authorization": f"Bearer {access_token}"}, - json={"data": {"backlogged": True, "rating": 7}}, + json={"backlogged": True, "rating": 7}, ) assert response.status_code == status.HTTP_200_OK @@ -283,7 +283,7 @@ def test_update_rom_user_props_partial_update( setup_response = client.put( f"/api/roms/{rom.id}/props", headers={"Authorization": f"Bearer {access_token}"}, - json={"data": {"backlogged": True, "rating": 5, "hidden": True}}, + json={"backlogged": True, "rating": 5, "hidden": True}, ) assert setup_response.status_code == status.HTTP_200_OK @@ -291,7 +291,7 @@ def test_update_rom_user_props_partial_update( response = client.put( f"/api/roms/{rom.id}/props", headers={"Authorization": f"Bearer {access_token}"}, - json={"data": {"rating": 9}}, + json={"rating": 9}, ) assert response.status_code == status.HTTP_200_OK @@ -305,17 +305,17 @@ def test_update_rom_user_props_last_played_flags( client: TestClient, access_token: str, rom: Rom ): mark_played_response = client.put( - f"/api/roms/{rom.id}/props", + f"/api/roms/{rom.id}/props?update_last_played=true", headers={"Authorization": f"Bearer {access_token}"}, - json={"data": {}, "update_last_played": True}, + json={}, ) assert mark_played_response.status_code == status.HTTP_200_OK assert mark_played_response.json()["last_played"] is not None clear_played_response = client.put( - f"/api/roms/{rom.id}/props", + f"/api/roms/{rom.id}/props?remove_last_played=true", headers={"Authorization": f"Bearer {access_token}"}, - json={"data": {}, "remove_last_played": True}, + json={}, ) assert clear_played_response.status_code == status.HTTP_200_OK assert clear_played_response.json()["last_played"] is None diff --git a/backend/tests/utils/test_validation.py b/backend/tests/utils/test_validation.py index 2e7a54802..69ffdb34a 100644 --- a/backend/tests/utils/test_validation.py +++ b/backend/tests/utils/test_validation.py @@ -342,6 +342,55 @@ class TestValidateUrlForHttpRequest: validate_url_for_http_request("http://server.localhost", "test_url") assert "internal domain names are not allowed" in exc_info.value.message + def test_invalid_non_standard_ip_representations(self): + """Test that non-standard IP representations are blocked (SSRF bypass vectors).""" + # Hexadecimal integer for 127.0.0.1 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://0x7f000001", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # Decimal integer for 127.0.0.1 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://2130706433", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # Shorthand dotted for 127.0.0.1 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://127.1", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # Hexadecimal integer for 10.0.0.1 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://0x0a000001", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # Decimal integer for 192.168.1.1 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://3232235777", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # Hexadecimal integer for 169.254.169.254 (cloud metadata) + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://0xa9fea9fe", "test_url") + assert ( + "cloud metadata service addresses are not allowed" in exc_info.value.message + ) + def test_invalid_missing_hostname(self): """Test that URLs without hostnames fail validation.""" with pytest.raises(ValidationError) as exc_info: diff --git a/backend/utils/validation.py b/backend/utils/validation.py index 1d55cb38d..20f541bea 100644 --- a/backend/utils/validation.py +++ b/backend/utils/validation.py @@ -1,5 +1,6 @@ import ipaddress import re +import socket from urllib.parse import urlparse from logger.logger import log @@ -202,8 +203,33 @@ def validate_url_for_http_request(url: str, field_name: str = "URL") -> None: log.error(f"SSRF prevention: {msg} - IP '{ip}'") raise ValidationError(msg, field_name) - except ValueError as e: - # Not a direct IP address, which is fine - it's a domain name + except ValueError: + # ipaddress.ip_address() only handles standard notation. HTTP clients + # also accept hex integers (0x7f000001), decimal integers (2130706433), + # shorthand dotted (127.1), and octal (0177.0.0.1). Use socket.inet_aton() + # which handles these non-standard IPv4 representations. + try: + packed = socket.inet_aton(hostname) + ip = ipaddress.IPv4Address(packed) + + if isinstance(ip, ipaddress.IPv4Address) and str(ip).startswith("169.254."): + msg = f"Invalid {field_name}: cloud metadata service addresses are not allowed" + log.error(f"SSRF prevention: {msg} - IP '{ip}'") + raise ValidationError(msg, field_name) + + if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved: + msg = f"Invalid {field_name}: private, internal, and reserved IP addresses are not allowed" + log.error(f"SSRF prevention: {msg} - IP '{ip}'") + raise ValidationError(msg, field_name) + + if ip.is_multicast: + msg = f"Invalid {field_name}: multicast addresses are not allowed" + log.error(f"SSRF prevention: {msg} - IP '{ip}'") + raise ValidationError(msg, field_name) + + except OSError: + pass # Not an IP address at all - fall through to domain name checks + # Additional checks for suspicious domain patterns hostname_lower = hostname.lower() @@ -212,4 +238,4 @@ def validate_url_for_http_request(url: str, field_name: str = "URL") -> None: if any(hostname_lower.endswith(tld) for tld in internal_tlds): msg = f"Invalid {field_name}: internal domain names are not allowed" log.error(f"SSRF prevention: {msg} - hostname '{hostname}'") - raise ValidationError(msg, field_name) from e + raise ValidationError(msg, field_name) diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index 583e9e389..c08dc50e1 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -5,7 +5,6 @@ import type { BulkOperationResponse, DetailedRomSchema, ManualMetadata, - RomUserUpdatePayload, RomUserSchema, SearchRomSchema, SimpleRomSchema, @@ -549,12 +548,14 @@ async function updateUserRomProps({ updateLastPlayed?: boolean; removeLastPlayed?: boolean; }) { - const payload: RomUserUpdatePayload = { - data: data, - update_last_played: updateLastPlayed, - remove_last_played: removeLastPlayed, - }; - return api.put(`/roms/${romId}/props`, payload); + const params = new URLSearchParams(); + if (updateLastPlayed) params.set("update_last_played", "true"); + if (removeLastPlayed) params.set("remove_last_played", "true"); + const query = params.toString(); + return api.put( + `/roms/${romId}/props${query ? `?${query}` : ""}`, + data, + ); } async function deleteRoms({