mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 18:43:23 +01:00
fix(screenscraper): report rejected credentials instead of a bare 403
ScreenScraper answers a bad credential set with HTTP 403 and a body that says so, but the login-error check sat after raise_for_status(), so it could never match the case it was written for. The scan logged "403, message='Forbidden'", carried on, and saved every ROM without ScreenScraper metadata, with nothing anywhere naming the credentials. The body is now read before the status is raised, and a 403 raises a ScreenScraperCredentialsError that says which of the two credential sets was refused. The account endpoint is the only one that checks the account password, so a refusal there names SCREENSCRAPER_USER and SCREENSCRAPER_PASSWORD, and a refusal from a scraping endpoint can only be about the RomM developer credentials. That message does not name their variables: they are only semi-protected, and nothing should send an end user looking for them. ScreenScraper's own wording is carried through under both, because it cannot attribute the fault by itself: with a bad developer id, ssuserInfos.php still blames the account. That wording reaches the caller as well as the log, and the credentials travel in the query string, so it is masked with the regex the log formatter already uses. The refusal surfaces as a 403, matching the blacklisted-version case: both mean ScreenScraper refused RomM itself and both need an operator change, unlike the transient failures that map to 503. Never a 401, which the frontend reads as an expired session and acts on by returning the user to the login page. A refusal trips a breaker like the daily quota does: it is reported once and the remaining requests short-circuit rather than spending a round trip per ROM to be told the same thing. The scan-path lookups treat it like an exhausted quota, so a scan degrades to the other providers instead of failing outright. Manual searches still surface the error. The account check reports a refusal but never arms that breaker. ScreenScraper refuses a developer id it accepted a minute earlier while the scraping endpoints keep answering, so leaving the breaker armed cost a working scan all of its ScreenScraper metadata. Only the requests a scan actually needs can take the provider out. prime_account_limits() now warns whether the lookup raised or was swallowed into an empty response, which is what left a scan with no limits, no quota readout and no explanation. The HTTP 401 message gains the half of ScreenScraper's error table it was missing: the API is closed to non-members and inactive members, with server saturation given as the cause. Both attempts had diverging copies of the status ladder, so they now share one mapping. Fixes #4122 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import enum
|
||||
import http
|
||||
import json
|
||||
import re
|
||||
@@ -22,6 +23,7 @@ from config import (
|
||||
SCREENSCRAPER_PASSWORD,
|
||||
SCREENSCRAPER_USER,
|
||||
)
|
||||
from logger.formatter import redact_sensitive
|
||||
from logger.logger import log
|
||||
from utils import get_version
|
||||
from utils.context import ctx_aiohttp_session
|
||||
@@ -29,6 +31,19 @@ from utils.rate_limiter import ConcurrencyLimiter, RateLimiter
|
||||
|
||||
LOGIN_ERROR_CHECK: Final = "Erreur de login"
|
||||
|
||||
# ScreenScraper's error bodies are a single short line of plain text. Anything
|
||||
# longer, or marked up, is a page rather than a message.
|
||||
SS_MAX_ERROR_MESSAGE: Final[int] = 200
|
||||
|
||||
# The one endpoint that checks the account password. The scraping endpoints
|
||||
# authorize on the developer credentials alone and never look at it.
|
||||
SS_ACCOUNT_ENDPOINT: Final = "ssuserInfos.php"
|
||||
|
||||
# ScreenScraper names the developer credentials in the refusal itself, but only
|
||||
# from the scraping endpoints; the account endpoint blames the account whichever
|
||||
# set is actually at fault.
|
||||
SS_DEVELOPER_ERROR_CHECK: Final = "développeur"
|
||||
|
||||
# ScreenScraper occasionally returns malformed JSON with unescaped backslashes in
|
||||
# text fields (e.g. game synopses), which the strict parser rejects with
|
||||
# "Invalid \escape" and discards the whole response. Match any backslash that is
|
||||
@@ -90,6 +105,43 @@ class ScreenScraperRateLimitError(HTTPException):
|
||||
)
|
||||
|
||||
|
||||
class SSCredentialSet(enum.StrEnum):
|
||||
"""Whose credentials ScreenScraper refused."""
|
||||
|
||||
USER = "user"
|
||||
DEVELOPER = "developer"
|
||||
|
||||
|
||||
CREDENTIAL_DETAILS: Final[dict[SSCredentialSet, str]] = {
|
||||
SSCredentialSet.USER: (
|
||||
"ScreenScraper rejected your user account credentials. Check "
|
||||
"SCREENSCRAPER_USER and SCREENSCRAPER_PASSWORD."
|
||||
),
|
||||
SSCredentialSet.DEVELOPER: "ScreenScraper rejected the RomM developer credentials.",
|
||||
}
|
||||
|
||||
|
||||
class ScreenScraperCredentialsError(HTTPException):
|
||||
"""Raised when ScreenScraper refuses one of the two credential sets.
|
||||
|
||||
Nothing clears this within a scan: the fix is a configuration change, and the
|
||||
credentials are read at startup.
|
||||
|
||||
Reported the way a blacklisted application version is, the other refusal an
|
||||
operator has to act on. Never as a 401: it is RomM's credentials the provider
|
||||
refused, not the caller's, and the frontend reads a 401 as an expired session
|
||||
and sends the user back to the login page.
|
||||
"""
|
||||
|
||||
def __init__(self, credential_set: SSCredentialSet, message: str = "") -> None:
|
||||
self.credential_set = credential_set
|
||||
detail = CREDENTIAL_DETAILS[credential_set]
|
||||
if message:
|
||||
detail = f"{detail} ScreenScraper said: {message}"
|
||||
|
||||
super().__init__(status_code=status.HTTP_403_FORBIDDEN, detail=detail)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SSAccountLimits:
|
||||
"""The per-account allowances ScreenScraper reports on every response."""
|
||||
@@ -152,6 +204,12 @@ class _ScanState:
|
||||
# short-circuit instead of hammering a dead quota.
|
||||
daily_quota_exhausted: bool = False
|
||||
|
||||
# A refused credential set (HTTP 403) is refused for every request that
|
||||
# follows, so it trips a breaker of its own rather than costing a round trip
|
||||
# per ROM to be told the same thing. Holds which set, so the requests that
|
||||
# short-circuit report the same thing the first one did.
|
||||
credentials_rejected: SSCredentialSet | None = None
|
||||
|
||||
def reset(self) -> None:
|
||||
for f in fields(self):
|
||||
setattr(self, f.name, f.default)
|
||||
@@ -181,6 +239,89 @@ def _trip_daily_quota(reason: str) -> None:
|
||||
_state.daily_quota_exhausted = True
|
||||
|
||||
|
||||
def _error_message(body: str) -> str:
|
||||
"""Condense a ScreenScraper error body into a single reportable line.
|
||||
|
||||
The reply reaches the caller as well as the log, and the credentials travel
|
||||
in the query string, so anything credential-shaped is masked the way the log
|
||||
formatter masks it.
|
||||
"""
|
||||
message = " ".join(body.split())
|
||||
if message.startswith("<"):
|
||||
return ""
|
||||
|
||||
return redact_sensitive(message[:SS_MAX_ERROR_MESSAGE])
|
||||
|
||||
|
||||
def _credential_set(url: str, message: str) -> SSCredentialSet:
|
||||
"""Work out which credential set a refusal is about.
|
||||
|
||||
ScreenScraper says so itself when a scraping endpoint refuses. When it does
|
||||
not, the endpoint settles it: only the account endpoint checks the account
|
||||
password, so a scraping endpoint can only be refusing the developer set.
|
||||
"""
|
||||
if SS_DEVELOPER_ERROR_CHECK in message.lower():
|
||||
return SSCredentialSet.DEVELOPER
|
||||
|
||||
if SS_ACCOUNT_ENDPOINT in url:
|
||||
return SSCredentialSet.USER
|
||||
|
||||
return SSCredentialSet.DEVELOPER
|
||||
|
||||
|
||||
def _reject_credentials(url: str, message: str = "") -> ScreenScraperCredentialsError:
|
||||
"""Trip the credentials breaker, reporting the cause once."""
|
||||
error = ScreenScraperCredentialsError(_credential_set(url, message), message)
|
||||
if _state.credentials_rejected != error.credential_set:
|
||||
log.error(error.detail)
|
||||
_state.credentials_rejected = error.credential_set
|
||||
|
||||
return error
|
||||
|
||||
|
||||
def _handle_client_error(url: str, err: aiohttp.ClientResponseError) -> dict:
|
||||
"""Map one of ScreenScraper's documented statuses onto a clear error.
|
||||
|
||||
Returns an empty response for the ones a scan can carry on through, and
|
||||
raises for the ones a caller has to hear about.
|
||||
"""
|
||||
if err.status == http.HTTPStatus.FORBIDDEN:
|
||||
raise _reject_credentials(url) from err
|
||||
elif err.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
# Both halves come from ScreenScraper's own error table, which gives the
|
||||
# closure as the description and the saturation as its cause.
|
||||
log.warning(
|
||||
"ScreenScraper closed the API to non-members and inactive members; "
|
||||
"it gives server saturation (CPU >60%) as the cause"
|
||||
)
|
||||
return {}
|
||||
elif err.status == 423:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="ScreenScraper API is currently offline.",
|
||||
) from err
|
||||
elif err.status == 426:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="ScreenScraper has blacklisted this application version. Please update RomM.",
|
||||
) from err
|
||||
elif err.status == 430:
|
||||
_trip_daily_quota("daily scrape quota exhausted")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily scrape quota exhausted. It resets at midnight CET.",
|
||||
) from err
|
||||
elif err.status == 431:
|
||||
_trip_daily_quota("daily unrecognized-ROM quota exhausted")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily unrecognized-ROM quota exhausted. It resets at midnight CET.",
|
||||
) from err
|
||||
|
||||
log.error(err)
|
||||
return {}
|
||||
|
||||
|
||||
def reset_scan_state() -> None:
|
||||
"""Clear the per-scan ScreenScraper state at the start of a scan.
|
||||
|
||||
@@ -405,10 +546,25 @@ async def prime_account_limits() -> SSAccountLimits | None:
|
||||
|
||||
try:
|
||||
await ScreenScraperService().get_user_info()
|
||||
except ScreenScraperCredentialsError:
|
||||
# The check reports, but it never takes the provider out: ScreenScraper
|
||||
# refuses a developer id it accepted a minute earlier, and the scraping
|
||||
# endpoints keep answering through it. The breaker is left to the
|
||||
# requests a scan actually needs.
|
||||
_state.credentials_rejected = None
|
||||
# Already reported in full, so say only why no quota follows.
|
||||
reason = "credentials rejected"
|
||||
except HTTPException as exc:
|
||||
log.warning("ScreenScraper: could not read the account limits (%s)", exc.detail)
|
||||
reason = str(exc.detail)
|
||||
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||
log.warning("ScreenScraper: could not read the account limits (%s)", exc)
|
||||
reason = str(exc)
|
||||
else:
|
||||
# Several errors are swallowed into an empty response rather than raised,
|
||||
# which used to leave a scan with no limits and nothing said about it.
|
||||
reason = "" if _state.account_limits else "no account information came back"
|
||||
|
||||
if reason:
|
||||
log.warning("ScreenScraper: could not read the account limits (%s)", reason)
|
||||
|
||||
return _state.account_limits
|
||||
|
||||
@@ -442,6 +598,44 @@ class ScreenScraperService:
|
||||
) -> None:
|
||||
self.url = yarl.URL(base_url or "https://api.screenscraper.fr/api2")
|
||||
|
||||
async def _attempt(self, url: str, request_timeout: int) -> dict:
|
||||
"""Make one request, and read the account allowances riding along on it.
|
||||
|
||||
A refusal explains itself in the body, so the body is read before the
|
||||
status is raised: a 403 would otherwise abort the attempt with a bare
|
||||
"Forbidden" and lose the one line that says what is wrong.
|
||||
"""
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
|
||||
async with _concurrency_limiter:
|
||||
await _rate_limiter.acquire()
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
headers={"user-agent": f"RomM/{get_version()}"},
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res_text = await res.text()
|
||||
if LOGIN_ERROR_CHECK in res_text:
|
||||
raise _reject_credentials(url, _error_message(res_text))
|
||||
|
||||
try:
|
||||
res.raise_for_status()
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == http.HTTPStatus.FORBIDDEN:
|
||||
raise _reject_credentials(url, _error_message(res_text)) from err
|
||||
raise
|
||||
|
||||
data = await res.json(loads=_loads_lenient)
|
||||
|
||||
_update_account_limits(data)
|
||||
return data
|
||||
|
||||
async def _request(self, url: str, request_timeout: int = 120) -> dict:
|
||||
# Daily quota already exhausted earlier in this scan: skip the request but
|
||||
# still raise the quota error so callers (e.g. manual search) surface a
|
||||
@@ -453,32 +647,13 @@ class ScreenScraperService:
|
||||
detail="ScreenScraper daily quota exhausted. It resets at midnight CET.",
|
||||
)
|
||||
|
||||
aiohttp_session = ctx_aiohttp_session.get()
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
# Credentials already refused: the answer will not change until they are
|
||||
# corrected, which takes a restart to pick up.
|
||||
if _state.credentials_rejected:
|
||||
raise ScreenScraperCredentialsError(_state.credentials_rejected)
|
||||
|
||||
try:
|
||||
async with _concurrency_limiter:
|
||||
await _rate_limiter.acquire()
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
headers={"user-agent": f"RomM/{get_version()}"},
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
res_text = await res.text()
|
||||
if LOGIN_ERROR_CHECK in res_text:
|
||||
log.error("Invalid ScreenScraper credentials")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid ScreenScraper credentials",
|
||||
)
|
||||
data = await res.json(loads=_loads_lenient)
|
||||
_update_account_limits(data)
|
||||
return data
|
||||
return await self._attempt(url, request_timeout)
|
||||
except aiohttp.ServerTimeoutError:
|
||||
# Retry the request once if it times out
|
||||
pass
|
||||
@@ -491,105 +666,28 @@ class ScreenScraperService:
|
||||
detail="Can't connect to ScreenScraper, check your internet connection",
|
||||
) from exc
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
log.warning("ScreenScraper: rate limit hit, retrying after 2s")
|
||||
await asyncio.sleep(2)
|
||||
elif err.status == 426:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="ScreenScraper has blacklisted this application version. Please update RomM.",
|
||||
) from err
|
||||
elif err.status == 430:
|
||||
_trip_daily_quota("daily scrape quota exhausted")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily scrape quota exhausted. It resets at midnight CET.",
|
||||
) from err
|
||||
elif err.status == 431:
|
||||
_trip_daily_quota("daily unrecognized-ROM quota exhausted")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily unrecognized-ROM quota exhausted. It resets at midnight CET.",
|
||||
) from err
|
||||
elif err.status == 423:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="ScreenScraper API is currently offline.",
|
||||
) from err
|
||||
elif err.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
log.warning(
|
||||
"ScreenScraper API is temporarily unavailable (server CPU >60%)"
|
||||
)
|
||||
return {}
|
||||
else:
|
||||
log.error(err)
|
||||
return {}
|
||||
if err.status != http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
return _handle_client_error(url, err)
|
||||
|
||||
log.warning("ScreenScraper: rate limit hit, retrying after 2s")
|
||||
await asyncio.sleep(2)
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
log.debug(
|
||||
"API request: URL=%s, Timeout=%s",
|
||||
url,
|
||||
request_timeout,
|
||||
)
|
||||
async with _concurrency_limiter:
|
||||
await _rate_limiter.acquire()
|
||||
res = await aiohttp_session.get(
|
||||
url,
|
||||
headers={"user-agent": f"RomM/{get_version()}"},
|
||||
middlewares=(auth_middleware,),
|
||||
timeout=ClientTimeout(total=request_timeout),
|
||||
)
|
||||
res.raise_for_status()
|
||||
res_text = await res.text()
|
||||
if LOGIN_ERROR_CHECK in res_text:
|
||||
log.error("Invalid ScreenScraper credentials")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid ScreenScraper credentials",
|
||||
)
|
||||
data = await res.json(loads=_loads_lenient)
|
||||
_update_account_limits(data)
|
||||
return data
|
||||
except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as err:
|
||||
if isinstance(err, aiohttp.ClientResponseError):
|
||||
if err.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Refused twice in a row: the pacing is behind the account's
|
||||
# per-minute budget. Surface it so the ROM is reported as
|
||||
# skipped instead of quietly saved without our metadata.
|
||||
raise ScreenScraperRateLimitError() from err
|
||||
elif err.status == http.HTTPStatus.UNAUTHORIZED:
|
||||
log.warning(
|
||||
"ScreenScraper API is temporarily unavailable (server CPU >60%)"
|
||||
)
|
||||
return {}
|
||||
elif err.status == 426:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="ScreenScraper has blacklisted this application version. Please update RomM.",
|
||||
) from err
|
||||
elif err.status == 430:
|
||||
_trip_daily_quota("daily scrape quota exhausted")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily scrape quota exhausted. It resets at midnight CET.",
|
||||
) from err
|
||||
elif err.status == 431:
|
||||
_trip_daily_quota("daily unrecognized-ROM quota exhausted")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="ScreenScraper daily unrecognized-ROM quota exhausted. It resets at midnight CET.",
|
||||
) from err
|
||||
elif err.status == 423:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="ScreenScraper API is currently offline.",
|
||||
) from err
|
||||
|
||||
return await self._attempt(url, request_timeout)
|
||||
except aiohttp.ServerTimeoutError as err:
|
||||
log.error(err)
|
||||
return {}
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == http.HTTPStatus.TOO_MANY_REQUESTS:
|
||||
# Refused twice in a row: the pacing is behind the account's
|
||||
# per-minute budget. Surface it so the ROM is reported as
|
||||
# skipped instead of quietly saved without our metadata.
|
||||
raise ScreenScraperRateLimitError() from err
|
||||
|
||||
return _handle_client_error(url, err)
|
||||
except json.JSONDecodeError as exc:
|
||||
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
|
||||
return {}
|
||||
|
||||
@@ -9,6 +9,7 @@ from fastapi import HTTPException, status
|
||||
from unidecode import unidecode as uc
|
||||
|
||||
from adapters.services.screenscraper import (
|
||||
ScreenScraperCredentialsError,
|
||||
ScreenScraperRateLimitError,
|
||||
ScreenScraperService,
|
||||
get_account_limits,
|
||||
@@ -250,6 +251,17 @@ def _is_daily_quota_error(exc: HTTPException) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _is_provider_exhausted(exc: HTTPException) -> bool:
|
||||
"""True for the errors that take ScreenScraper out for the rest of the scan.
|
||||
|
||||
Both an exhausted daily quota and a refused credential set trip a breaker in
|
||||
the service, so the remaining ROMs short-circuit. The scan carries on with
|
||||
the other providers rather than failing over a provider that has already said
|
||||
everything it is going to say.
|
||||
"""
|
||||
return _is_daily_quota_error(exc) or isinstance(exc, ScreenScraperCredentialsError)
|
||||
|
||||
|
||||
def _is_notgame(game: SSGame) -> bool:
|
||||
if game.get("notgame") == "true":
|
||||
return True
|
||||
@@ -842,9 +854,9 @@ class SSHandler(MetadataHandler):
|
||||
rom_type=_get_rom_type(first_file),
|
||||
)
|
||||
except HTTPException as exc:
|
||||
# Daily quota exhausted: skip ScreenScraper for this ROM so the scan
|
||||
# falls back to the other providers.
|
||||
if not _is_daily_quota_error(exc):
|
||||
# Quota exhausted or credentials refused: skip ScreenScraper for this
|
||||
# ROM so the scan falls back to the other providers.
|
||||
if not _is_provider_exhausted(exc):
|
||||
raise
|
||||
return SSRom(ss_id=None), False
|
||||
if not res:
|
||||
@@ -968,8 +980,9 @@ class SSHandler(MetadataHandler):
|
||||
terms[-1], platform_ss_id, split_game_name=True
|
||||
)
|
||||
except HTTPException as exc:
|
||||
# Daily quota exhausted: fall back to the name-only match (if any).
|
||||
if not _is_daily_quota_error(exc):
|
||||
# Quota exhausted or credentials refused: fall back to the name-only
|
||||
# match (if any).
|
||||
if not _is_provider_exhausted(exc):
|
||||
raise
|
||||
return fallback_rom
|
||||
|
||||
@@ -985,8 +998,9 @@ class SSHandler(MetadataHandler):
|
||||
try:
|
||||
res = await self.ss_service.get_game_info(game_id=ss_id)
|
||||
except HTTPException as exc:
|
||||
# Daily quota exhausted: return an empty match rather than failing.
|
||||
if not _is_daily_quota_error(exc):
|
||||
# Quota exhausted or credentials refused: return an empty match rather
|
||||
# than failing.
|
||||
if not _is_provider_exhausted(exc):
|
||||
raise
|
||||
return SSRom(ss_id=None)
|
||||
if not res:
|
||||
|
||||
@@ -15,8 +15,10 @@ from adapters.services.screenscraper import (
|
||||
SS_DEFAULT_MEDIA_TIMEOUT,
|
||||
SS_MAX_MEDIA_TIMEOUT,
|
||||
SS_UNPACED_REQUESTS_PER_SECOND,
|
||||
ScreenScraperCredentialsError,
|
||||
ScreenScraperRateLimitError,
|
||||
ScreenScraperService,
|
||||
SSCredentialSet,
|
||||
_loads_lenient,
|
||||
auth_middleware,
|
||||
get_account_limits,
|
||||
@@ -36,6 +38,13 @@ INVALID_SYSTEM_ID = 999999
|
||||
# Fast enough that the module's pacing never adds real sleeps to a test.
|
||||
UNTHROTTLED_RATE = 10_000
|
||||
|
||||
# What ScreenScraper answers a rejected credential set with, verbatim. The
|
||||
# account endpoint blames the account whichever set is at fault; only a
|
||||
# scraping endpoint names the developer credentials.
|
||||
SS_LOGIN_ERROR_BODY = "Erreur de login : Vérifier les identifiants utilisateurs !"
|
||||
SS_DEV_ERROR_BODY = "Erreur de login : Vérifier vos identifiants développeur !"
|
||||
ACCOUNT_URL = "https://api.screenscraper.fr/api2/ssuserInfos.php"
|
||||
|
||||
|
||||
def _rendered(mock_call) -> str:
|
||||
"""Render a lazily-formatted log call into the message it would emit."""
|
||||
@@ -278,8 +287,8 @@ class TestScreenScraperServiceUnit:
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
assert "Invalid ScreenScraper credentials" in exc_info.value.detail
|
||||
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert "RomM developer credentials" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_connection_error(self, service):
|
||||
@@ -1217,11 +1226,255 @@ class TestScreenScraperServiceEdgeCases:
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
assert "Invalid ScreenScraper credentials" in exc_info.value.detail
|
||||
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert "RomM developer credentials" in exc_info.value.detail
|
||||
assert mock_session.get.call_count == 2
|
||||
|
||||
|
||||
class TestCredentialErrors:
|
||||
"""ScreenScraper refuses a bad credential set with HTTP 403. RomM has to say
|
||||
which set, rather than the bare "403, message='Forbidden'" that sends users
|
||||
looking at their quota.
|
||||
|
||||
Only the account endpoint checks the account password, so a refusal from a
|
||||
scraping endpoint is always about RomM's own credentials, whatever the body
|
||||
happens to say."""
|
||||
|
||||
@pytest.fixture
|
||||
def service(self):
|
||||
return ScreenScraperService()
|
||||
|
||||
def _forbidden_response(self, body: str = SS_LOGIN_ERROR_BODY) -> MagicMock:
|
||||
"""A response whose body carries the login error, as a 403 does."""
|
||||
response = MagicMock()
|
||||
response.text = AsyncMock(return_value=body)
|
||||
response.json = AsyncMock(return_value={})
|
||||
response.raise_for_status.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(),
|
||||
history=(),
|
||||
status=http.HTTPStatus.FORBIDDEN,
|
||||
message="Forbidden",
|
||||
)
|
||||
return response
|
||||
|
||||
def _session(self, *responses) -> tuple[AsyncMock, MagicMock]:
|
||||
session = AsyncMock()
|
||||
if len(responses) == 1:
|
||||
session.get.return_value = responses[0]
|
||||
else:
|
||||
session.get.side_effect = list(responses)
|
||||
|
||||
context = MagicMock()
|
||||
context.get.return_value = session
|
||||
return session, context
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_account_endpoint_reports_the_account_sign_in(self, service):
|
||||
_, context = self._session(self._forbidden_response())
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request(ACCOUNT_URL)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert exc_info.value.credential_set is SSCredentialSet.USER
|
||||
assert "SCREENSCRAPER_USER" in exc_info.value.detail
|
||||
assert "SCREENSCRAPER_PASSWORD" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_scraping_endpoint_reports_romms_own_credentials(self, service):
|
||||
_, context = self._session(self._forbidden_response(SS_DEV_ERROR_BODY))
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.credential_set is SSCredentialSet.DEVELOPER
|
||||
assert "RomM developer credentials" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_developer_credentials_are_never_named(self, service):
|
||||
"""Their values are only semi-protected, so nothing sends an end user
|
||||
looking for them."""
|
||||
_, context = self._session(self._forbidden_response(SS_DEV_ERROR_BODY))
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert "SCREENSCRAPER_DEV_ID" not in exc_info.value.detail
|
||||
assert "SCREENSCRAPER_DEV_PASSWORD" not in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_scraping_refusal_is_not_blamed_on_the_account(self, service):
|
||||
"""ScreenScraper says "utilisateurs" from endpoints that never check the
|
||||
account password, so the endpoint settles it rather than the wording."""
|
||||
_, context = self._session(self._forbidden_response())
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert exc_info.value.credential_set is SSCredentialSet.DEVELOPER
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_body_is_read_before_the_status_is_raised(self, service):
|
||||
"""The regression: the login-error check sat after raise_for_status(), so
|
||||
it could never match the 403 it was written for."""
|
||||
response = self._forbidden_response()
|
||||
_, context = self._session(response)
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request(ACCOUNT_URL)
|
||||
|
||||
response.text.assert_awaited()
|
||||
# ScreenScraper's own wording, carried through under RomM's summary.
|
||||
assert "identifiants utilisateurs" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_credentials_are_masked_in_the_reported_message(self, service):
|
||||
"""The message reaches the caller, and the credentials ride in the query
|
||||
string ScreenScraper is free to quote back."""
|
||||
_, context = self._session(
|
||||
self._forbidden_response(
|
||||
"Erreur de login : ssid=user1&sspassword=hunter2&devpassword=s3cret"
|
||||
)
|
||||
)
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert "hunter2" not in exc_info.value.detail
|
||||
assert "s3cret" not in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_forbidden_without_a_body_still_names_a_set(self, service):
|
||||
_, context = self._session(self._forbidden_response(""))
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
|
||||
await service._request(ACCOUNT_URL)
|
||||
|
||||
assert "SCREENSCRAPER_USER" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rejected_credentials_are_not_retried(self, service):
|
||||
"""Nothing about a wrong password clears on a second attempt."""
|
||||
session, context = self._session(self._forbidden_response())
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert session.get.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_forbidden_on_the_retry_attempt_is_reported(self, service):
|
||||
session, context = self._session(
|
||||
aiohttp.ServerTimeoutError("Timeout"), self._forbidden_response()
|
||||
)
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert session.get.call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_later_requests_short_circuit(self, service):
|
||||
"""Every remaining ROM would be refused the same way, so stop asking."""
|
||||
session, context = self._session(self._forbidden_response())
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
assert session.get.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_failure_is_logged_once(self, service, monkeypatch):
|
||||
mock_log = MagicMock()
|
||||
monkeypatch.setattr(ss_module, "log", mock_log)
|
||||
_, context = self._session(self._forbidden_response())
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
for _ in range(2):
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await service._request(
|
||||
"https://api.screenscraper.fr/api2/jeuInfos.php"
|
||||
)
|
||||
|
||||
assert mock_log.error.call_count == 1
|
||||
assert "RomM developer credentials" in _rendered(mock_log.error.call_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_new_scan_asks_again(self, service):
|
||||
"""Credentials are read at startup, so a restart is what clears this."""
|
||||
_, context = self._session(self._forbidden_response())
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
|
||||
reset_scan_state()
|
||||
|
||||
ok_response = MagicMock()
|
||||
ok_response.text = AsyncMock(return_value="{}")
|
||||
ok_response.json = AsyncMock(return_value={"response": {}})
|
||||
ok_response.raise_for_status.return_value = None
|
||||
session, context = self._session(ok_response)
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
assert await service._request(
|
||||
"https://api.screenscraper.fr/api2/jeuInfos.php"
|
||||
) == {"response": {}}
|
||||
|
||||
session.get.assert_called_once()
|
||||
|
||||
|
||||
class TestApiClosedForAccount:
|
||||
"""ScreenScraper's error table gives HTTP 401 two halves: the description is
|
||||
"API fermé pour les non membres ou les membres inactifs" and the cause is
|
||||
"Le Serveur est saturé (utilisation CPU>60%)". Reporting either one alone
|
||||
sends the reader looking in the wrong place."""
|
||||
|
||||
@pytest.fixture
|
||||
def service(self):
|
||||
return ScreenScraperService()
|
||||
|
||||
def _unauthorized_session(self) -> MagicMock:
|
||||
session = AsyncMock()
|
||||
session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(),
|
||||
history=(),
|
||||
status=http.HTTPStatus.UNAUTHORIZED,
|
||||
)
|
||||
context = MagicMock()
|
||||
context.get.return_value = session
|
||||
return context
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unauthorized_describes_a_closed_account(self, service, monkeypatch):
|
||||
mock_log = MagicMock()
|
||||
monkeypatch.setattr(ss_module, "log", mock_log)
|
||||
|
||||
with patch(
|
||||
"adapters.services.screenscraper.ctx_aiohttp_session",
|
||||
self._unauthorized_session(),
|
||||
):
|
||||
assert (
|
||||
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
|
||||
== {}
|
||||
)
|
||||
|
||||
messages = [_rendered(call).lower() for call in mock_log.warning.call_args_list]
|
||||
assert any("inactive" in message and "cpu" in message for message in messages)
|
||||
|
||||
|
||||
class TestLoadsLenient:
|
||||
"""Test tolerant parsing of ScreenScraper's occasionally malformed JSON."""
|
||||
|
||||
@@ -1472,6 +1725,88 @@ class TestPrimingAccountLimits:
|
||||
|
||||
assert mock_log.warning.called
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_priming_warns_when_the_lookup_answers_nothing(self, monkeypatch):
|
||||
"""The errors that are swallowed into an empty response left the scan with
|
||||
no limits and no warning: complete silence."""
|
||||
mock_log = MagicMock()
|
||||
monkeypatch.setattr(ss_module, "log", mock_log)
|
||||
|
||||
session = AsyncMock()
|
||||
session.get.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(),
|
||||
history=(),
|
||||
status=http.HTTPStatus.BAD_REQUEST,
|
||||
)
|
||||
context = MagicMock()
|
||||
context.get.return_value = session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
assert await prime_account_limits() is None
|
||||
|
||||
assert mock_log.warning.called
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_priming_reports_rejected_credentials(self, monkeypatch):
|
||||
mock_log = MagicMock()
|
||||
monkeypatch.setattr(ss_module, "log", mock_log)
|
||||
|
||||
response = MagicMock()
|
||||
response.text = AsyncMock(return_value=SS_LOGIN_ERROR_BODY)
|
||||
response.json = AsyncMock(return_value={})
|
||||
response.raise_for_status.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(),
|
||||
history=(),
|
||||
status=http.HTTPStatus.FORBIDDEN,
|
||||
)
|
||||
session = AsyncMock()
|
||||
session.get.return_value = response
|
||||
context = MagicMock()
|
||||
context.get.return_value = session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
assert await prime_account_limits() is None
|
||||
|
||||
# The full explanation is the error the service already logged; the
|
||||
# warning only has to say why no quota readout follows.
|
||||
assert "SCREENSCRAPER_USER" in _rendered(mock_log.error.call_args)
|
||||
messages = [_rendered(call) for call in mock_log.warning.call_args_list]
|
||||
assert any("credentials" in message for message in messages)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_priming_never_takes_the_provider_out(self):
|
||||
"""ScreenScraper refuses a developer id it accepted a minute earlier while
|
||||
the scraping endpoints keep answering, so a scan whose scraping still works
|
||||
must not lose it to the account check."""
|
||||
response = MagicMock()
|
||||
response.text = AsyncMock(return_value=SS_LOGIN_ERROR_BODY)
|
||||
response.json = AsyncMock(return_value={})
|
||||
response.raise_for_status.side_effect = aiohttp.ClientResponseError(
|
||||
request_info=MagicMock(),
|
||||
history=(),
|
||||
status=http.HTTPStatus.FORBIDDEN,
|
||||
)
|
||||
session = AsyncMock()
|
||||
session.get.return_value = response
|
||||
context = MagicMock()
|
||||
context.get.return_value = session
|
||||
|
||||
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
|
||||
await prime_account_limits()
|
||||
|
||||
assert ss_module._state.credentials_rejected is None
|
||||
|
||||
# The next request is made rather than short-circuited, and it is the
|
||||
# one that arms the breaker.
|
||||
session.get.reset_mock()
|
||||
with pytest.raises(ScreenScraperCredentialsError):
|
||||
await ScreenScraperService()._request(
|
||||
"https://api.screenscraper.fr/api2/jeuInfos.php"
|
||||
)
|
||||
|
||||
session.get.assert_called_once()
|
||||
assert ss_module._state.credentials_rejected is SSCredentialSet.DEVELOPER
|
||||
|
||||
|
||||
class TestQuotaWarnings:
|
||||
@pytest.fixture
|
||||
|
||||
@@ -9,8 +9,10 @@ import pytest
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from adapters.services.screenscraper import (
|
||||
ScreenScraperCredentialsError,
|
||||
ScreenScraperRateLimitError,
|
||||
SSAccountLimits,
|
||||
SSCredentialSet,
|
||||
)
|
||||
from adapters.services.screenscraper_types import SSGame
|
||||
from config.config_manager import Config, MetadataMediaType
|
||||
@@ -1348,6 +1350,81 @@ class TestScreenScraperQuotaFallback:
|
||||
assert result["ss_id"] is None
|
||||
|
||||
|
||||
class TestScreenScraperCredentialFallback:
|
||||
"""Rejected credentials are a configuration problem, not a scan failure: the
|
||||
service reports them once and the scan carries on with the other providers."""
|
||||
|
||||
def _make_file(self) -> MagicMock:
|
||||
mock_file = MagicMock()
|
||||
mock_file.file_size_bytes = 131072
|
||||
mock_file.is_top_level = True
|
||||
mock_file.file_extension = "md"
|
||||
mock_file.md5_hash = "abc123"
|
||||
mock_file.sha1_hash = "def456"
|
||||
mock_file.crc_hash = "78901234"
|
||||
mock_file.file_name = "Sonic (USA).md"
|
||||
mock_file.archive_members = None
|
||||
return mock_file
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_rom_returns_empty_on_rejected_credentials(self):
|
||||
handler = SSHandler()
|
||||
rom = MagicMock(
|
||||
platform_slug="genesis", platform_id=1, id=1, fs_name="Sonic (USA).md"
|
||||
)
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
||||
patch.object(
|
||||
handler.ss_service,
|
||||
"get_game_info",
|
||||
AsyncMock(
|
||||
side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER)
|
||||
),
|
||||
),
|
||||
):
|
||||
result, _ = await handler.lookup_rom(rom, 1, [self._make_file()])
|
||||
|
||||
assert result["ss_id"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_rom_returns_empty_on_rejected_credentials(self):
|
||||
handler = SSHandler()
|
||||
rom = MagicMock(platform_slug="genesis", platform_id=1, id=1, regions=[])
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
||||
patch.object(
|
||||
handler.ss_service,
|
||||
"search_games",
|
||||
AsyncMock(
|
||||
side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER)
|
||||
),
|
||||
),
|
||||
):
|
||||
result = await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
|
||||
|
||||
assert result["ss_id"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_rom_by_id_returns_empty_on_rejected_credentials(self):
|
||||
handler = SSHandler()
|
||||
with (
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
||||
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
||||
patch.object(
|
||||
handler.ss_service,
|
||||
"get_game_info",
|
||||
AsyncMock(
|
||||
side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER)
|
||||
),
|
||||
),
|
||||
):
|
||||
result = await handler.get_rom_by_id(MagicMock(), 1234)
|
||||
|
||||
assert result["ss_id"] is None
|
||||
|
||||
|
||||
class TestScreenScraperRateLimitPropagation:
|
||||
"""A per-minute refusal that survives the retry must reach the scan, which
|
||||
records the ROM as skipped once and stops asking ScreenScraper about it.
|
||||
|
||||
Reference in New Issue
Block a user