test_makerworld.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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.model_providers.base import ProviderResourceRef
  8. from backend.app.services.model_providers.makerworld.errors import (
  9. MakerWorldAuthError,
  10. MakerWorldForbiddenError,
  11. MakerWorldNotFoundError,
  12. MakerWorldUnavailableError,
  13. MakerWorldUrlError,
  14. )
  15. from backend.app.services.model_providers.makerworld.http import _MAX_3MF_BYTES, MAKERWORLD_API_BASE
  16. from backend.app.services.model_providers.makerworld.service import MakerWorldService, set_shared_http_client
  17. from backend.app.services.model_providers.makerworld.url import parse_url
  18. class TestParseUrl:
  19. """MakerWorld URL extraction — tests parse_url directly."""
  20. def test_strips_locale_prefix_and_slug(self):
  21. ref = parse_url("https://makerworld.com/en/models/1400373-self-watering-seed-starter")
  22. assert ref.external_id == "1400373"
  23. assert ref.sub_id is None
  24. def test_extracts_profile_id_from_fragment(self):
  25. ref = parse_url("https://makerworld.com/en/models/1400373-slug#profileId-1452154")
  26. assert ref.external_id == "1400373"
  27. assert ref.sub_id == "1452154"
  28. def test_accepts_scheme_omitted(self):
  29. ref = parse_url("makerworld.com/models/999")
  30. assert ref.external_id == "999"
  31. assert ref.sub_id is None
  32. def test_accepts_subdomain(self):
  33. # Defensive: if MakerWorld ever stands up a regional subdomain, still accept it
  34. ref = parse_url("https://www.makerworld.com/en/models/42")
  35. assert ref.external_id == "42"
  36. assert ref.sub_id is None
  37. def test_rejects_non_makerworld_host(self):
  38. with pytest.raises(MakerWorldUrlError):
  39. 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. parse_url("https://makerworld.com/en/creators/foo")
  44. def test_rejects_empty(self):
  45. with pytest.raises(MakerWorldUrlError):
  46. 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 TestResolve:
  222. """``resolve`` — the interface-level "URL → metadata + plate list" flow the
  223. /makerworld/resolve route drives. The per-instance printer-compatibility
  224. merge lives here (not in the route) so every future provider gets it from
  225. its own ``resolve`` implementation."""
  226. @pytest.fixture
  227. def service(self):
  228. return MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  229. @pytest.mark.asyncio
  230. async def test_merges_compatibility_from_design_into_instances(self, service):
  231. """Per-instance printer compatibility info lives on
  232. ``design.instances[].extention.modelInfo`` but not on
  233. ``/instances/hits``. Resolve enriches each hit with both
  234. ``compatibility`` (primary printer the instance was sliced for) and
  235. ``otherCompatibility`` (extra printers the uploader marked it
  236. compatible with) so the frontend can show "sliced for A1 / also
  237. marked compatible with: H2D, P1S".
  238. """
  239. design_payload = {
  240. "id": 1400373,
  241. "title": "Seed Starter",
  242. "instances": [
  243. {
  244. "id": 1452154,
  245. "extention": {
  246. "modelInfo": {
  247. "compatibility": ["A1"],
  248. "otherCompatibility": ["H2D", "P1S"],
  249. }
  250. },
  251. },
  252. {
  253. "id": 1452158,
  254. "extention": {
  255. "modelInfo": {
  256. "compatibility": ["X1 Carbon"],
  257. "otherCompatibility": [],
  258. }
  259. },
  260. },
  261. ],
  262. }
  263. instances_payload = {
  264. "total": 2,
  265. "hits": [
  266. {"id": 1452154, "profileId": 298919107, "title": "9 cells"},
  267. {"id": 1452158, "profileId": 298919564, "title": "12 cells"},
  268. ],
  269. }
  270. service.get_design = AsyncMock(return_value=design_payload)
  271. service.get_design_instances = AsyncMock(return_value=instances_payload)
  272. resolved = await service.resolve(ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  273. by_id = {i["id"]: i for i in resolved.instances}
  274. assert by_id[1452154]["compatibility"] == ["A1"]
  275. assert by_id[1452154]["otherCompatibility"] == ["H2D", "P1S"]
  276. assert by_id[1452158]["compatibility"] == ["X1 Carbon"]
  277. assert by_id[1452158]["otherCompatibility"] == []
  278. assert resolved.design == design_payload
  279. @pytest.mark.asyncio
  280. async def test_handles_missing_compatibility_gracefully(self, service):
  281. """Older designs (or hits without a matching design.instances entry)
  282. must not crash resolve — they just don't get the compat fields."""
  283. design_payload = {"id": 1400373, "instances": [{"id": 1452154}]} # no extention
  284. instances_payload = {
  285. "total": 2,
  286. "hits": [
  287. {"id": 1452154, "profileId": 298919107},
  288. {"id": 9999999, "profileId": 298919999}, # no design.instances match
  289. ],
  290. }
  291. service.get_design = AsyncMock(return_value=design_payload)
  292. service.get_design_instances = AsyncMock(return_value=instances_payload)
  293. resolved = await service.resolve(ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  294. # First instance: design entry exists but no extention → fields absent or None.
  295. first = next(i for i in resolved.instances if i["id"] == 1452154)
  296. assert first.get("compatibility") is None
  297. assert first.get("otherCompatibility") is None
  298. # Second instance: no design entry at all → no enrichment, no crash.
  299. second = next(i for i in resolved.instances if i["id"] == 9999999)
  300. assert "compatibility" not in second or second["compatibility"] is None
  301. @pytest.mark.asyncio
  302. async def test_normalises_null_and_non_list_hits_to_empty(self, service):
  303. service.get_design = AsyncMock(return_value={"id": 1400373})
  304. service.get_design_instances = AsyncMock(return_value={"total": 0, "hits": None})
  305. resolved = await service.resolve(ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  306. assert resolved.instances == []
  307. class TestGetDownload:
  308. """``get_download`` — the interface-level "resource → signed 3MF URL"
  309. flow the /makerworld/import route drives. The profile falls back in two
  310. tiers; the link comes from the instance behind the profile, and from the
  311. iot-service profile endpoint (which needs the *alphanumeric* modelId, not
  312. the integer design id) only when that gives none (#3447, #3448). Malformed
  313. upstream shapes map to UnavailableError (502)."""
  314. @pytest.fixture
  315. def service(self):
  316. return MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  317. def _design(self, **overrides):
  318. design = {
  319. "id": 1400373,
  320. "modelId": "US2bb73b106683e5",
  321. "instances": [{"id": 4028000, "profileId": 298919107, "title": "9 cells"}],
  322. }
  323. design.update(overrides)
  324. return design
  325. def _manifest(self, url="https://makerworld.bblmw.com/x.3mf?exp=1", name="benchy.3mf"):
  326. return {"url": url, "name": name}
  327. async def _run(self, service, ref):
  328. return await service.get_download(ref)
  329. @pytest.mark.asyncio
  330. async def test_the_link_comes_from_the_instance_behind_the_profile(self, service):
  331. """Explicit profile_id: its instance is asked, the profile endpoint is not."""
  332. service.get_design = AsyncMock(
  333. return_value=self._design(
  334. instances=[{"id": 1, "profileId": 5}, {"id": 4028000, "profileId": 298919107}],
  335. )
  336. )
  337. manifest = self._manifest()
  338. service.get_instance_download = AsyncMock(return_value=manifest)
  339. service.get_profile_download = AsyncMock()
  340. info = await self._run(
  341. service, ProviderResourceRef(source_type="makerworld", external_id="1400373", sub_id="298919107")
  342. )
  343. service.get_instance_download.assert_awaited_once_with(4028000)
  344. service.get_profile_download.assert_not_awaited()
  345. assert info.url == manifest["url"]
  346. assert info.suggested_filename == "benchy.3mf"
  347. # The enriched ref carries the resolved profile for the dedupe key.
  348. assert info.ref.sub_id == "298919107"
  349. @pytest.mark.asyncio
  350. async def test_falls_back_to_first_design_instance_profile(self, service):
  351. """No profile given → first ``design.instances[].profileId`` wins."""
  352. service.get_design = AsyncMock(return_value=self._design())
  353. service.get_instance_download = AsyncMock(return_value=self._manifest())
  354. info = await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  355. service.get_instance_download.assert_awaited_once_with(4028000)
  356. assert info.ref.sub_id == "298919107"
  357. @pytest.mark.asyncio
  358. async def test_second_tier_falls_back_to_instances_envelope(self, service):
  359. """Design carries no usable profileId → the ``/design/{id}/instances``
  360. envelope is consulted before giving up, once, for the instance too."""
  361. service.get_design = AsyncMock(return_value=self._design(instances=[{"title": "no profileId here"}]))
  362. service.get_design_instances = AsyncMock(
  363. return_value={"total": 1, "hits": [{"id": 4028001, "profileId": 298919564}]}
  364. )
  365. service.get_instance_download = AsyncMock(return_value=self._manifest())
  366. info = await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  367. service.get_design_instances.assert_awaited_once_with(1400373)
  368. service.get_instance_download.assert_awaited_once_with(4028001)
  369. assert info.ref.sub_id == "298919564"
  370. @pytest.mark.asyncio
  371. async def test_an_instance_the_design_lists_without_id_is_found_in_the_envelope(self, service):
  372. service.get_design = AsyncMock(return_value=self._design(instances=[{"profileId": 298919107}]))
  373. service.get_design_instances = AsyncMock(
  374. return_value={"total": 2, "hits": [{"id": 1, "profileId": 5}, {"id": 4028000, "profileId": 298919107}]}
  375. )
  376. service.get_instance_download = AsyncMock(return_value=self._manifest())
  377. await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  378. service.get_instance_download.assert_awaited_once_with(4028000)
  379. @pytest.mark.asyncio
  380. async def test_no_link_from_the_instance_asks_the_profile(self, service):
  381. """The profile endpoint gets the alphanumeric modelId, not the integer id."""
  382. service.get_design = AsyncMock(return_value=self._design())
  383. service.get_instance_download = AsyncMock(return_value={"name": "x.3mf", "url": ""})
  384. manifest = self._manifest(name="from-profile.3mf")
  385. service.get_profile_download = AsyncMock(return_value=manifest)
  386. info = await self._run(
  387. service, ProviderResourceRef(source_type="makerworld", external_id="1400373", sub_id="298919107")
  388. )
  389. service.get_profile_download.assert_awaited_once_with(298919107, "US2bb73b106683e5")
  390. assert info.url == manifest["url"]
  391. assert info.suggested_filename == "from-profile.3mf"
  392. @pytest.mark.asyncio
  393. async def test_a_profile_no_instance_lists_asks_the_profile(self, service):
  394. service.get_design = AsyncMock(return_value=self._design())
  395. service.get_design_instances = AsyncMock(return_value={"total": 0, "hits": []})
  396. service.get_instance_download = AsyncMock()
  397. service.get_profile_download = AsyncMock(return_value=self._manifest())
  398. info = await self._run(
  399. service, ProviderResourceRef(source_type="makerworld", external_id="1400373", sub_id="777")
  400. )
  401. service.get_instance_download.assert_not_awaited()
  402. service.get_profile_download.assert_awaited_once_with(777, "US2bb73b106683e5")
  403. assert info.ref.sub_id == "777"
  404. @pytest.mark.asyncio
  405. async def test_the_instance_link_needs_no_model_id(self, service):
  406. service.get_design = AsyncMock(return_value=self._design(modelId=None))
  407. service.get_instance_download = AsyncMock(return_value=self._manifest())
  408. info = await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  409. assert info.url == self._manifest()["url"]
  410. @pytest.mark.asyncio
  411. async def test_missing_alphanumeric_model_id_is_unavailable(self, service):
  412. """No link from the instance, and a design without the ``modelId``
  413. field can't reach iot-service."""
  414. service.get_design = AsyncMock(return_value=self._design(modelId=None))
  415. service.get_instance_download = AsyncMock(return_value={"url": ""})
  416. with pytest.raises(MakerWorldUnavailableError, match="modelId"):
  417. await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  418. @pytest.mark.asyncio
  419. async def test_no_profiles_anywhere_is_unavailable(self, service):
  420. service.get_design = AsyncMock(return_value=self._design(instances=[]))
  421. service.get_design_instances = AsyncMock(return_value={"total": 0, "hits": []})
  422. with pytest.raises(MakerWorldUnavailableError, match="no instances"):
  423. await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  424. @pytest.mark.asyncio
  425. async def test_a_refusal_from_the_instance_is_not_retried_on_the_profile(self, service):
  426. """Bambu's reason (paid, points, region) reaches the user rather than
  427. the profile endpoint's empty link."""
  428. service.get_design = AsyncMock(return_value=self._design())
  429. service.get_instance_download = AsyncMock(side_effect=MakerWorldForbiddenError("paid model"))
  430. service.get_profile_download = AsyncMock()
  431. with pytest.raises(MakerWorldForbiddenError, match="paid model"):
  432. await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  433. service.get_profile_download.assert_not_awaited()
  434. @pytest.mark.asyncio
  435. async def test_no_link_from_either_is_unavailable(self, service):
  436. """The reports: the profile answers with ``url: ""``, and here the instance does too."""
  437. service.get_design = AsyncMock(return_value=self._design())
  438. service.get_instance_download = AsyncMock(return_value={"name": "benchy.3mf"})
  439. service.get_profile_download = AsyncMock(return_value={"name": "benchy.3mf", "url": ""})
  440. with pytest.raises(MakerWorldUnavailableError, match="download URL"):
  441. await self._run(service, ProviderResourceRef(source_type="makerworld", external_id="1400373"))
  442. class TestGetProfileDownload:
  443. """The auth-gated 3MF manifest endpoint on the Bambu iot-service.
  444. YASTL#51's endpoint minted the signed CDN URL from the same long-lived
  445. Bambu Cloud bearer users already have; since 2026-11-03 it answers with
  446. an empty ``url`` and is only the fallback behind the instance endpoint.
  447. """
  448. def _make_service(self, *, auth_token: str | None = "tok-abc") -> MakerWorldService:
  449. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token=auth_token)
  450. svc._client.get = AsyncMock()
  451. return svc
  452. @pytest.mark.asyncio
  453. async def test_requires_auth_token(self):
  454. svc = self._make_service(auth_token=None)
  455. with pytest.raises(MakerWorldAuthError):
  456. await svc.get_profile_download(1452154, "US2bb73b106683e5")
  457. @pytest.mark.asyncio
  458. async def test_returns_signed_manifest(self):
  459. svc = self._make_service()
  460. resp = MagicMock()
  461. resp.status_code = 200
  462. resp.json.return_value = {
  463. "name": "benchy.3mf",
  464. "url": "https://makerworld.bblmw.com/makerworld/model/X/Y/f.3mf?exp=1&key=k",
  465. }
  466. svc._client.get.return_value = resp
  467. manifest = await svc.get_profile_download(1452154, "US2bb73b106683e5")
  468. assert manifest["url"].startswith("https://makerworld.bblmw.com/")
  469. assert manifest["name"] == "benchy.3mf"
  470. @pytest.mark.asyncio
  471. async def test_sends_bearer_and_model_id_query(self):
  472. """Auth goes in ``Authorization`` and the alphanumeric modelId as a
  473. ``model_id`` query param — this is what YASTL#51 reverse-engineered."""
  474. svc = self._make_service(auth_token="tok-abc")
  475. resp = MagicMock()
  476. resp.status_code = 200
  477. resp.json.return_value = {"url": "https://makerworld.bblmw.com/x.3mf"}
  478. svc._client.get.return_value = resp
  479. await svc.get_profile_download(1452154, "US2bb73b106683e5")
  480. call = svc._client.get.call_args
  481. url = call.args[0] if call.args else call.kwargs.get("url")
  482. assert url == "https://api.bambulab.com/v1/iot-service/api/user/profile/1452154"
  483. assert call.kwargs["headers"]["Authorization"] == "Bearer tok-abc"
  484. assert call.kwargs["params"] == {"model_id": "US2bb73b106683e5"}
  485. @pytest.mark.asyncio
  486. async def test_maps_401_to_auth_error(self):
  487. svc = self._make_service()
  488. resp = MagicMock()
  489. resp.status_code = 401
  490. resp.json.return_value = {"error": "token expired"}
  491. svc._client.get.return_value = resp
  492. with pytest.raises(MakerWorldAuthError):
  493. await svc.get_profile_download(1, "M1")
  494. @pytest.mark.asyncio
  495. async def test_maps_403_to_forbidden(self):
  496. svc = self._make_service()
  497. resp = MagicMock()
  498. resp.status_code = 403
  499. resp.json.return_value = {"error": "paid model"}
  500. svc._client.get.return_value = resp
  501. with pytest.raises(MakerWorldForbiddenError) as exc_info:
  502. await svc.get_profile_download(1, "M1")
  503. assert "paid model" in str(exc_info.value)
  504. @pytest.mark.asyncio
  505. async def test_maps_404_to_not_found(self):
  506. svc = self._make_service()
  507. resp = MagicMock()
  508. resp.status_code = 404
  509. svc._client.get.return_value = resp
  510. with pytest.raises(MakerWorldNotFoundError):
  511. await svc.get_profile_download(1, "M1")
  512. @pytest.mark.asyncio
  513. async def test_maps_timeout_to_unavailable(self):
  514. svc = self._make_service()
  515. svc._client.get.side_effect = httpx.TimeoutException("nope")
  516. with pytest.raises(MakerWorldUnavailableError):
  517. await svc.get_profile_download(1, "M1")
  518. @pytest.mark.asyncio
  519. async def test_rejects_non_dict_json(self):
  520. svc = self._make_service()
  521. resp = MagicMock()
  522. resp.status_code = 200
  523. resp.json.return_value = ["not", "a", "dict"]
  524. svc._client.get.return_value = resp
  525. with pytest.raises(MakerWorldUnavailableError):
  526. await svc.get_profile_download(1, "M1")
  527. class TestGetInstanceDownload:
  528. """The design-service instance endpoint on ``api.bambulab.com`` that
  529. mints the signed URL since the profile endpoint stopped (#3447, #3448).
  530. Same bearer, same status mapping, the resource named as an instance."""
  531. def _make_service(self, *, auth_token: str | None = "tok-abc") -> MakerWorldService:
  532. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token=auth_token)
  533. svc._client.get = AsyncMock()
  534. return svc
  535. def _respond(self, svc, status, body=None):
  536. resp = MagicMock()
  537. resp.status_code = status
  538. resp.json.return_value = body if body is not None else {}
  539. svc._client.get.return_value = resp
  540. @pytest.mark.asyncio
  541. async def test_requires_auth_token(self):
  542. svc = self._make_service(auth_token=None)
  543. with pytest.raises(MakerWorldAuthError):
  544. await svc.get_instance_download(4028000)
  545. svc._client.get.assert_not_awaited()
  546. @pytest.mark.asyncio
  547. async def test_sends_bearer_and_type_download(self):
  548. svc = self._make_service(auth_token="tok-abc")
  549. self._respond(
  550. svc, 200, {"name": "m.3mf", "url": "https://makerworld.bblmw.com/m.3mf", "highCompression": False}
  551. )
  552. manifest = await svc.get_instance_download(4028000)
  553. call = svc._client.get.call_args
  554. url = call.args[0] if call.args else call.kwargs.get("url")
  555. assert url == "https://api.bambulab.com/v1/design-service/instance/4028000/f3mf"
  556. assert call.kwargs["headers"]["Authorization"] == "Bearer tok-abc"
  557. assert call.kwargs["params"] == {"type": "download"}
  558. assert manifest["name"] == "m.3mf"
  559. @pytest.mark.asyncio
  560. async def test_maps_401_to_auth_error(self):
  561. svc = self._make_service()
  562. self._respond(svc, 401, {"error": "token expired"})
  563. with pytest.raises(MakerWorldAuthError):
  564. await svc.get_instance_download(4028000)
  565. @pytest.mark.asyncio
  566. async def test_an_expired_sign_in_is_noted(self):
  567. """The same sign-out as every other MakerWorld call (``_note_auth_failure``)."""
  568. svc = self._make_service()
  569. svc._note_auth_failure = AsyncMock()
  570. self._respond(svc, 401, {"code": 4, "error": "Please login."})
  571. with pytest.raises(MakerWorldAuthError):
  572. await svc.get_instance_download(4028000)
  573. svc._note_auth_failure.assert_awaited_once_with(svc._client.get.return_value)
  574. @pytest.mark.asyncio
  575. async def test_maps_403_to_forbidden_naming_the_instance(self):
  576. svc = self._make_service()
  577. self._respond(svc, 403, {})
  578. with pytest.raises(MakerWorldForbiddenError, match="instance 4028000"):
  579. await svc.get_instance_download(4028000)
  580. @pytest.mark.asyncio
  581. async def test_maps_404_to_not_found_naming_the_instance(self):
  582. svc = self._make_service()
  583. self._respond(svc, 404)
  584. with pytest.raises(MakerWorldNotFoundError, match="instance not found: 4028000"):
  585. await svc.get_instance_download(4028000)
  586. @pytest.mark.asyncio
  587. async def test_other_status_is_unavailable(self):
  588. svc = self._make_service()
  589. self._respond(svc, 500)
  590. with pytest.raises(MakerWorldUnavailableError, match="for instance 4028000"):
  591. await svc.get_instance_download(4028000)
  592. class TestDownload3MF:
  593. """SSRF guard + size cap + streaming behaviour."""
  594. def _stream_ctx(self, resp):
  595. ctx = MagicMock()
  596. ctx.__aenter__ = AsyncMock(return_value=resp)
  597. ctx.__aexit__ = AsyncMock(return_value=None)
  598. return ctx
  599. @pytest.mark.asyncio
  600. @pytest.mark.parametrize(
  601. "url",
  602. [
  603. "https://example.com/steal.3mf",
  604. "https://169.254.169.254/meta", # EC2 metadata
  605. "http://internal.host/loot",
  606. "http://127.0.0.1/loot",
  607. ],
  608. )
  609. async def test_rejects_non_allowed_hosts(self, url):
  610. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  611. with pytest.raises(MakerWorldUrlError):
  612. await svc.download_3mf(url)
  613. @pytest.mark.asyncio
  614. async def test_download_allowlist_is_driven_by_injected_hosts(self):
  615. """``download_hosts`` is the SSRF seam, not a hardcoded constant (review
  616. round 3 note 2). ``build_service`` passes ``ModelProvider.download_hosts()``
  617. into ``MakerWorldService`` — prove the injection is live by accepting a
  618. host inside a custom allowlist and refusing a MakerWorld CDN host that
  619. isn't in it."""
  620. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), download_hosts=("cdn.example.com",))
  621. resp = MagicMock()
  622. resp.status_code = 200
  623. async def _chunks():
  624. yield b"PK\x03\x04"
  625. resp.aiter_bytes = lambda: _chunks()
  626. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  627. payload, _ = await svc.download_3mf("https://cdn.example.com/m/foo.3mf?exp=1&key=k")
  628. assert payload == b"PK\x03\x04"
  629. with pytest.raises(MakerWorldUrlError):
  630. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  631. @pytest.mark.asyncio
  632. async def test_s3_suffix_family_is_allowed_regardless_of_injected_hosts(self):
  633. """``_ALLOWED_DOWNLOAD_SUFFIXES`` is deliberately outside the
  634. ``download_hosts()`` seam: Bambu's presigned S3 endpoints are this
  635. provider's own signed-URL family, not an exact-host allowlist a
  636. provider declares. Pinned so narrowing the injected hosts can never
  637. silently take the S3 download path with it."""
  638. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), download_hosts=("cdn.example.com",))
  639. with patch(
  640. "backend.app.services.model_providers.makerworld.service._download_s3_urllib",
  641. AsyncMock(return_value=(b"PK\x03\x04", "plate.3mf")),
  642. ) as s3:
  643. payload, name = await svc.download_3mf("https://s3.us-west-2.amazonaws.com/bucket/plate.3mf?sig=1")
  644. assert payload == b"PK\x03\x04"
  645. assert name == "plate.3mf"
  646. assert s3.await_count == 1
  647. @pytest.mark.asyncio
  648. async def test_s3_host_delegates_to_urllib_path(self):
  649. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  650. with patch(
  651. "backend.app.services.model_providers.makerworld.service._download_s3_urllib",
  652. new=AsyncMock(return_value=(b"payload", "file.3mf")),
  653. ) as mocked:
  654. payload, filename = await svc.download_3mf(
  655. "https://s3.us-west-2.amazonaws.com/bucket/key/file.3mf?X-Amz-Signature=abc"
  656. )
  657. mocked.assert_awaited_once()
  658. # First arg is the verbatim URL — must NOT be round-tripped through
  659. # httpx/urlparse.urlencode since that breaks S3 SigV4.
  660. args = mocked.await_args.args
  661. assert args[0] == ("https://s3.us-west-2.amazonaws.com/bucket/key/file.3mf?X-Amz-Signature=abc")
  662. assert payload == b"payload"
  663. assert filename == "file.3mf"
  664. @pytest.mark.asyncio
  665. async def test_cdn_url_uses_httpx_with_minimal_headers(self):
  666. """Signed CDN URLs already carry the auth in the query string — don't
  667. leak the Bambu Cloud bearer to the CDN too. The client is reduced to a
  668. single ``User-Agent`` header; no ``Authorization``, no ``x-bbl-*``."""
  669. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient), auth_token="tok-abc")
  670. resp = MagicMock()
  671. resp.status_code = 200
  672. async def _chunks():
  673. yield b"PK\x03\x04"
  674. resp.aiter_bytes = lambda: _chunks()
  675. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  676. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  677. call = svc._client.stream.call_args
  678. headers = call.kwargs["headers"]
  679. # Minimal: UA only. No bearer to the CDN.
  680. assert "Authorization" not in headers
  681. assert all(not k.startswith("x-bbl") for k in headers)
  682. assert "User-Agent" in headers
  683. # Redirects off — host allowlist is only meaningful on the initial URL.
  684. assert call.kwargs["follow_redirects"] is False
  685. @pytest.mark.asyncio
  686. async def test_happy_path_streams_bytes(self):
  687. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  688. resp = MagicMock()
  689. resp.status_code = 200
  690. async def _chunks():
  691. yield b"PK\x03\x04" # 3MF = zip magic
  692. yield b"rest of file"
  693. resp.aiter_bytes = lambda: _chunks()
  694. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  695. payload, filename = await svc.download_3mf(
  696. "https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k"
  697. )
  698. assert payload.startswith(b"PK\x03\x04")
  699. assert filename == "foo.3mf"
  700. @pytest.mark.asyncio
  701. async def test_http_error_on_cdn_path_raises_unavailable(self):
  702. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  703. resp = MagicMock()
  704. resp.status_code = 500
  705. resp.aiter_bytes = lambda: (_ for _ in ())
  706. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  707. with pytest.raises(MakerWorldUnavailableError):
  708. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  709. @pytest.mark.asyncio
  710. async def test_exceeds_size_cap_raises(self):
  711. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  712. resp = MagicMock()
  713. resp.status_code = 200
  714. # Cap is 200 MB — emit one "chunk" that reports exceeding it.
  715. oversized = _MAX_3MF_BYTES + 1
  716. async def _chunks():
  717. # Emit a bytes object whose ``len()`` is oversized, without
  718. # actually allocating 200 MB in the test process.
  719. yield b"\x00" * oversized
  720. resp.aiter_bytes = lambda: _chunks()
  721. svc._client.stream = MagicMock(return_value=self._stream_ctx(resp))
  722. with pytest.raises(MakerWorldUnavailableError, match="cap"):
  723. await svc.download_3mf("https://makerworld.bblmw.com/makerworld/model/X/Y/foo.3mf?exp=1&key=k")
  724. class TestS3UrllibDownload:
  725. """Module-level ``_download_s3_urllib`` — the verbatim-URL path for S3."""
  726. @pytest.mark.asyncio
  727. async def test_returns_bytes_and_filename(self):
  728. from backend.app.services.model_providers.makerworld.http import _download_s3_urllib
  729. fake_resp = MagicMock()
  730. fake_resp.status = 200
  731. # Simulate urllib's file-like ``read(n)`` interface.
  732. fake_resp.read = MagicMock(side_effect=[b"hello", b""])
  733. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  734. fake_resp.__exit__ = MagicMock(return_value=None)
  735. fake_opener = MagicMock()
  736. fake_opener.open = MagicMock(return_value=fake_resp)
  737. with patch("urllib.request.build_opener", return_value=fake_opener):
  738. data, filename = await _download_s3_urllib(
  739. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  740. "fallback.3mf",
  741. )
  742. assert data == b"hello"
  743. assert filename == "fallback.3mf"
  744. @pytest.mark.asyncio
  745. async def test_redirect_is_treated_as_error(self):
  746. """The ``_NoRedirect`` handler returns ``None`` from ``redirect_request``,
  747. which makes ``urllib`` raise ``HTTPError`` instead of following. The
  748. wrapper must surface that as ``MakerWorldUnavailableError``."""
  749. from backend.app.services.model_providers.makerworld.http import _download_s3_urllib
  750. fake_opener = MagicMock()
  751. fake_opener.open = MagicMock(
  752. side_effect=HTTPError(
  753. "https://s3.example/redirect",
  754. 302,
  755. "Found",
  756. {}, # type: ignore[arg-type]
  757. None,
  758. )
  759. )
  760. with (
  761. patch("urllib.request.build_opener", return_value=fake_opener),
  762. pytest.raises(MakerWorldUnavailableError),
  763. ):
  764. await _download_s3_urllib(
  765. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  766. "fallback.3mf",
  767. )
  768. @pytest.mark.asyncio
  769. async def test_non_200_raises_unavailable(self):
  770. from backend.app.services.model_providers.makerworld.http import _download_s3_urllib
  771. fake_resp = MagicMock()
  772. fake_resp.status = 403
  773. fake_resp.read = MagicMock(return_value=b"")
  774. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  775. fake_resp.__exit__ = MagicMock(return_value=None)
  776. fake_opener = MagicMock()
  777. fake_opener.open = MagicMock(return_value=fake_resp)
  778. with (
  779. patch("urllib.request.build_opener", return_value=fake_opener),
  780. pytest.raises(MakerWorldUnavailableError),
  781. ):
  782. await _download_s3_urllib(
  783. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  784. "fallback.3mf",
  785. )
  786. @pytest.mark.asyncio
  787. async def test_size_cap_enforced(self):
  788. from backend.app.services.model_providers.makerworld.http import _download_s3_urllib
  789. fake_resp = MagicMock()
  790. fake_resp.status = 200
  791. # A single oversized chunk trips the cap on the first iteration.
  792. fake_resp.read = MagicMock(side_effect=[b"\x00" * (_MAX_3MF_BYTES + 1), b""])
  793. fake_resp.__enter__ = MagicMock(return_value=fake_resp)
  794. fake_resp.__exit__ = MagicMock(return_value=None)
  795. fake_opener = MagicMock()
  796. fake_opener.open = MagicMock(return_value=fake_resp)
  797. with (
  798. patch("urllib.request.build_opener", return_value=fake_opener),
  799. pytest.raises(MakerWorldUnavailableError, match="cap"),
  800. ):
  801. await _download_s3_urllib(
  802. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  803. "fallback.3mf",
  804. )
  805. @pytest.mark.asyncio
  806. async def test_network_error_mapped_to_unavailable(self):
  807. from backend.app.services.model_providers.makerworld.http import _download_s3_urllib
  808. fake_opener = MagicMock()
  809. fake_opener.open = MagicMock(side_effect=URLError("dns fail"))
  810. with (
  811. patch("urllib.request.build_opener", return_value=fake_opener),
  812. pytest.raises(MakerWorldUnavailableError),
  813. ):
  814. await _download_s3_urllib(
  815. "https://s3.us-west-2.amazonaws.com/b/k/file.3mf?sig=abc",
  816. "fallback.3mf",
  817. )
  818. class TestFetchThumbnail:
  819. """Proxy the CDN thumbnails so img-src CSP doesn't need to allow external hosts."""
  820. @pytest.fixture
  821. def service(self):
  822. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  823. svc._client.get = AsyncMock()
  824. return svc
  825. @pytest.mark.asyncio
  826. async def test_rejects_non_cdn_host(self, service):
  827. with pytest.raises(MakerWorldUrlError):
  828. await service.fetch_thumbnail("https://evil.example.com/img.jpg")
  829. @pytest.mark.asyncio
  830. async def test_rejects_loopback(self, service):
  831. # SSRF: don't let anyone abuse this as an open proxy toward 127.0.0.1
  832. with pytest.raises(MakerWorldUrlError):
  833. await service.fetch_thumbnail("http://127.0.0.1/secret.jpg")
  834. @pytest.mark.asyncio
  835. async def test_does_not_follow_redirects(self, service):
  836. """Host allowlist is only enforced on the initial URL — a 302 from the
  837. CDN to any other host would otherwise bypass the allowlist. ``follow_
  838. redirects=False`` pins that behaviour in the wire contract."""
  839. resp = MagicMock()
  840. resp.status_code = 200
  841. resp.headers = {"content-type": "image/jpeg"}
  842. resp.content = b"\xff\xd8\xff\xe0JFIF"
  843. service._client.get.return_value = resp
  844. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/cover.jpg")
  845. assert service._client.get.call_args.kwargs["follow_redirects"] is False
  846. @pytest.mark.asyncio
  847. async def test_rejects_html_content_type_even_with_image_extension(self, service):
  848. # An upstream error page (HTML) at a .jpg URL must be refused —
  849. # otherwise we'd forward it to the browser under an image framing.
  850. resp = MagicMock()
  851. resp.status_code = 200
  852. resp.headers = {"content-type": "text/html"}
  853. resp.content = b"<html>error page</html>"
  854. service._client.get.return_value = resp
  855. with pytest.raises(MakerWorldUnavailableError):
  856. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/cover.jpg")
  857. @pytest.mark.asyncio
  858. async def test_happy_path_with_proper_image_content_type(self, service):
  859. resp = MagicMock()
  860. resp.status_code = 200
  861. resp.headers = {"content-type": "image/jpeg; charset=binary"}
  862. resp.content = b"\xff\xd8\xff\xe0JFIF" # JPEG magic bytes
  863. service._client.get.return_value = resp
  864. payload, content_type = await service.fetch_thumbnail(
  865. "https://makerworld.bblmw.com/makerworld/model/X/cover.jpg"
  866. )
  867. assert payload == b"\xff\xd8\xff\xe0JFIF"
  868. # Semi-colon params stripped
  869. assert content_type == "image/jpeg"
  870. @pytest.mark.asyncio
  871. async def test_infers_mime_from_extension_when_cdn_lies(self, service):
  872. """MakerWorld's CDN returns application/octet-stream for real PNG/JPG
  873. files. Relying on upstream content-type alone would fail every
  874. thumbnail request; fall back to the URL extension."""
  875. resp = MagicMock()
  876. resp.status_code = 200
  877. resp.headers = {"content-type": "application/octet-stream"}
  878. resp.content = b"\x89PNG\r\n\x1a\n" # PNG magic bytes
  879. service._client.get.return_value = resp
  880. payload, content_type = await service.fetch_thumbnail(
  881. "https://makerworld.bblmw.com/makerworld/model/X/design/abc.png"
  882. )
  883. assert payload.startswith(b"\x89PNG")
  884. assert content_type == "image/png"
  885. @pytest.mark.asyncio
  886. async def test_refuses_when_no_extension_and_non_image_type(self, service):
  887. """If the URL carries no image extension AND upstream doesn't declare
  888. image/*, we can't confidently serve it as an image — refuse."""
  889. resp = MagicMock()
  890. resp.status_code = 200
  891. resp.headers = {"content-type": "application/octet-stream"}
  892. resp.content = b"who knows what this is"
  893. service._client.get.return_value = resp
  894. with pytest.raises(MakerWorldUnavailableError):
  895. await service.fetch_thumbnail("https://makerworld.bblmw.com/makerworld/model/X/blob")
  896. class TestSharedHttpClient:
  897. """The app-scoped httpx client registered via ``set_shared_http_client``
  898. must be reused by per-request services (one shared connection pool, same
  899. pattern as ``bambu_cloud``). The setter has to live in the same module as
  900. the service class, or the import-time snapshot never sees the lifespan's
  901. late registration and every request spins up its own client."""
  902. @pytest.mark.asyncio
  903. async def test_reuses_registered_client(self):
  904. client = MagicMock(spec=httpx.AsyncClient)
  905. set_shared_http_client(client)
  906. try:
  907. svc = MakerWorldService()
  908. assert svc._client is client
  909. assert svc._owns_client is False
  910. # close() must NOT close a client it doesn't own
  911. await svc.close()
  912. client.aclose.assert_not_called()
  913. finally:
  914. set_shared_http_client(None)
  915. @pytest.mark.asyncio
  916. async def test_creates_and_owns_own_client_when_none_registered(self):
  917. set_shared_http_client(None)
  918. svc = MakerWorldService()
  919. assert svc._owns_client is True
  920. await svc.close()
  921. assert svc._client.is_closed
  922. class TestADownloadIsAZip:
  923. """Only the status code was checked, so a truncated body or an error page
  924. served with 200 was stored as the model's 3MF and kept."""
  925. @staticmethod
  926. def _info():
  927. from backend.app.services.model_providers.base import ProviderDownloadInfo
  928. return ProviderDownloadInfo(
  929. ref=ProviderResourceRef(source_type="makerworld", external_id="1"),
  930. url="https://makerworld.bblmw.com/f.3mf",
  931. suggested_filename="f.3mf",
  932. )
  933. @pytest.mark.asyncio
  934. @pytest.mark.parametrize("body", [b"<html>Access denied</html>", b"PK\x03\x04truncated"])
  935. async def test_a_body_that_is_not_a_zip_is_refused(self, body):
  936. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  937. svc.download_3mf = AsyncMock(return_value=(body, "f.3mf"))
  938. with pytest.raises(MakerWorldUnavailableError, match="not a valid 3MF"):
  939. await svc.download(self._info())
  940. @pytest.mark.asyncio
  941. async def test_a_zip_is_returned(self):
  942. import io
  943. import zipfile
  944. buffer = io.BytesIO()
  945. with zipfile.ZipFile(buffer, "w") as zf:
  946. zf.writestr("3D/3dmodel.model", "<model/>")
  947. svc = MakerWorldService(client=MagicMock(spec=httpx.AsyncClient))
  948. svc.download_3mf = AsyncMock(return_value=(buffer.getvalue(), "f.3mf"))
  949. result = await svc.download(self._info())
  950. assert result.file_bytes == buffer.getvalue()