test_makerworld.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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_transient_401_with_token_does_not_invalidate(self):
  167. """A 401 WITHOUT Bambu's expiry signature (endpoint/edge noise) must fail
  168. the request but NOT durably sign the user out — otherwise one stray 401
  169. from any single MakerWorld call kills the whole cloud integration."""
  170. marked: list[bool] = []
  171. async def _on_auth_failure() -> None:
  172. marked.append(True)
  173. svc = MakerWorldService(
  174. client=MagicMock(spec=httpx.AsyncClient),
  175. auth_token="tok-abc",
  176. on_auth_failure=_on_auth_failure,
  177. )
  178. svc._client.get = AsyncMock()
  179. resp = MagicMock()
  180. resp.status_code = 401
  181. resp.json.return_value = {"code": 1, "error": "forbidden"}
  182. svc._client.get.return_value = resp
  183. with pytest.raises(MakerWorldAuthError):
  184. await svc.get_design(1)
  185. assert marked == [], "a benign 401 must not record the credential as dead"
  186. @pytest.mark.asyncio
  187. async def test_maps_403_to_forbidden_with_upstream_reason(self, service):
  188. """403 is distinct from 401: auth was valid, MakerWorld refuses the
  189. specific resource (content-gated, region-locked, etc.). The upstream
  190. reason must reach the user so they know what to do."""
  191. resp = MagicMock()
  192. resp.status_code = 403
  193. resp.json.return_value = {
  194. "code": 15001,
  195. "error": "This model is only available to members",
  196. }
  197. service._client.get.return_value = resp
  198. with pytest.raises(MakerWorldForbiddenError) as exc_info:
  199. await service.get_design(1)
  200. assert "members" in str(exc_info.value)
  201. @pytest.mark.asyncio
  202. async def test_maps_5xx_to_unavailable(self, service):
  203. resp = MagicMock()
  204. resp.status_code = 503
  205. service._client.get.return_value = resp
  206. with pytest.raises(MakerWorldUnavailableError):
  207. await service.get_design(1)
  208. @pytest.mark.asyncio
  209. async def test_maps_timeout_to_unavailable(self, service):
  210. service._client.get.side_effect = httpx.TimeoutException("tooo slow")
  211. with pytest.raises(MakerWorldUnavailableError):
  212. await service.get_design(1)
  213. @pytest.mark.asyncio
  214. async def test_rejects_non_dict_json(self, service):
  215. resp = MagicMock()
  216. resp.status_code = 200
  217. resp.json.return_value = [1, 2, 3] # list, not dict
  218. service._client.get.return_value = resp
  219. with pytest.raises(MakerWorldUnavailableError):
  220. await service.get_design(1)
  221. class TestGetProfileDownload:
  222. """The new auth-gated 3MF manifest endpoint on the Bambu iot-service.
  223. Replaces the removed ``get_instance_download`` / ``get_model_download``
  224. helpers — YASTL#51's endpoint mints the signed CDN URL from the same
  225. long-lived Bambu Cloud bearer users already have.
  226. """
  227. def _make_service(self, *, auth_token: str | None = "tok-abc") -> MakerWorldService:
  228. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token=auth_token)
  229. svc._client.get = AsyncMock()
  230. return svc
  231. @pytest.mark.asyncio
  232. async def test_requires_auth_token(self):
  233. svc = self._make_service(auth_token=None)
  234. with pytest.raises(MakerWorldAuthError):
  235. await svc.get_profile_download(1452154, "US2bb73b106683e5")
  236. @pytest.mark.asyncio
  237. async def test_returns_signed_manifest(self):
  238. svc = self._make_service()
  239. resp = MagicMock()
  240. resp.status_code = 200
  241. resp.json.return_value = {
  242. "name": "benchy.3mf",
  243. "url": "https://makerworld.bblmw.com/makerworld/model/X/Y/f.3mf?exp=1&key=k",
  244. }
  245. svc._client.get.return_value = resp
  246. manifest = await svc.get_profile_download(1452154, "US2bb73b106683e5")
  247. assert manifest["url"].startswith("https://makerworld.bblmw.com/")
  248. assert manifest["name"] == "benchy.3mf"
  249. @pytest.mark.asyncio
  250. async def test_sends_bearer_and_model_id_query(self):
  251. """Auth goes in ``Authorization`` and the alphanumeric modelId as a
  252. ``model_id`` query param — this is what YASTL#51 reverse-engineered."""
  253. svc = self._make_service(auth_token="tok-abc")
  254. resp = MagicMock()
  255. resp.status_code = 200
  256. resp.json.return_value = {"url": "https://makerworld.bblmw.com/x.3mf"}
  257. svc._client.get.return_value = resp
  258. await svc.get_profile_download(1452154, "US2bb73b106683e5")
  259. call = svc._client.get.call_args
  260. url = call.args[0] if call.args else call.kwargs.get("url")
  261. assert url == "https://api.bambulab.com/v1/iot-service/api/user/profile/1452154"
  262. assert call.kwargs["headers"]["Authorization"] == "Bearer tok-abc"
  263. assert call.kwargs["params"] == {"model_id": "US2bb73b106683e5"}
  264. @pytest.mark.asyncio
  265. async def test_maps_401_to_auth_error(self):
  266. svc = self._make_service()
  267. resp = MagicMock()
  268. resp.status_code = 401
  269. resp.json.return_value = {"error": "token expired"}
  270. svc._client.get.return_value = resp
  271. with pytest.raises(MakerWorldAuthError):
  272. await svc.get_profile_download(1, "M1")
  273. @pytest.mark.asyncio
  274. async def test_maps_403_to_forbidden(self):
  275. svc = self._make_service()
  276. resp = MagicMock()
  277. resp.status_code = 403
  278. resp.json.return_value = {"error": "paid model"}
  279. svc._client.get.return_value = resp
  280. with pytest.raises(MakerWorldForbiddenError) as exc_info:
  281. await svc.get_profile_download(1, "M1")
  282. assert "paid model" in str(exc_info.value)
  283. @pytest.mark.asyncio
  284. async def test_maps_404_to_not_found(self):
  285. svc = self._make_service()
  286. resp = MagicMock()
  287. resp.status_code = 404
  288. svc._client.get.return_value = resp
  289. with pytest.raises(MakerWorldNotFoundError):
  290. await svc.get_profile_download(1, "M1")
  291. @pytest.mark.asyncio
  292. async def test_maps_timeout_to_unavailable(self):
  293. svc = self._make_service()
  294. svc._client.get.side_effect = httpx.TimeoutException("nope")
  295. with pytest.raises(MakerWorldUnavailableError):
  296. await svc.get_profile_download(1, "M1")
  297. @pytest.mark.asyncio
  298. async def test_rejects_non_dict_json(self):
  299. svc = self._make_service()
  300. resp = MagicMock()
  301. resp.status_code = 200
  302. resp.json.return_value = ["not", "a", "dict"]
  303. svc._client.get.return_value = resp
  304. with pytest.raises(MakerWorldUnavailableError):
  305. await svc.get_profile_download(1, "M1")
  306. class TestDownload3MF:
  307. """SSRF guard + size cap + streaming behaviour."""
  308. def _stream_ctx(self, resp):
  309. ctx = MagicMock()
  310. ctx.__aenter__ = AsyncMock(return_value=resp)
  311. ctx.__aexit__ = AsyncMock(return_value=None)
  312. return ctx
  313. @pytest.mark.asyncio
  314. @pytest.mark.parametrize(
  315. "url",
  316. [
  317. "https://example.com/steal.3mf",
  318. "https://169.254.169.254/meta", # EC2 metadata
  319. "http://internal.host/loot",
  320. "http://127.0.0.1/loot",
  321. ],
  322. )
  323. async def test_rejects_non_allowed_hosts(self, url):
  324. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  325. with pytest.raises(MakerWorldUrlError):
  326. await svc.download_3mf(url)
  327. @pytest.mark.asyncio
  328. async def test_s3_host_delegates_to_urllib_path(self):
  329. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  330. with patch(
  331. "backend.app.services.makerworld._download_s3_urllib",
  332. new=AsyncMock(return_value=(b"payload", "file.3mf")),
  333. ) as mocked:
  334. payload, filename = await svc.download_3mf(
  335. "https://s3.us-west-2.amazonaws.com/bucket/key/file.3mf?X-Amz-Signature=abc"
  336. )
  337. mocked.assert_awaited_once()
  338. # First arg is the verbatim URL — must NOT be round-tripped through
  339. # httpx/urlparse.urlencode since that breaks S3 SigV4.
  340. args = mocked.await_args.args
  341. assert args[0] == ("https://s3.us-west-2.amazonaws.com/bucket/key/file.3mf?X-Amz-Signature=abc")
  342. assert payload == b"payload"
  343. assert filename == "file.3mf"
  344. @pytest.mark.asyncio
  345. async def test_cdn_url_uses_httpx_with_minimal_headers(self):
  346. """Signed CDN URLs already carry the auth in the query string — don't
  347. leak the Bambu Cloud bearer to the CDN too. The client is reduced to a
  348. single ``User-Agent`` header; no ``Authorization``, no ``x-bbl-*``."""
  349. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token="tok-abc")
  350. resp = MagicMock()
  351. resp.status_code = 200
  352. async def _chunks():
  353. yield b"PK\x03\x04"
  354. resp.aiter_bytes = lambda: _chunks()
  355. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  356. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  357. call = svc._client.stream.call_args
  358. headers = call.kwargs["headers"]
  359. # Minimal: UA only. No bearer to the CDN.
  360. assert "Authorization" not in headers
  361. assert all(not k.startswith("x-bbl") for k in headers)
  362. assert "User-Agent" in headers
  363. # Redirects off — host allowlist is only meaningful on the initial URL.
  364. assert call.kwargs["follow_redirects"] is False
  365. @pytest.mark.asyncio
  366. async def test_happy_path_streams_bytes(self):
  367. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  368. resp = MagicMock()
  369. resp.status_code = 200
  370. async def _chunks():
  371. yield b"PK\x03\x04" # 3MF = zip magic
  372. yield b"rest of file"
  373. resp.aiter_bytes = lambda: _chunks()
  374. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  375. payload, filename = await svc.download_3mf(
  376. "https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k"
  377. )
  378. assert payload.startswith(b"PK\x03\x04")
  379. assert filename == "foo.3mf"
  380. @pytest.mark.asyncio
  381. async def test_http_error_on_cdn_path_raises_unavailable(self):
  382. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  383. resp = MagicMock()
  384. resp.status_code = 500
  385. resp.aiter_bytes = lambda: (_ for _ in ())
  386. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  387. with pytest.raises(MakerWorldUnavailableError):
  388. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  389. @pytest.mark.asyncio
  390. async def test_exceeds_size_cap_raises(self):
  391. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  392. resp = MagicMock()
  393. resp.status_code = 200
  394. # Cap is 200 MB — emit one "chunk" that reports exceeding it.
  395. oversized = _MAX_3MF_BYTES + 1
  396. async def _chunks():
  397. # Emit a bytes object whose ``len()`` is oversized, without
  398. # actually allocating 200 MB in the test process.
  399. yield b"\x00" * oversized
  400. resp.aiter_bytes = lambda: _chunks()
  401. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  402. with pytest.raises(MakerWorldUnavailableError, match="cap"):
  403. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  404. class TestS3UrllibDownload:
  405. """Module-level ``_download_s3_urllib`` — the verbatim-URL path for S3."""
  406. @pytest.mark.asyncio
  407. async def test_returns_bytes_and_filename(self):
  408. from backend.app.services.makerworld import _download_s3_urllib
  409. fake_resp = MagicMock()
  410. fake_resp.status = 200
  411. # Simulate urllib's file-like ``read(n)`` interface.
  412. fake_resp.read = MagicMock(side_effect=[b"hello", b""])
  413. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  414. fake_resp.__exit__ = MagicMock(return_value=None)
  415. fake_opener = MagicMock()
  416. fake_opener.open = MagicMock(return_value=fake_resp)
  417. with patch("urllib.request.build_opener", return_value=fake_opener):
  418. data, filename = await _download_s3_urllib(
  419. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  420. "fallback.3mf",
  421. )
  422. assert data == b"hello"
  423. assert filename == "fallback.3mf"
  424. @pytest.mark.asyncio
  425. async def test_redirect_is_treated_as_error(self):
  426. """The ``_NoRedirect`` handler returns ``None`` from ``redirect_request``,
  427. which makes ``urllib`` raise ``HTTPError`` instead of following. The
  428. wrapper must surface that as ``MakerWorldUnavailableError``."""
  429. from backend.app.services.makerworld import _download_s3_urllib
  430. fake_opener = MagicMock()
  431. fake_opener.open = MagicMock(
  432. side_effect=HTTPError(
  433. "https://s3.example/redirect",
  434. 302,
  435. "Found",
  436. {}, # type: ignore[arg-type]
  437. None,
  438. )
  439. )
  440. with (
  441. patch("urllib.request.build_opener", return_value=fake_opener),
  442. pytest.raises(MakerWorldUnavailableError),
  443. ):
  444. await _download_s3_urllib(
  445. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  446. "fallback.3mf",
  447. )
  448. @pytest.mark.asyncio
  449. async def test_non_200_raises_unavailable(self):
  450. from backend.app.services.makerworld import _download_s3_urllib
  451. fake_resp = MagicMock()
  452. fake_resp.status = 403
  453. fake_resp.read = MagicMock(return_value=b"")
  454. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  455. fake_resp.__exit__ = MagicMock(return_value=None)
  456. fake_opener = MagicMock()
  457. fake_opener.open = MagicMock(return_value=fake_resp)
  458. with (
  459. patch("urllib.request.build_opener", return_value=fake_opener),
  460. pytest.raises(MakerWorldUnavailableError),
  461. ):
  462. await _download_s3_urllib(
  463. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  464. "fallback.3mf",
  465. )
  466. @pytest.mark.asyncio
  467. async def test_size_cap_enforced(self):
  468. from backend.app.services.makerworld import _download_s3_urllib
  469. fake_resp = MagicMock()
  470. fake_resp.status = 200
  471. # A single oversized chunk trips the cap on the first iteration.
  472. fake_resp.read = MagicMock(side_effect=[b"\x00" * (_MAX_3MF_BYTES + 1), b""])
  473. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  474. fake_resp.__exit__ = MagicMock(return_value=None)
  475. fake_opener = MagicMock()
  476. fake_opener.open = MagicMock(return_value=fake_resp)
  477. with (
  478. patch("urllib.request.build_opener", return_value=fake_opener),
  479. pytest.raises(MakerWorldUnavailableError, match="cap"),
  480. ):
  481. await _download_s3_urllib(
  482. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  483. "fallback.3mf",
  484. )
  485. @pytest.mark.asyncio
  486. async def test_network_error_mapped_to_unavailable(self):
  487. from backend.app.services.makerworld import _download_s3_urllib
  488. fake_opener = MagicMock()
  489. fake_opener.open = MagicMock(side_effect=URLError("dns fail"))
  490. with (
  491. patch("urllib.request.build_opener", return_value=fake_opener),
  492. pytest.raises(MakerWorldUnavailableError),
  493. ):
  494. await _download_s3_urllib(
  495. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  496. "fallback.3mf",
  497. )
  498. class TestFetchThumbnail:
  499. """Proxy the CDN thumbnails so img-src CSP doesn't need to allow external hosts."""
  500. @pytest.fixture
  501. def service(self):
  502. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  503. svc._client.get = AsyncMock()
  504. return svc
  505. @pytest.mark.asyncio
  506. async def test_rejects_non_cdn_host(self, service):
  507. with pytest.raises(MakerWorldUrlError):
  508. await service.fetch_thumbnail("https://evil.example.com/img.jpg")
  509. @pytest.mark.asyncio
  510. async def test_rejects_loopback(self, service):
  511. # SSRF: don't let anyone abuse this as an open proxy toward 127.0.0.1
  512. with pytest.raises(MakerWorldUrlError):
  513. await service.fetch_thumbnail("http://127.0.0.1/secret.jpg")
  514. @pytest.mark.asyncio
  515. async def test_does_not_follow_redirects(self, service):
  516. """Host allowlist is only enforced on the initial URL — a 302 from the
  517. CDN to any other host would otherwise bypass the allowlist. ``follow_
  518. redirects=False`` pins that behaviour in the wire contract."""
  519. resp = MagicMock()
  520. resp.status_code = 200
  521. resp.headers = {"content-type": "image/jpeg"}
  522. resp.content = b"\xff\xd8\xff\xe0JFIF"
  523. service._client.get.return_value = resp
  524. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/cover.jpg")
  525. assert service._client.get.call_args.kwargs["follow_redirects"] is False
  526. @pytest.mark.asyncio
  527. async def test_rejects_html_content_type_even_with_image_extension(self, service):
  528. # An upstream error page (HTML) at a .jpg URL must be refused —
  529. # otherwise we'd forward it to the browser under an image framing.
  530. resp = MagicMock()
  531. resp.status_code = 200
  532. resp.headers = {"content-type": "text/html"}
  533. resp.content = b"<html>error page</html>"
  534. service._client.get.return_value = resp
  535. with pytest.raises(MakerWorldUnavailableError):
  536. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/cover.jpg")
  537. @pytest.mark.asyncio
  538. async def test_happy_path_with_proper_image_content_type(self, service):
  539. resp = MagicMock()
  540. resp.status_code = 200
  541. resp.headers = {"content-type": "image/jpeg; charset=binary"}
  542. resp.content = b"\xff\xd8\xff\xe0JFIF" # JPEG magic bytes
  543. service._client.get.return_value = resp
  544. payload, content_type = await service.fetch_thumbnail(
  545. "https://makerworld.bblmw.com/makerworld/model/X/cover.jpg"
  546. )
  547. assert payload == b"\xff\xd8\xff\xe0JFIF"
  548. # Semi-colon params stripped
  549. assert content_type == "image/jpeg"
  550. @pytest.mark.asyncio
  551. async def test_infers_mime_from_extension_when_cdn_lies(self, service):
  552. """MakerWorld's CDN returns application/octet-stream for real PNG/JPG
  553. files. Relying on upstream content-type alone would fail every
  554. thumbnail request; fall back to the URL extension."""
  555. resp = MagicMock()
  556. resp.status_code = 200
  557. resp.headers = {"content-type": "application/octet-stream"}
  558. resp.content = b"\x89PNG\r\n\x1a\n" # PNG magic bytes
  559. service._client.get.return_value = resp
  560. payload, content_type = await service.fetch_thumbnail(
  561. "https://makerworld.bblmw.com/makerworld/model/X/design/abc.png"
  562. )
  563. assert payload.startswith(b"\x89PNG")
  564. assert content_type == "image/png"
  565. @pytest.mark.asyncio
  566. async def test_refuses_when_no_extension_and_non_image_type(self, service):
  567. """If the URL carries no image extension AND upstream doesn't declare
  568. image/*, we can't confidently serve it as an image — refuse."""
  569. resp = MagicMock()
  570. resp.status_code = 200
  571. resp.headers = {"content-type": "application/octet-stream"}
  572. resp.content = b"who knows what this is"
  573. service._client.get.return_value = resp
  574. with pytest.raises(MakerWorldUnavailableError):
  575. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/blob")