Files
romm/backend/tests/utils/test_update_hltb_api_url.py
Sam Dornan d084723bfb fix(hltb): accept token-only sessions and discover the endpoint when GitHub fails (#4758)
* fix(hltb): accept token-only sessions from /init

HowLongToBeat's /api/search/site/init now returns only a token and the
site's own search sends just x-auth-token. parse_session still required
hpKey and hpVal, so every mint read as "no session" and all HLTB lookups
(and the endpoint discovery workflow) silently returned nothing. The
honeypot pair is now optional and only sent when HLTB issues it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DHm9rRfJsxunF1RckjQqzx

* review: share the honeypot check and narrow optional mock calls

Move the both-fields honeypot check into HLTBSession.honeypot() so the
headers and body cannot drift apart, drop the historical note from its
comment, and assert mock call args are not None before reading kwargs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DHm9rRfJsxunF1RckjQqzx

* feat(hltb): discover the search endpoint from HLTB when GitHub fails

If the endpoint fixture can't be fetched from GitHub, run the same
build-manifest discovery the weekly workflow uses against HLTB itself,
and fall back to the fixture bundled in the image rather than the stale
hard-coded /api/find. The discovery helpers now log instead of printing
so their output joins RomM's logs. Search requests also send an Origin
header, as the browser does for HLTB's same-origin POST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DHm9rRfJsxunF1RckjQqzx

* fix(hltb): keep a malformed discovery response from aborting scans

parse_session and the discovery validator called .get() on whatever JSON
HLTB returned, so a non-object body raised AttributeError out of
initialize() and aborted the scan. Both now reject non-object JSON, and
the handler logs any discovery failure and keeps the bundled endpoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DHm9rRfJsxunF1RckjQqzx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:20:47 -05:00

139 lines
4.4 KiB
Python

from unittest.mock import MagicMock
import pytest
from utils.hltb_search import HLTB_BASE_URL, build_search_payload
from utils.update_hltb_api_url import (
BUILD_MANIFEST_REGEX,
VALIDATION_SEARCH_TERM,
candidate_search_routes,
serves_game_search,
)
# Abridged from the real manifest: the search route, its /init sibling, and the
# unrelated routes a naive "/api/search" match would also accept.
MANIFEST = """
self.__BUILD_MANIFEST={"/api/forum/search":["x.js"],"/api/search/site":["y.js"],
"/api/search/site/init":["z.js"],"/api/stats/games":["w.js"],"/api/user":["v.js"]}
"""
def test_search_route_is_the_one_paired_with_a_session_mint():
assert candidate_search_routes(MANIFEST) == ["/api/search/site"]
def test_a_route_without_an_init_sibling_is_not_a_candidate():
assert candidate_search_routes('{"/api/search/site":[]}') == []
def test_search_like_candidates_are_tried_first():
manifest = '{"/api/aaa":[],"/api/aaa/init":[],"/api/search/site":[],"/api/search/site/init":[]}'
assert candidate_search_routes(manifest) == ["/api/search/site", "/api/aaa"]
def test_build_manifest_is_located_by_its_hashed_build_id():
html = '<script src="/_next/static/xXfhvAtyEbN6z1HpYBEoi/_buildManifest.js" defer></script>'
match = BUILD_MANIFEST_REGEX.search(html)
assert match is not None
assert match.group("path") == (
"/_next/static/xXfhvAtyEbN6z1HpYBEoi/_buildManifest.js"
)
def test_turbopack_chunks_are_not_mistaken_for_the_manifest():
html = '<script src="/_next/static/chunks/turbopack-3c7ykt0_ogp3s.js"></script>'
assert BUILD_MANIFEST_REGEX.search(html) is None
def _client(session: object, search_body: object) -> MagicMock:
"""A stand-in HLTB whose /init and search responses the test controls."""
client = MagicMock()
client.get.return_value = _json_response(session)
client.post.return_value = _json_response(search_body)
return client
def _json_response(body: object) -> MagicMock:
response = MagicMock()
response.json.return_value = body
return response
SESSION = {"token": "t", "hpKey": "ign_k", "hpVal": "v"}
GAME = {"game_id": 6909, "game_name": "Paper Mario"}
def test_a_route_serving_real_games_is_accepted():
client = _client(SESSION, {"data": [GAME]})
assert (
serves_game_search(client, HLTB_BASE_URL, f"{HLTB_BASE_URL}/api/search/site")
is True
)
# A session-backed route is not enough: it has to answer the search itself.
@pytest.mark.parametrize(
"search_body",
[
pytest.param({"ok": True}, id="not-a-search-response"),
pytest.param({"data": [{"userId": 1, "name": "someone"}]}, id="not-games"),
pytest.param({"data": []}, id="no-results"),
pytest.param([GAME], id="not-a-json-object"),
],
)
def test_a_route_that_mints_but_does_not_serve_games_is_rejected(search_body: object):
client = _client(SESSION, search_body)
assert (
serves_game_search(client, HLTB_BASE_URL, f"{HLTB_BASE_URL}/api/other") is False
)
@pytest.mark.parametrize(
"session",
[
pytest.param({"hpKey": "ign_k", "hpVal": "v"}, id="no-token"),
pytest.param([SESSION], id="not-a-json-object"),
],
)
def test_an_incomplete_session_is_rejected_before_searching(session: object):
client = _client(session, {"data": [GAME]})
assert (
serves_game_search(client, HLTB_BASE_URL, f"{HLTB_BASE_URL}/api/search/site")
is False
)
client.post.assert_not_called()
def test_the_search_carries_the_session_and_honeypot_key():
client = _client(SESSION, {"data": [GAME]})
serves_game_search(client, HLTB_BASE_URL, f"{HLTB_BASE_URL}/api/search/site")
kwargs = client.post.call_args.kwargs
assert kwargs["headers"]["x-auth-token"] == "t"
# HLTB requires the rotating honeypot key in the body, not just the headers.
assert kwargs["json"]["ign_k"] == "v"
assert kwargs["json"]["searchTerms"] == [VALIDATION_SEARCH_TERM]
def test_a_token_only_session_searches_without_a_honeypot_key():
client = _client({"token": "t"}, {"data": [GAME]})
assert (
serves_game_search(client, HLTB_BASE_URL, f"{HLTB_BASE_URL}/api/search/site")
is True
)
post_call = client.post.call_args
assert post_call is not None
kwargs = post_call.kwargs
assert kwargs["headers"]["x-auth-token"] == "t"
assert "x-hp-key" not in kwargs["headers"]
assert kwargs["json"] == build_search_payload(VALIDATION_SEARCH_TERM, "")