fix(metadata): guard every scene id parse against the int() digit limit

CPython's int() raises past 4300 digits. The bare-digit branch of
scene_id_or_none already caught that, but the URL parsers, the filename
tag extractors and the Pouet 302 Location parser all called int() on an
unbounded (\d+) capture, so a pasted URL or a scanned filename carrying a
long digit run surfaced as a 500.

Promote pouet_handler's private _int_or_none to utils.int_or_none, next
to valid_youtube_id, and route every scene id conversion through it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-31 21:23:49 -04:00
parent 287af99a98
commit 45c8a1057f
6 changed files with 72 additions and 29 deletions

View File

@@ -1,5 +1,7 @@
from typing import Any, Callable, Final
from utils import int_or_none
from .csdb_handler import CsdbHandler, csdb_id_from_url
from .demozoo_handler import DemozooHandler, demozoo_id_from_url
from .flashpoint_handler import FlashpointHandler
@@ -53,9 +55,6 @@ def scene_id_or_none(value: Any, kind: str) -> int | None:
text = str(value).strip()
if text.isdigit():
# isdigit() also accepts superscripts and other digits int() rejects.
try:
return int(text)
except ValueError:
return None
return int_or_none(text)
parser = _SCENE_ID_PARSERS.get(kind)
return parser(text) if parser else None

View File

@@ -18,7 +18,7 @@ from fastapi import HTTPException, status
from config import CSDB_API_ENABLED
from logger.logger import log
from utils import get_version
from utils import get_version, int_or_none
from utils.rate_limiter import RateLimiter
from .base_handler import BaseRom, MetadataHandler
@@ -55,7 +55,7 @@ class CsdbRom(BaseRom):
def extract_csdb_id_from_filename(fs_name: str) -> int | None:
match = CSDB_TAG_REGEX.search(fs_name)
if match:
return int(match.group(1))
return int_or_none(match.group(1))
return None
@@ -70,10 +70,10 @@ def csdb_id_from_url(url: str) -> int | None:
query = parse_qs(parsed.query)
raw = (query.get("id") or [""])[0]
if raw.isdigit():
return int(raw)
return int_or_none(raw)
parts = [p for p in parsed.path.split("/") if p]
if len(parts) >= 2 and parts[0] == "release" and parts[1].isdigit():
return int(parts[1])
return int_or_none(parts[1])
return None

View File

@@ -19,7 +19,7 @@ from fastapi import HTTPException, status
from config import DEMOZOO_API_ENABLED
from logger.logger import log
from utils import get_version, valid_youtube_id
from utils import get_version, int_or_none, valid_youtube_id
from utils.rate_limiter import RateLimiter
from .base_handler import BaseRom, MetadataHandler
@@ -76,7 +76,7 @@ def extract_demozoo_id_from_filename(fs_name: str) -> int | None:
"""Extract Demozoo ID from a filename tag like ``(demozoo-108)``."""
match = DEMOZOO_TAG_REGEX.search(fs_name)
if match:
return int(match.group(1))
return int_or_none(match.group(1))
return None
@@ -86,9 +86,9 @@ def demozoo_id_from_url(value: str) -> int | None:
if not text:
return None
if text.isdigit():
return int(text)
return int_or_none(text)
match = DEMOZOO_PROD_ID_RE.search(text)
return int(match.group(1)) if match else None
return int_or_none(match.group(1)) if match else None
def _youtube_id_from_url(url: str) -> str | None:
@@ -124,7 +124,7 @@ def _pouet_id_from_url(url: str) -> int | None:
digits += ch
else:
break
return int(digits) if digits else None
return int_or_none(digits) if digits else None
def http_url(value: Any) -> str | None:

View File

