test_makerworld.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. """Tests for the MakerWorldService."""
  2. from __future__ import annotations
  3. from unittest.mock import AsyncMock, MagicMock, patch
  4. from urllib.error import HTTPError, URLError
  5. import httpx
  6. import pytest
  7. from backend.app.services.makerworld import (
  8. _MAX_3MF_BYTES,
  9. MAKERWORLD_API_BASE,
  10. MakerWorldAuthError,
  11. MakerWorldForbiddenError,
  12. MakerWorldNotFoundError,
  13. MakerWorldService,
  14. MakerWorldUnavailableError,
  15. MakerWorldUrlError,
  16. )
  17. class TestParseUrl:
  18. """MakerWorld URL extraction."""
  19. def test_strips_locale_prefix_and_slug(self):
  20. model, profile = MakerWorldService.parse_url(
  21. "https://makerworld.com/en/models/1400373-self-watering-seed-starter"
  22. )
  23. assert model == 1400373
  24. assert profile is None
  25. def test_extracts_profile_id_from_fragment(self):
  26. model, profile = MakerWorldService.parse_url("https://makerworld.com/en/models/1400373-slug#profileId-1452154")
  27. assert model == 1400373
  28. assert profile == 1452154
  29. def test_accepts_scheme_omitted(self):
  30. model, profile = MakerWorldService.parse_url("makerworld.com/models/999")
  31. assert model == 999
  32. assert profile is None
  33. def test_accepts_subdomain(self):
  34. # Defensive: if MakerWorld ever stands up a regional subdomain, still accept it
  35. model, _ = MakerWorldService.parse_url("https://www.makerworld.com/en/models/42")
  36. assert model == 42
  37. def test_rejects_non_makerworld_host(self):
  38. with pytest.raises(MakerWorldUrlError):
  39. MakerWorldService.parse_url("https://thingiverse.com/things/123")
  40. def test_rejects_malformed_url(self):
  41. # No /models/ segment anywhere in path
  42. with pytest.raises(MakerWorldUrlError):
  43. MakerWorldService.parse_url("https://makerworld.com/en/creators/foo")
  44. def test_rejects_empty(self):
  45. with pytest.raises(MakerWorldUrlError):
  46. MakerWorldService.parse_url("")
  47. class TestApiBase:
  48. """Sanity check on the module-level constant — changing it is a deploy-risk."""
  49. def test_api_base_targets_bambulab_backend(self):
  50. # ``api.bambulab.com`` is not Cloudflare-fronted; ``makerworld.com`` is
  51. # and returns empty JSON to plain httpx. Regressing this constant
  52. # silently breaks the whole integration.
  53. assert MAKERWORLD_API_BASE == "https://api.bambulab.com/v1/design-service"
  54. class TestGetDesign:
  55. """Metadata endpoint happy-path + error mapping."""
  56. @pytest.fixture
  57. def service(self):
  58. # Use a MagicMock for the client so each call can be individually stubbed
  59. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  60. svc._client.get = AsyncMock()
  61. return svc
  62. @pytest.mark.asyncio
  63. async def test_returns_decoded_json(self, service):
  64. resp = MagicMock()
  65. resp.status_code = 200
  66. resp.json.return_value = {"id": 1400373, "title": "Benchy"}
  67. service._client.get.return_value = resp
  68. data = await service.get_design(1400373)
  69. assert data == {"id": 1400373, "title": "Benchy"}
  70. @pytest.mark.asyncio
  71. async def test_hits_bambulab_api_base(self, service):
  72. resp = MagicMock()
  73. resp.status_code = 200
  74. resp.json.return_value = {"id": 1}
  75. service._client.get.return_value = resp
  76. await service.get_design(1)
  77. call = service._client.get.call_args
  78. # First positional arg is the URL — must be on the api.bambulab.com
  79. # backend, not the Cloudflare-fronted makerworld.com host.
  80. url = call.args[0] if call.args else call.kwargs.get("url")
  81. assert url == "https://api.bambulab.com/v1/design-service/design/1"
  82. @pytest.mark.asyncio
  83. async def test_sends_honest_bambuddy_user_agent(self, service):
  84. """The client identifies honestly as Bambuddy, not as Firefox.
  85. Earlier iterations of this code stripped ``x-bbl-*`` Bambu-app
  86. identification headers but kept a Firefox User-Agent. Verified
  87. 2026-05-12 that MakerWorld treats ``Bambuddy/X.Y.Z`` identically to
  88. a Firefox UA at the Cloudflare edge — same response shape on
  89. ``/api/v1/design-service/*`` paths. Honest identification keeps us
  90. clearly outside Bambu Lab's "no falsified client identity" line
  91. from the 2026-05-12 cloud-access blog post.
  92. Referer is still sent because MakerWorld's CSRF / origin-check
  93. middleware uses it on some endpoints — that is functional, not
  94. client-impersonation.
  95. """
  96. resp = MagicMock()
  97. resp.status_code = 200
  98. resp.json.return_value = {"id": 1}
  99. service._client.get.return_value = resp
  100. await service.get_design(1)
  101. headers = service._client.get.call_args.kwargs["headers"]
  102. assert headers["User-Agent"].startswith("Bambuddy/")
  103. # Browser-impersonation strings must not creep back in
  104. assert "Mozilla" not in headers["User-Agent"]
  105. assert "Firefox" not in headers["User-Agent"]
  106. assert "Chrome" not in headers["User-Agent"]
  107. # Functional headers stay
  108. assert headers["Accept-Language"].startswith("en-US")
  109. assert headers["Referer"] == "https://makerworld.com/"
  110. assert "Accept" in headers
  111. # The deprecated Bambu-identification headers must no longer be sent.
  112. for dead_header in (
  113. "x-bbl-client-type",
  114. "x-bbl-client-version",
  115. "x-bbl-app-source",
  116. "x-bbl-client-name",
  117. ):
  118. assert dead_header not in headers
  119. @pytest.mark.asyncio
  120. async def test_maps_404_to_not_found(self, service):
  121. resp = MagicMock()
  122. resp.status_code = 404
  123. service._client.get.return_value = resp
  124. with pytest.raises(MakerWorldNotFoundError):
  125. await service.get_design(404)
  126. @pytest.mark.asyncio
  127. async def test_maps_401_without_token_to_auth_error(self, service):
  128. """No token was sent, so a 401 means "sign-in required" — not "your
  129. sign-in expired", and nothing gets marked dead (there is nothing to
  130. mark). The fixture's service carries no auth token."""
  131. resp = MagicMock()
  132. resp.status_code = 401
  133. resp.json.return_value = {"code": 1, "error": "Please log in"}
  134. service._client.get.return_value = resp
  135. with pytest.raises(MakerWorldAuthError) as exc_info:
  136. await service.get_design(1)
  137. assert "Bambu Cloud" in str(exc_info.value)
  138. @pytest.mark.asyncio
  139. async def test_401_with_token_reports_expired_and_hides_upstream_text(self):
  140. """Bambu answers a dead token with ``{"error": "Please login."}``. We used
  141. to forward that verbatim, which produced a "Please login." toast on a UI
  142. that simultaneously claimed the user was connected, and pointed at a
  143. Settings page that does not exist. Say what happened, name a real page,
  144. and record the credential as dead."""
  145. marked: list[bool] = []
  146. async def _on_auth_failure() -> None:
  147. marked.append(True)
  148. svc = MakerWorldService(
  149. client=MagicMock(spec=httpx.AsyncClient),
  150. auth_token="tok-abc",
  151. on_auth_failure=_on_auth_failure,
  152. )
  153. svc._client.get = AsyncMock()
  154. resp = MagicMock()
  155. resp.status_code = 401
  156. resp.json.return_value = {"code": 4, "error": "Please login.", "message": ""}
  157. svc._client.get.return_value = resp
  158. with pytest.raises(MakerWorldAuthError) as exc_info:
  159. await svc.get_design(1)
  160. message = str(exc_info.value)
  161. assert "Please login." not in message
  162. assert "expired" in message.lower()
  163. assert "Profiles" in message
  164. assert marked == [True], "a rejected token must be recorded as dead"
  165. @pytest.mark.asyncio
  166. async def test_maps_403_to_forbidden_with_upstream_reason(self, service):
  167. """403 is distinct from 401: auth was valid, MakerWorld refuses the
  168. specific resource (content-gated, region-locked, etc.). The upstream
  169. reason must reach the user so they know what to do."""
  170. resp = MagicMock()
  171. resp.status_code = 403
  172. resp.json.return_value = {
  173. "code": 15001,
  174. "error": "This model is only available to members",
  175. }
  176. service._client.get.return_value = resp
  177. with pytest.raises(MakerWorldForbiddenError) as exc_info:
  178. await service.get_design(1)
  179. assert "members" in str(exc_info.value)
  180. @pytest.mark.asyncio
  181. async def test_maps_5xx_to_unavailable(self, service):
  182. resp = MagicMock()
  183. resp.status_code = 503
  184. service._client.get.return_value = resp
  185. with pytest.raises(MakerWorldUnavailableError):
  186. await service.get_design(1)
  187. @pytest.mark.asyncio
  188. async def test_maps_timeout_to_unavailable(self, service):
  189. service._client.get.side_effect = httpx.TimeoutException("tooo slow")
  190. with pytest.raises(MakerWorldUnavailableError):
  191. await service.get_design(1)
  192. @pytest.mark.asyncio
  193. async def test_rejects_non_dict_json(self, service):
  194. resp = MagicMock()
  195. resp.status_code = 200
  196. resp.json.return_value = [1, 2, 3] # list, not dict
  197. service._client.get.return_value = resp
  198. with pytest.raises(MakerWorldUnavailableError):
  199. await service.get_design(1)
  200. class TestGetProfileDownload:
  201. """The new auth-gated 3MF manifest endpoint on the Bambu iot-service.
  202. Replaces the removed ``get_instance_download`` / ``get_model_download``
  203. helpers — YASTL#51's endpoint mints the signed CDN URL from the same
  204. long-lived Bambu Cloud bearer users already have.
  205. """
  206. def _make_service(self, *, auth_token: str | None = "tok-abc") -> MakerWorldService:
  207. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token=auth_token)
  208. svc._client.get = AsyncMock()
  209. return svc
  210. @pytest.mark.asyncio
  211. async def test_requires_auth_token(self):
  212. svc = self._make_service(auth_token=None)
  213. with pytest.raises(MakerWorldAuthError):
  214. await svc.get_profile_download(1452154, "US2bb73b106683e5")
  215. @pytest.mark.asyncio
  216. async def test_returns_signed_manifest(self):
  217. svc = self._make_service()
  218. resp = MagicMock()
  219. resp.status_code = 200
  220. resp.json.return_value = {
  221. "name": "benchy.3mf",
  222. "url": "https://makerworld.bblmw.com/makerworld/model/X/Y/f.3mf?exp=1&key=k",
  223. }
  224. svc._client.get.return_value = resp
  225. manifest = await svc.get_profile_download(1452154, "US2bb73b106683e5")
  226. assert manifest["url"].startswith("https://makerworld.bblmw.com/")
  227. assert manifest["name"] == "benchy.3mf"
  228. @pytest.mark.asyncio
  229. async def test_sends_bearer_and_model_id_query(self):
  230. """Auth goes in ``Authorization`` and the alphanumeric modelId as a
  231. ``model_id`` query param — this is what YASTL#51 reverse-engineered."""
  232. svc = self._make_service(auth_token="tok-abc")
  233. resp = MagicMock()
  234. resp.status_code = 200
  235. resp.json.return_value = {"url": "https://makerworld.bblmw.com/x.3mf"}
  236. svc._client.get.return_value = resp
  237. await svc.get_profile_download(1452154, "US2bb73b106683e5")
  238. call = svc._client.get.call_args
  239. url = call.args[0] if call.args else call.kwargs.get("url")
  240. assert url == "https://api.bambulab.com/v1/iot-service/api/user/profile/1452154"
  241. assert call.kwargs["headers"]["Authorization"] == "Bearer tok-abc"
  242. assert call.kwargs["params"] == {"model_id": "US2bb73b106683e5"}
  243. @pytest.mark.asyncio
  244. async def test_maps_401_to_auth_error(self):
  245. svc = self._make_service()
  246. resp = MagicMock()
  247. resp.status_code = 401
  248. resp.json.return_value = {"error": "token expired"}
  249. svc._client.get.return_value = resp
  250. with pytest.raises(MakerWorldAuthError):
  251. await svc.get_profile_download(1, "M1")
  252. @pytest.mark.asyncio
  253. async def test_maps_403_to_forbidden(self):
  254. svc = self._make_service()
  255. resp = MagicMock()
  256. resp.status_code = 403
  257. resp.json.return_value = {"error": "paid model"}
  258. svc._client.get.return_value = resp
  259. with pytest.raises(MakerWorldForbiddenError) as exc_info:
  260. await svc.get_profile_download(1, "M1")
  261. assert "paid model" in str(exc_info.value)
  262. @pytest.mark.asyncio
  263. async def test_maps_404_to_not_found(self):
  264. svc = self._make_service()
  265. resp = MagicMock()
  266. resp.status_code = 404
  267. svc._client.get.return_value = resp
  268. with pytest.raises(MakerWorldNotFoundError):
  269. await svc.get_profile_download(1, "M1")
  270. @pytest.mark.asyncio
  271. async def test_maps_timeout_to_unavailable(self):
  272. svc = self._make_service()
  273. svc._client.get.side_effect = httpx.TimeoutException("nope")
  274. with pytest.raises(MakerWorldUnavailableError):
  275. await svc.get_profile_download(1, "M1")
  276. @pytest.mark.asyncio
  277. async def test_rejects_non_dict_json(self):
  278. svc = self._make_service()
  279. resp = MagicMock()
  280. resp.status_code = 200
  281. resp.json.return_value = ["not", "a", "dict"]
  282. svc._client.get.return_value = resp
  283. with pytest.raises(MakerWorldUnavailableError):
  284. await svc.get_profile_download(1, "M1")
  285. class TestDownload3MF:
  286. """SSRF guard + size cap + streaming behaviour."""
  287. def _stream_ctx(self, resp):
  288. ctx = MagicMock()
  289. ctx.__aenter__ = AsyncMock(return_value=resp)
  290. ctx.__aexit__ = AsyncMock(return_value=None)
  291. return ctx
  292. @pytest.mark.asyncio
  293. @pytest.mark.parametrize(
  294. "url",
  295. [
  296. "https://example.com/steal.3mf",
  297. "https://169.254.169.254/meta", # EC2 metadata
  298. "http://internal.host/loot",
  299. "http://127.0.0.1/loot",
  300. ],
  301. )
  302. async def test_rejects_non_allowed_hosts(self, url):
  303. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  304. with pytest.raises(MakerWorldUrlError):
  305. await svc.download_3mf(url)
  306. @pytest.mark.asyncio
  307. async def test_s3_host_delegates_to_urllib_path(self):
  308. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  309. with patch(
  310. "backend.app.services.makerworld._download_s3_urllib",
  311. new=AsyncMock(return_value=(b"payload", "file.3mf")),
  312. ) as mocked:
  313. payload, filename = await svc.download_3mf(
  314. "https://s3.us-west-2.amazonaws.com/bucket/key/file.3mf?X-Amz-Signature=abc"
  315. )
  316. mocked.assert_awaited_once()
  317. # First arg is the verbatim URL — must NOT be round-tripped through
  318. # httpx/urlparse.urlencode since that breaks S3 SigV4.
  319. args = mocked.await_args.args
  320. assert args[0] == ("https://s3.us-west-2.amazonaws.com/bucket/key/file.3mf?X-Amz-Signature=abc")
  321. assert payload == b"payload"
  322. assert filename == "file.3mf"
  323. @pytest.mark.asyncio
  324. async def test_cdn_url_uses_httpx_with_minimal_headers(self):
  325. """Signed CDN URLs already carry the auth in the query string — don't
  326. leak the Bambu Cloud bearer to the CDN too. The client is reduced to a
  327. single ``User-Agent`` header; no ``Authorization``, no ``x-bbl-*``."""
  328. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token="tok-abc")
  329. resp = MagicMock()
  330. resp.status_code = 200
  331. async def _chunks():
  332. yield b"PK\x03\x04"
  333. resp.aiter_bytes = lambda: _chunks()
  334. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  335. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  336. call = svc._client.stream.call_args
  337. headers = call.kwargs["headers"]
  338. # Minimal: UA only. No bearer to the CDN.
  339. assert "Authorization" not in headers
  340. assert all(not k.startswith("x-bbl") for k in headers)
  341. assert "User-Agent" in headers
  342. # Redirects off — host allowlist is only meaningful on the initial URL.
  343. assert call.kwargs["follow_redirects"] is False
  344. @pytest.mark.asyncio
  345. async def test_happy_path_streams_bytes(self):
  346. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  347. resp = MagicMock()
  348. resp.status_code = 200
  349. async def _chunks():
  350. yield b"PK\x03\x04" # 3MF = zip magic
  351. yield b"rest of file"
  352. resp.aiter_bytes = lambda: _chunks()
  353. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  354. payload, filename = await svc.download_3mf(
  355. "https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k"
  356. )
  357. assert payload.startswith(b"PK\x03\x04")
  358. assert filename == "foo.3mf"
  359. @pytest.mark.asyncio
  360. async def test_http_error_on_cdn_path_raises_unavailable(self):
  361. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  362. resp = MagicMock()
  363. resp.status_code = 500
  364. resp.aiter_bytes = lambda: (_ for _ in ())
  365. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  366. with pytest.raises(MakerWorldUnavailableError):
  367. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  368. @pytest.mark.asyncio
  369. async def test_exceeds_size_cap_raises(self):
  370. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  371. resp = MagicMock()
  372. resp.status_code = 200
  373. # Cap is 200 MB — emit one "chunk" that reports exceeding it.
  374. oversized = _MAX_3MF_BYTES + 1
  375. async def _chunks():
  376. # Emit a bytes object whose ``len()`` is oversized, without
  377. # actually allocating 200 MB in the test process.
  378. yield b"\x00" * oversized
  379. resp.aiter_bytes = lambda: _chunks()
  380. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  381. with pytest.raises(MakerWorldUnavailableError, match="cap"):
  382. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  383. class TestS3UrllibDownload:
  384. """Module-level ``_download_s3_urllib`` — the verbatim-URL path for S3."""
  385. @pytest.mark.asyncio
  386. async def test_returns_bytes_and_filename(self):
  387. from backend.app.services.makerworld import _download_s3_urllib
  388. fake_resp = MagicMock()
  389. fake_resp.status = 200
  390. # Simulate urllib's file-like ``read(n)`` interface.
  391. fake_resp.read = MagicMock(side_effect=[b"hello", b""])
  392. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  393. fake_resp.__exit__ = MagicMock(return_value=None)
  394. fake_opener = MagicMock()
  395. fake_opener.open = MagicMock(return_value=fake_resp)
  396. with patch("urllib.request.build_opener", return_value=fake_opener):
  397. data, filename = await _download_s3_urllib(
  398. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  399. "fallback.3mf",
  400. )
  401. assert data == b"hello"
  402. assert filename == "fallback.3mf"
  403. @pytest.mark.asyncio
  404. async def test_redirect_is_treated_as_error(self):
  405. """The ``_NoRedirect`` handler returns ``None`` from ``redirect_request``,
  406. which makes ``urllib`` raise ``HTTPError`` instead of following. The
  407. wrapper must surface that as ``MakerWorldUnavailableError``."""
  408. from backend.app.services.makerworld import _download_s3_urllib
  409. fake_opener = MagicMock()
  410. fake_opener.open = MagicMock(
  411. side_effect=HTTPError(
  412. "https://s3.example/redirect",
  413. 302,
  414. "Found",
  415. {}, # type: ignore[arg-type]
  416. None,
  417. )
  418. )
  419. with (
  420. patch("urllib.request.build_opener", return_value=fake_opener),
  421. pytest.raises(MakerWorldUnavailableError),
  422. ):
  423. await _download_s3_urllib(
  424. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  425. "fallback.3mf",
  426. )
  427. @pytest.mark.asyncio
  428. async def test_non_200_raises_unavailable(self):
  429. from backend.app.services.makerworld import _download_s3_urllib
  430. fake_resp = MagicMock()
  431. fake_resp.status = 403
  432. fake_resp.read = MagicMock(return_value=b"")
  433. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  434. fake_resp.__exit__ = MagicMock(return_value=None)
  435. fake_opener = MagicMock()
  436. fake_opener.open = MagicMock(return_value=fake_resp)
  437. with (
  438. patch("urllib.request.build_opener", return_value=fake_opener),
  439. pytest.raises(MakerWorldUnavailableError),
  440. ):
  441. await _download_s3_urllib(
  442. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  443. "fallback.3mf",
  444. )
  445. @pytest.mark.asyncio
  446. async def test_size_cap_enforced(self):
  447. from backend.app.services.makerworld import _download_s3_urllib
  448. fake_resp = MagicMock()
  449. fake_resp.status = 200
  450. # A single oversized chunk trips the cap on the first iteration.
  451. fake_resp.read = MagicMock(side_effect=[b"\x00" * (_MAX_3MF_BYTES + 1), b""])
  452. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  453. fake_resp.__exit__ = MagicMock(return_value=None)
  454. fake_opener = MagicMock()
  455. fake_opener.open = MagicMock(return_value=fake_resp)
  456. with (
  457. patch("urllib.request.build_opener", return_value=fake_opener),
  458. pytest.raises(MakerWorldUnavailableError, match="cap"),
  459. ):
  460. await _download_s3_urllib(
  461. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  462. "fallback.3mf",
  463. )
  464. @pytest.mark.asyncio
  465. async def test_network_error_mapped_to_unavailable(self):
  466. from backend.app.services.makerworld import _download_s3_urllib
  467. fake_opener = MagicMock()
  468. fake_opener.open = MagicMock(side_effect=URLError("dns fail"))
  469. with (
  470. patch("urllib.request.build_opener", return_value=fake_opener),
  471. pytest.raises(MakerWorldUnavailableError),
  472. ):
  473. await _download_s3_urllib(
  474. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  475. "fallback.3mf",
  476. )
  477. class TestFetchThumbnail:
  478. """Proxy the CDN thumbnails so img-src CSP doesn't need to allow external hosts."""
  479. @pytest.fixture
  480. def service(self):
  481. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  482. svc._client.get = AsyncMock()
  483. return svc
  484. @pytest.mark.asyncio
  485. async def test_rejects_non_cdn_host(self, service):
  486. with pytest.raises(MakerWorldUrlError):
  487. await service.fetch_thumbnail("https://evil.example.com/img.jpg")
  488. @pytest.mark.asyncio
  489. async def test_rejects_loopback(self, service):
  490. # SSRF: don't let anyone abuse this as an open proxy toward 127.0.0.1
  491. with pytest.raises(MakerWorldUrlError):
  492. await service.fetch_thumbnail("http://127.0.0.1/secret.jpg")
  493. @pytest.mark.asyncio
  494. async def test_does_not_follow_redirects(self, service):
  495. """Host allowlist is only enforced on the initial URL — a 302 from the
  496. CDN to any other host would otherwise bypass the allowlist. ``follow_
  497. redirects=False`` pins that behaviour in the wire contract."""
  498. resp = MagicMock()
  499. resp.status_code = 200
  500. resp.headers = {"content-type": "image/jpeg"}
  501. resp.content = b"\xff\xd8\xff\xe0JFIF"
  502. service._client.get.return_value = resp
  503. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/cover.jpg")
  504. assert service._client.get.call_args.kwargs["follow_redirects"] is False
  505. @pytest.mark.asyncio
  506. async def test_rejects_html_content_type_even_with_image_extension(self, service):
  507. # An upstream error page (HTML) at a .jpg URL must be refused —
  508. # otherwise we'd forward it to the browser under an image framing.
  509. resp = MagicMock()
  510. resp.status_code = 200
  511. resp.headers = {"content-type": "text/html"}
  512. resp.content = b"<html>error page</html>"
  513. service._client.get.return_value = resp
  514. with pytest.raises(MakerWorldUnavailableError):
  515. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/cover.jpg")
  516. @pytest.mark.asyncio
  517. async def test_happy_path_with_proper_image_content_type(self, service):
  518. resp = MagicMock()
  519. resp.status_code = 200
  520. resp.headers = {"content-type": "image/jpeg; charset=binary"}
  521. resp.content = b"\xff\xd8\xff\xe0JFIF" # JPEG magic bytes
  522. service._client.get.return_value = resp
  523. payload, content_type = await service.fetch_thumbnail(
  524. "https://makerworld.bblmw.com/makerworld/model/X/cover.jpg"
  525. )
  526. assert payload == b"\xff\xd8\xff\xe0JFIF"
  527. # Semi-colon params stripped
  528. assert content_type == "image/jpeg"
  529. @pytest.mark.asyncio
  530. async def test_infers_mime_from_extension_when_cdn_lies(self, service):
  531. """MakerWorld's CDN returns application/octet-stream for real PNG/JPG
  532. files. Relying on upstream content-type alone would fail every
  533. thumbnail request; fall back to the URL extension."""
  534. resp = MagicMock()
  535. resp.status_code = 200
  536. resp.headers = {"content-type": "application/octet-stream"}
  537. resp.content = b"\x89PNG\r\n\x1a\n" # PNG magic bytes
  538. service._client.get.return_value = resp
  539. payload, content_type = await service.fetch_thumbnail(
  540. "https://makerworld.bblmw.com/makerworld/model/X/design/abc.png"
  541. )
  542. assert payload.startswith(b"\x89PNG")
  543. assert content_type == "image/png"
  544. @pytest.mark.asyncio
  545. async def test_refuses_when_no_extension_and_non_image_type(self, service):
  546. """If the URL carries no image extension AND upstream doesn't declare
  547. image/*, we can't confidently serve it as an image — refuse."""
  548. resp = MagicMock()
  549. resp.status_code = 200
  550. resp.headers = {"content-type": "application/octet-stream"}
  551. resp.content = b"who knows what this is"
  552. service._client.get.return_value = resp
  553. with pytest.raises(MakerWorldUnavailableError):
  554. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/blob")