@@ -17,7 +17,7 @@ from fastapi import HTTPException, status
from config import POUET_API_ENABLED
from logger.logger import log
from utils import get_version
from utils import get_version, int_or_none
from utils.context import ctx_httpx_client
from utils.rate_limiter import RateLimiter
@@ -73,7 +73,7 @@ def extract_pouet_id_from_filename(fs_name: str) -> int | None:
"""Extract Pouët ID from a filename tag like ``(pouet-99)``."""
match = POUET_TAG_REGEX.search(fs_name)
if match:
return int(match.group(1))
return int_or_none(match.group(1))
return None
@@ -83,11 +83,11 @@ def pouet_id_from_location(location: str) -> int | None:
return None
match = POUET_WHICH_RE.search(location)
if match:
return int(match.group(1))
return int_or_none(match.group(1))
query = parse_qs(urlparse(location).query)
which = query.get("which") or query.get("WHICH")
if which and which[0].isdigit():
return int(which[0])
return int_or_none(which[0])
return None
@@ -98,13 +98,6 @@ def _float_or_none(value: Any) -> float | None:
return None
def _int_or_none(value: Any) -> int | None:
try:
return int(value) if value is not None and value != "" else None
except (TypeError, ValueError):
return None
_POUET_TYPE_LABELS: Final[dict[str, str]] = {
"demo": "Demo",
"64k": "64K Intro",
@@ -219,7 +212,7 @@ def production_to_rom(prod: dict[str, Any]) -> PouetRom:
demozoo_id = None
raw_dz = prod.get("demozoo")
if raw_dz not in (None, "", "0", 0):
demozoo_id = _int_or_none(raw_dz)
demozoo_id = int_or_none(raw_dz)
screenshots: list[str] = []
shot = http_url(str(prod.get("screenshot") or ""))
@@ -246,18 +239,18 @@ def production_to_rom(prod: dict[str, Any]) -> PouetRom:
if youtube_id is None:
youtube_id = _youtube_id_from_url(str(prod.get("download") or ""))
csdb = _int_or_none(prod.get("csdb"))
csdb = int_or_none(prod.get("csdb"))
if csdb:
_append_unique(download_urls, f"https://csdb.dk/release/?id={csdb}")
zxdemo = _int_or_none(prod.get("zxdemo"))
zxdemo = int_or_none(prod.get("zxdemo"))
if zxdemo:
_append_unique(download_urls, f"https://zxdemo.org/prod.php?id={zxdemo}")
year = str(prod.get("releaseDate") or "")[:4]
who = ", ".join(groups)
vote_avg = _float_or_none(prod.get("voteavg"))
pouet_rank = _int_or_none(prod.get("rank"))
pouet_cdc = _int_or_none(prod.get("cdc"))
pouet_rank = int_or_none(prod.get("rank"))
pouet_cdc = int_or_none(prod.get("cdc"))
pouet_url = POUET_PROD_PAGE.format(id=pouet_id)
demozoo_url = DEMOZOO_PROD_PAGE.format(id=demozoo_id) if demozoo_id else None

View File

@@ -1,8 +1,16 @@
"""scene_id_or_none accepts a bare scene id or a pasted production URL."""
from collections.abc import Callable
import pytest
from handler.metadata import scene_id_or_none
from handler.metadata.csdb_handler import extract_csdb_id_from_filename
from handler.metadata.demozoo_handler import extract_demozoo_id_from_filename
from handler.metadata.pouet_handler import (
extract_pouet_id_from_filename,
pouet_id_from_location,
)
KINDS = ["demozoo", "pouet", "csdb"]
@@ -40,3 +48,36 @@ def test_non_ascii_digit_is_none(kind: str) -> None:
def test_absurdly_long_digit_string_is_none(kind: str) -> None:
"""int() refuses to parse past CPython's 4300-digit limit."""
assert scene_id_or_none("9" * 4400, kind) is None
@pytest.mark.parametrize(
("template", "kind"),
[
("https://demozoo.org/productions/{id}/", "demozoo"),
("https://www.pouet.net/prod.php?which={id}", "pouet"),
("https://csdb.dk/release/?id={id}", "csdb"),
("https://csdb.dk/release/{id}", "csdb"),
],
)
def test_absurdly_long_digit_string_in_url_is_none(template: str, kind: str) -> None:
"""The URL branch must guard the digit limit the bare branch already guards."""
assert scene_id_or_none(template.format(id="9" * 4400), kind) is None
@pytest.mark.parametrize(
("extract", "tag"),
[
(extract_demozoo_id_from_filename, "demozoo"),
(extract_pouet_id_from_filename, "pouet"),
(extract_csdb_id_from_filename, "csdb"),
],
)
def test_absurdly_long_filename_tag_is_none(
extract: Callable[[str], int | None], tag: str
) -> None:
"""A scanned filename is untrusted input and reaches int() unauthenticated."""
assert extract(f"prod ({tag}-{'9' * 4400}).zip") is None
def test_absurdly_long_pouet_location_is_none() -> None:
assert pouet_id_from_location(f"/prod.php?which={'9' * 4400}") is None

View File

@@ -25,6 +25,16 @@ def is_valid_uuid(uuid_str: str) -> bool:
return False
def int_or_none(value: Any) -> int | None:
"""An int, or None when it is not one (``int()`` raises past 4300 digits)."""
if value is None or value == "":
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def valid_youtube_id(value: Any) -> str | None:
"""A video id, or None when it is not one."""
text = str(value or "")