test_ownership_permissions.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. """Integration tests for ownership-based permission system.
  2. Tests the ownership permission model where users can have:
  3. - *_all permissions: can modify any item
  4. - *_own permissions: can only modify items they created
  5. - Ownerless items (created_by_id = null) require *_all permission
  6. """
  7. import pytest
  8. from httpx import AsyncClient
  9. class TestOwnershipPermissionsSetup:
  10. """Helper fixture class for ownership permission tests."""
  11. @pytest.fixture
  12. async def auth_setup(self, async_client: AsyncClient):
  13. """Setup auth with admin, create test users with different permission levels."""
  14. # Enable auth with admin user
  15. await async_client.post(
  16. "/api/v1/auth/setup",
  17. json={
  18. "auth_enabled": True,
  19. "admin_username": "ownershipadmin",
  20. "admin_password": "AdminPass1!",
  21. },
  22. )
  23. # Login as admin
  24. admin_login = await async_client.post(
  25. "/api/v1/auth/login",
  26. json={"username": "ownershipadmin", "password": "AdminPass1!"},
  27. )
  28. admin_token = admin_login.json()["access_token"]
  29. admin_user = admin_login.json()["user"]
  30. # Get group IDs
  31. groups_response = await async_client.get(
  32. "/api/v1/groups/",
  33. headers={"Authorization": f"Bearer {admin_token}"},
  34. )
  35. groups = groups_response.json()
  36. operators_group = next(g for g in groups if g["name"] == "Operators")
  37. viewers_group = next(g for g in groups if g["name"] == "Viewers")
  38. # Create operator user (has *_own permissions)
  39. operator_response = await async_client.post(
  40. "/api/v1/users/",
  41. headers={"Authorization": f"Bearer {admin_token}"},
  42. json={
  43. "username": "operator1",
  44. "password": "Operatorpass1!",
  45. "group_ids": [operators_group["id"]],
  46. },
  47. )
  48. operator_user = operator_response.json()
  49. # Login as operator
  50. operator_login = await async_client.post(
  51. "/api/v1/auth/login",
  52. json={"username": "operator1", "password": "Operatorpass1!"},
  53. )
  54. operator_token = operator_login.json()["access_token"]
  55. # Create second operator (for cross-user tests)
  56. operator2_response = await async_client.post(
  57. "/api/v1/users/",
  58. headers={"Authorization": f"Bearer {admin_token}"},
  59. json={
  60. "username": "operator2",
  61. "password": "Operatorpass1!",
  62. "group_ids": [operators_group["id"]],
  63. },
  64. )
  65. operator2_user = operator2_response.json()
  66. operator2_login = await async_client.post(
  67. "/api/v1/auth/login",
  68. json={"username": "operator2", "password": "Operatorpass1!"},
  69. )
  70. operator2_token = operator2_login.json()["access_token"]
  71. # Create viewer user (has no update/delete permissions)
  72. await async_client.post(
  73. "/api/v1/users/",
  74. headers={"Authorization": f"Bearer {admin_token}"},
  75. json={
  76. "username": "viewer1",
  77. "password": "Viewerpass1!",
  78. "group_ids": [viewers_group["id"]],
  79. },
  80. )
  81. viewer_login = await async_client.post(
  82. "/api/v1/auth/login",
  83. json={"username": "viewer1", "password": "Viewerpass1!"},
  84. )
  85. viewer_token = viewer_login.json()["access_token"]
  86. return {
  87. "admin_token": admin_token,
  88. "admin_user": admin_user,
  89. "operator_token": operator_token,
  90. "operator_user": operator_user,
  91. "operator2_token": operator2_token,
  92. "operator2_user": operator2_user,
  93. "viewer_token": viewer_token,
  94. }
  95. class TestArchiveOwnershipPermissions(TestOwnershipPermissionsSetup):
  96. """Tests for archive ownership-based permissions."""
  97. # ========================================================================
  98. # DELETE permissions
  99. # ========================================================================
  100. @pytest.mark.asyncio
  101. @pytest.mark.integration
  102. async def test_admin_can_delete_any_archive(
  103. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  104. ):
  105. """Admin with *_all permissions can delete any archive."""
  106. printer = await printer_factory()
  107. # Create archive owned by operator
  108. archive = await archive_factory(
  109. printer.id,
  110. print_name="Operator Archive",
  111. created_by_id=auth_setup["operator_user"]["id"],
  112. )
  113. # Admin deletes it
  114. response = await async_client.delete(
  115. f"/api/v1/archives/{archive.id}",
  116. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  117. )
  118. assert response.status_code == 200
  119. @pytest.mark.asyncio
  120. @pytest.mark.integration
  121. async def test_operator_can_delete_own_archive(
  122. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  123. ):
  124. """Operator with *_own permissions can delete their own archive."""
  125. printer = await printer_factory()
  126. archive = await archive_factory(
  127. printer.id,
  128. print_name="My Archive",
  129. created_by_id=auth_setup["operator_user"]["id"],
  130. )
  131. response = await async_client.delete(
  132. f"/api/v1/archives/{archive.id}",
  133. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  134. )
  135. assert response.status_code == 200
  136. @pytest.mark.asyncio
  137. @pytest.mark.integration
  138. async def test_operator_cannot_delete_others_archive(
  139. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  140. ):
  141. """Operator with *_own permissions cannot delete another user's archive."""
  142. printer = await printer_factory()
  143. # Archive created by operator2
  144. archive = await archive_factory(
  145. printer.id,
  146. print_name="Other's Archive",
  147. created_by_id=auth_setup["operator2_user"]["id"],
  148. )
  149. # operator1 tries to delete it
  150. response = await async_client.delete(
  151. f"/api/v1/archives/{archive.id}",
  152. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  153. )
  154. assert response.status_code == 403
  155. assert "your own" in response.json()["detail"].lower()
  156. @pytest.mark.asyncio
  157. @pytest.mark.integration
  158. async def test_operator_cannot_delete_ownerless_archive(
  159. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  160. ):
  161. """Operator with *_own permissions cannot delete ownerless archive."""
  162. printer = await printer_factory()
  163. # Archive with no owner (legacy data)
  164. archive = await archive_factory(
  165. printer.id,
  166. print_name="Ownerless Archive",
  167. created_by_id=None,
  168. )
  169. response = await async_client.delete(
  170. f"/api/v1/archives/{archive.id}",
  171. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  172. )
  173. assert response.status_code == 403
  174. @pytest.mark.asyncio
  175. @pytest.mark.integration
  176. async def test_viewer_cannot_delete_archive(
  177. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  178. ):
  179. """Viewer with no delete permissions cannot delete any archive."""
  180. printer = await printer_factory()
  181. archive = await archive_factory(printer.id, print_name="Any Archive")
  182. response = await async_client.delete(
  183. f"/api/v1/archives/{archive.id}",
  184. headers={"Authorization": f"Bearer {auth_setup['viewer_token']}"},
  185. )
  186. assert response.status_code == 403
  187. # ========================================================================
  188. # UPDATE permissions
  189. # ========================================================================
  190. @pytest.mark.asyncio
  191. @pytest.mark.integration
  192. async def test_admin_can_update_any_archive(
  193. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  194. ):
  195. """Admin can update any archive."""
  196. printer = await printer_factory()
  197. archive = await archive_factory(
  198. printer.id,
  199. print_name="Original Name",
  200. created_by_id=auth_setup["operator_user"]["id"],
  201. )
  202. response = await async_client.patch(
  203. f"/api/v1/archives/{archive.id}",
  204. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  205. json={"print_name": "Admin Updated"},
  206. )
  207. assert response.status_code == 200
  208. assert response.json()["print_name"] == "Admin Updated"
  209. @pytest.mark.asyncio
  210. @pytest.mark.integration
  211. async def test_operator_can_update_own_archive(
  212. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  213. ):
  214. """Operator can update their own archive."""
  215. printer = await printer_factory()
  216. archive = await archive_factory(
  217. printer.id,
  218. print_name="Original Name",
  219. created_by_id=auth_setup["operator_user"]["id"],
  220. )
  221. response = await async_client.patch(
  222. f"/api/v1/archives/{archive.id}",
  223. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  224. json={"print_name": "Operator Updated"},
  225. )
  226. assert response.status_code == 200
  227. assert response.json()["print_name"] == "Operator Updated"
  228. @pytest.mark.asyncio
  229. @pytest.mark.integration
  230. async def test_operator_cannot_update_others_archive(
  231. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  232. ):
  233. """Operator cannot update another user's archive."""
  234. printer = await printer_factory()
  235. archive = await archive_factory(
  236. printer.id,
  237. print_name="Other's Archive",
  238. created_by_id=auth_setup["operator2_user"]["id"],
  239. )
  240. response = await async_client.patch(
  241. f"/api/v1/archives/{archive.id}",
  242. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  243. json={"print_name": "Attempted Update"},
  244. )
  245. assert response.status_code == 403
  246. # ========================================================================
  247. # Legacy reprint endpoint
  248. # ========================================================================
  249. @pytest.mark.asyncio
  250. @pytest.mark.integration
  251. async def test_reprint_endpoint_is_gone_for_all_callers(
  252. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  253. ):
  254. """Direct archive reprint no longer exists; callers must use the queue."""
  255. printer = await printer_factory()
  256. archive = await archive_factory(
  257. printer.id,
  258. created_by_id=auth_setup["operator2_user"]["id"],
  259. )
  260. response = await async_client.post(
  261. f"/api/v1/archives/{archive.id}/reprint?printer_id={printer.id}",
  262. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  263. )
  264. assert response.status_code == 410
  265. # ========================================================================
  266. # Queue route — archives:reprint_* gate (#1625)
  267. # ========================================================================
  268. # The unified /queue/ route replaced the legacy /reprint endpoint; the
  269. # reprint permission gate must move with it. Without these checks a
  270. # caller with QUEUE_CREATE + ARCHIVES_READ_OWN could reprint their own
  271. # archives even if explicitly denied ARCHIVES_REPRINT_OWN.
  272. @pytest.mark.asyncio
  273. @pytest.mark.integration
  274. async def test_queue_route_operator_can_reprint_own_archive(
  275. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  276. ):
  277. """Operator with REPRINT_OWN can queue their own archive."""
  278. printer = await printer_factory()
  279. archive = await archive_factory(
  280. printer.id,
  281. created_by_id=auth_setup["operator_user"]["id"],
  282. )
  283. response = await async_client.post(
  284. "/api/v1/queue/",
  285. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  286. json={"printer_id": printer.id, "archive_id": archive.id},
  287. )
  288. assert response.status_code == 200
  289. @pytest.mark.asyncio
  290. @pytest.mark.integration
  291. async def test_queue_route_user_without_reprint_gets_403(
  292. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  293. ):
  294. """User with QUEUE_CREATE + ARCHIVES_READ_OWN but no reprint perm → 403.
  295. Custom group mirrors a real operator policy where someone is allowed
  296. to enqueue freshly-uploaded library files but explicitly NOT allowed
  297. to re-run completed archives.
  298. """
  299. # Create custom group with queue:create + archives:read_own but no reprint perm.
  300. admin_headers = {"Authorization": f"Bearer {auth_setup['admin_token']}"}
  301. group_resp = await async_client.post(
  302. "/api/v1/groups/",
  303. headers=admin_headers,
  304. json={
  305. "name": "QueueOnlyNoReprint",
  306. "description": "Test group: can queue library files but not reprint",
  307. "permissions": [
  308. "queue:create",
  309. "queue:read_own",
  310. "archives:read_own",
  311. "library:read_own",
  312. "library:upload",
  313. "printers:read",
  314. ],
  315. },
  316. )
  317. assert group_resp.status_code in (200, 201)
  318. group_id = group_resp.json()["id"]
  319. await async_client.post(
  320. "/api/v1/users/",
  321. headers=admin_headers,
  322. json={
  323. "username": "noreprint_user",
  324. "password": "NoreprintPass1!",
  325. "group_ids": [group_id],
  326. },
  327. )
  328. login = await async_client.post(
  329. "/api/v1/auth/login",
  330. json={"username": "noreprint_user", "password": "NoreprintPass1!"},
  331. )
  332. token = login.json()["access_token"]
  333. user_id = login.json()["user"]["id"]
  334. # Archive owned by the no-reprint user.
  335. printer = await printer_factory()
  336. archive = await archive_factory(printer.id, created_by_id=user_id)
  337. response = await async_client.post(
  338. "/api/v1/queue/",
  339. headers={"Authorization": f"Bearer {token}"},
  340. json={"printer_id": printer.id, "archive_id": archive.id},
  341. )
  342. assert response.status_code == 403
  343. assert "reprint" in response.json()["detail"].lower()
  344. @pytest.mark.asyncio
  345. @pytest.mark.integration
  346. async def test_queue_route_ownerless_archive_requires_reprint_all(
  347. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  348. ):
  349. """Ownerless archive (created_by_id=null) requires REPRINT_ALL.
  350. Pre-IDOR-fix legacy data has no creator; an operator with
  351. REPRINT_OWN can't fall back to "I own this" — fail-closed.
  352. The existing IDOR check returns 404 first (operator lacks
  353. READ_ALL and doesn't own the row), so this is also a regression
  354. guard against accidentally surfacing 403-instead-of-404 if the
  355. IDOR check is ever loosened.
  356. """
  357. printer = await printer_factory()
  358. archive = await archive_factory(printer.id, created_by_id=None)
  359. response = await async_client.post(
  360. "/api/v1/queue/",
  361. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  362. json={"printer_id": printer.id, "archive_id": archive.id},
  363. )
  364. # IDOR returns 404 before the new gate fires for this operator.
  365. assert response.status_code == 404
  366. class TestQueueOwnershipPermissions(TestOwnershipPermissionsSetup):
  367. """Tests for print queue ownership-based permissions."""
  368. @pytest.fixture
  369. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  370. """Factory to create test queue items."""
  371. async def _create_item(**kwargs):
  372. from backend.app.models.print_queue import PrintQueueItem
  373. printer = await printer_factory()
  374. # Create an archive to link to the queue item
  375. archive = await archive_factory(printer.id)
  376. defaults = {
  377. "printer_id": printer.id,
  378. "archive_id": archive.id,
  379. "status": "pending",
  380. "position": 0,
  381. }
  382. defaults.update(kwargs)
  383. item = PrintQueueItem(**defaults)
  384. db_session.add(item)
  385. await db_session.commit()
  386. await db_session.refresh(item)
  387. return item
  388. return _create_item
  389. @pytest.mark.asyncio
  390. @pytest.mark.integration
  391. async def test_admin_can_delete_any_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  392. """Admin can delete any queue item."""
  393. item = await queue_item_factory(created_by_id=auth_setup["operator_user"]["id"])
  394. response = await async_client.delete(
  395. f"/api/v1/queue/{item.id}",
  396. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  397. )
  398. assert response.status_code == 200
  399. @pytest.mark.asyncio
  400. @pytest.mark.integration
  401. async def test_operator_can_delete_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  402. """Operator can delete their own queue item."""
  403. item = await queue_item_factory(created_by_id=auth_setup["operator_user"]["id"])
  404. response = await async_client.delete(
  405. f"/api/v1/queue/{item.id}",
  406. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  407. )
  408. assert response.status_code == 200
  409. @pytest.mark.asyncio
  410. @pytest.mark.integration
  411. async def test_operator_cannot_delete_others_queue_item(
  412. self, async_client: AsyncClient, auth_setup, queue_item_factory
  413. ):
  414. """Operator cannot delete another user's queue item."""
  415. item = await queue_item_factory(created_by_id=auth_setup["operator2_user"]["id"])
  416. response = await async_client.delete(
  417. f"/api/v1/queue/{item.id}",
  418. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  419. )
  420. assert response.status_code == 403
  421. @pytest.mark.asyncio
  422. @pytest.mark.integration
  423. async def test_operator_can_update_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  424. """Operator can update their own queue item."""
  425. item = await queue_item_factory(created_by_id=auth_setup["operator_user"]["id"])
  426. response = await async_client.patch(
  427. f"/api/v1/queue/{item.id}",
  428. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  429. json={"position": 10},
  430. )
  431. assert response.status_code == 200
  432. @pytest.mark.asyncio
  433. @pytest.mark.integration
  434. async def test_operator_cannot_update_others_queue_item(
  435. self, async_client: AsyncClient, auth_setup, queue_item_factory
  436. ):
  437. """Operator cannot update another user's queue item."""
  438. item = await queue_item_factory(created_by_id=auth_setup["operator2_user"]["id"])
  439. response = await async_client.patch(
  440. f"/api/v1/queue/{item.id}",
  441. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  442. json={"position": 10},
  443. )
  444. assert response.status_code == 403
  445. @pytest.mark.asyncio
  446. @pytest.mark.integration
  447. async def test_operator_cannot_cancel_others_queue_item(
  448. self, async_client: AsyncClient, auth_setup, queue_item_factory
  449. ):
  450. """Operator cannot cancel another user's queue item."""
  451. item = await queue_item_factory(created_by_id=auth_setup["operator2_user"]["id"])
  452. response = await async_client.post(
  453. f"/api/v1/queue/{item.id}/cancel",
  454. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  455. )
  456. assert response.status_code == 403
  457. # ========================================================================
  458. # Start / Stop ownership gates (#1625-followup)
  459. # ========================================================================
  460. # Pre-fix /stop required QUEUE_UPDATE_ALL (admin-only) — operators saw the
  461. # Stop button in the queue UI but got 403 on click. /start required
  462. # QUEUE_UPDATE_OWN with no ownership check — operators could start anyone's
  463. # queue items via direct API. Both now use require_ownership_permission.
  464. @pytest.mark.asyncio
  465. @pytest.mark.integration
  466. async def test_operator_can_start_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  467. """Operator can start their own staged queue item."""
  468. item = await queue_item_factory(
  469. created_by_id=auth_setup["operator_user"]["id"],
  470. manual_start=True,
  471. )
  472. response = await async_client.post(
  473. f"/api/v1/queue/{item.id}/start?skip_filament_check=true",
  474. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  475. )
  476. assert response.status_code == 200
  477. @pytest.mark.asyncio
  478. @pytest.mark.integration
  479. async def test_operator_cannot_start_others_queue_item(
  480. self, async_client: AsyncClient, auth_setup, queue_item_factory
  481. ):
  482. """Operator cannot start another user's queue item."""
  483. item = await queue_item_factory(
  484. created_by_id=auth_setup["operator2_user"]["id"],
  485. manual_start=True,
  486. )
  487. response = await async_client.post(
  488. f"/api/v1/queue/{item.id}/start?skip_filament_check=true",
  489. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  490. )
  491. assert response.status_code == 403
  492. @pytest.mark.asyncio
  493. @pytest.mark.integration
  494. async def test_operator_can_start_unowned_queue_item(
  495. self, async_client: AsyncClient, auth_setup, queue_item_factory, db_session
  496. ):
  497. """Operator can start a NULL-owner queue item (VP-uploaded, #1670)
  498. and claims ownership in the process.
  499. Stop and Cancel reject unowned items for _OWN holders (destructive,
  500. no "I own it" claim available), but Start is the entry point for the
  501. VP-import flow where attribution happens at click-time.
  502. """
  503. from backend.app.models.print_queue import PrintQueueItem
  504. item = await queue_item_factory(created_by_id=None, manual_start=True)
  505. response = await async_client.post(
  506. f"/api/v1/queue/{item.id}/start?skip_filament_check=true",
  507. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  508. )
  509. assert response.status_code == 200
  510. # Ownership claimed: operator is now the item's owner.
  511. await db_session.refresh(item)
  512. refetch = await db_session.get(PrintQueueItem, item.id)
  513. assert refetch.created_by_id == auth_setup["operator_user"]["id"]
  514. @pytest.mark.asyncio
  515. @pytest.mark.integration
  516. async def test_operator_can_stop_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  517. """Operator can stop their own currently-printing queue item."""
  518. item = await queue_item_factory(
  519. created_by_id=auth_setup["operator_user"]["id"],
  520. status="printing",
  521. )
  522. response = await async_client.post(
  523. f"/api/v1/queue/{item.id}/stop",
  524. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  525. )
  526. assert response.status_code == 200
  527. @pytest.mark.asyncio
  528. @pytest.mark.integration
  529. async def test_operator_cannot_stop_others_queue_item(
  530. self, async_client: AsyncClient, auth_setup, queue_item_factory
  531. ):
  532. """Operator cannot stop another user's printing queue item."""
  533. item = await queue_item_factory(
  534. created_by_id=auth_setup["operator2_user"]["id"],
  535. status="printing",
  536. )
  537. response = await async_client.post(
  538. f"/api/v1/queue/{item.id}/stop",
  539. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  540. )
  541. assert response.status_code == 403
  542. @pytest.mark.asyncio
  543. @pytest.mark.integration
  544. async def test_operator_cannot_stop_unowned_queue_item(
  545. self, async_client: AsyncClient, auth_setup, queue_item_factory
  546. ):
  547. """Operator cannot stop a NULL-owner printing queue item — stop mirrors
  548. cancel (destructive, no claim semantics). Admins with _ALL can still stop it.
  549. """
  550. item = await queue_item_factory(created_by_id=None, status="printing")
  551. response = await async_client.post(
  552. f"/api/v1/queue/{item.id}/stop",
  553. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  554. )
  555. assert response.status_code == 403
  556. @pytest.mark.asyncio
  557. @pytest.mark.integration
  558. async def test_admin_can_stop_any_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  559. """Admin with _ALL can stop any printing queue item including unowned."""
  560. item = await queue_item_factory(created_by_id=None, status="printing")
  561. response = await async_client.post(
  562. f"/api/v1/queue/{item.id}/stop",
  563. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  564. )
  565. assert response.status_code == 200
  566. @pytest.mark.asyncio
  567. @pytest.mark.integration
  568. async def test_bulk_update_skips_non_owned_items(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  569. """Bulk update only updates items the user owns."""
  570. # Create items owned by different users
  571. own_item = await queue_item_factory(
  572. created_by_id=auth_setup["operator_user"]["id"],
  573. )
  574. other_item = await queue_item_factory(
  575. created_by_id=auth_setup["operator2_user"]["id"],
  576. )
  577. response = await async_client.patch(
  578. "/api/v1/queue/bulk",
  579. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  580. json={
  581. "item_ids": [own_item.id, other_item.id],
  582. "manual_start": True,
  583. },
  584. )
  585. assert response.status_code == 200
  586. result = response.json()
  587. # Should only update the owned item
  588. assert result["updated_count"] == 1
  589. assert result["skipped_count"] == 1
  590. class TestLibraryOwnershipPermissions(TestOwnershipPermissionsSetup):
  591. """Tests for library file ownership-based permissions."""
  592. @pytest.fixture
  593. async def library_file_factory(self, db_session):
  594. """Factory to create test library files."""
  595. _counter = [0]
  596. async def _create_file(**kwargs):
  597. from backend.app.models.library import LibraryFile
  598. _counter[0] += 1
  599. defaults = {
  600. "filename": f"test_{_counter[0]}.3mf",
  601. "file_path": f"library/test_{_counter[0]}.3mf",
  602. "file_type": "3mf",
  603. "file_size": 1024,
  604. }
  605. defaults.update(kwargs)
  606. file = LibraryFile(**defaults)
  607. db_session.add(file)
  608. await db_session.commit()
  609. await db_session.refresh(file)
  610. return file
  611. return _create_file
  612. @pytest.fixture
  613. async def library_folder_factory(self, db_session):
  614. """Factory to create test library folders."""
  615. _counter = [0]
  616. async def _create_folder(**kwargs):
  617. from backend.app.models.library import LibraryFolder
  618. _counter[0] += 1
  619. defaults = {
  620. "name": f"TestFolder_{_counter[0]}",
  621. }
  622. defaults.update(kwargs)
  623. folder = LibraryFolder(**defaults)
  624. db_session.add(folder)
  625. await db_session.commit()
  626. await db_session.refresh(folder)
  627. return folder
  628. return _create_folder
  629. @pytest.mark.asyncio
  630. @pytest.mark.integration
  631. async def test_admin_can_delete_any_library_file(self, async_client: AsyncClient, auth_setup, library_file_factory):
  632. """Admin can delete any library file."""
  633. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  634. response = await async_client.delete(
  635. f"/api/v1/library/files/{file.id}",
  636. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  637. )
  638. assert response.status_code == 200
  639. @pytest.mark.asyncio
  640. @pytest.mark.integration
  641. async def test_operator_can_delete_own_library_file(
  642. self, async_client: AsyncClient, auth_setup, library_file_factory
  643. ):
  644. """Operator can delete their own library file."""
  645. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  646. response = await async_client.delete(
  647. f"/api/v1/library/files/{file.id}",
  648. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  649. )
  650. assert response.status_code == 200
  651. @pytest.mark.asyncio
  652. @pytest.mark.integration
  653. async def test_operator_cannot_delete_others_library_file(
  654. self, async_client: AsyncClient, auth_setup, library_file_factory
  655. ):
  656. """Operator cannot delete another user's library file."""
  657. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  658. response = await async_client.delete(
  659. f"/api/v1/library/files/{file.id}",
  660. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  661. )
  662. assert response.status_code == 403
  663. @pytest.mark.asyncio
  664. @pytest.mark.integration
  665. async def test_operator_can_update_own_library_file(
  666. self, async_client: AsyncClient, auth_setup, library_file_factory
  667. ):
  668. """Operator can update their own library file."""
  669. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  670. response = await async_client.put(
  671. f"/api/v1/library/files/{file.id}",
  672. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  673. json={"filename": "renamed.3mf"},
  674. )
  675. assert response.status_code == 200
  676. @pytest.mark.asyncio
  677. @pytest.mark.integration
  678. async def test_operator_cannot_update_others_library_file(
  679. self, async_client: AsyncClient, auth_setup, library_file_factory
  680. ):
  681. """Operator cannot update another user's library file."""
  682. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  683. response = await async_client.put(
  684. f"/api/v1/library/files/{file.id}",
  685. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  686. json={"filename": "renamed.3mf"},
  687. )
  688. assert response.status_code == 403
  689. @pytest.mark.asyncio
  690. @pytest.mark.integration
  691. async def test_folders_require_all_permission(self, async_client: AsyncClient, auth_setup, library_folder_factory):
  692. """Folders require *_all permission (no ownership tracking on folders)."""
  693. folder = await library_folder_factory(name="TestFolder")
  694. # Operator cannot delete folder (needs *_all)
  695. response = await async_client.delete(
  696. f"/api/v1/library/folders/{folder.id}",
  697. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  698. )
  699. assert response.status_code == 403
  700. @pytest.mark.asyncio
  701. @pytest.mark.integration
  702. async def test_bulk_delete_skips_non_owned_files(self, async_client: AsyncClient, auth_setup, library_file_factory):
  703. """Bulk delete only deletes files the user owns."""
  704. own_file = await library_file_factory(
  705. filename="own.3mf",
  706. created_by_id=auth_setup["operator_user"]["id"],
  707. )
  708. other_file = await library_file_factory(
  709. filename="other.3mf",
  710. created_by_id=auth_setup["operator2_user"]["id"],
  711. )
  712. response = await async_client.post(
  713. "/api/v1/library/bulk-delete",
  714. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  715. json={"file_ids": [own_file.id, other_file.id], "folder_ids": []},
  716. )
  717. assert response.status_code == 200
  718. result = response.json()
  719. # Should only delete the owned file; other_file is skipped (but skipped count not in response)
  720. assert result["deleted_files"] == 1
  721. class TestAuthDisabledPermissions:
  722. """Tests that verify all operations are allowed when auth is disabled."""
  723. @pytest.mark.asyncio
  724. @pytest.mark.integration
  725. async def test_delete_archive_without_auth(
  726. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  727. ):
  728. """When auth is disabled, anyone can delete archives."""
  729. printer = await printer_factory()
  730. archive = await archive_factory(printer.id)
  731. response = await async_client.delete(f"/api/v1/archives/{archive.id}")
  732. assert response.status_code == 200
  733. @pytest.mark.asyncio
  734. @pytest.mark.integration
  735. async def test_update_archive_without_auth(
  736. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  737. ):
  738. """When auth is disabled, anyone can update archives."""
  739. printer = await printer_factory()
  740. archive = await archive_factory(printer.id)
  741. response = await async_client.patch(
  742. f"/api/v1/archives/{archive.id}",
  743. json={"print_name": "Updated Name"},
  744. )
  745. assert response.status_code == 200
  746. class TestUserItemsCountAndDeletion(TestOwnershipPermissionsSetup):
  747. """Tests for user items count endpoint and deletion with items."""
  748. @pytest.mark.asyncio
  749. @pytest.mark.integration
  750. async def test_get_user_items_count(
  751. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  752. ):
  753. """Verify items count endpoint returns correct counts."""
  754. printer = await printer_factory()
  755. user_id = auth_setup["operator_user"]["id"]
  756. # Create some items for the operator
  757. await archive_factory(printer.id, created_by_id=user_id)
  758. await archive_factory(printer.id, created_by_id=user_id)
  759. response = await async_client.get(
  760. f"/api/v1/users/{user_id}/items-count",
  761. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  762. )
  763. assert response.status_code == 200
  764. counts = response.json()
  765. assert counts["archives"] >= 2
  766. assert "queue_items" in counts
  767. assert "library_files" in counts
  768. @pytest.mark.asyncio
  769. @pytest.mark.integration
  770. async def test_delete_user_keeps_items(
  771. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  772. ):
  773. """Verify deleting user without delete_items keeps items (ownerless)."""
  774. printer = await printer_factory()
  775. user_id = auth_setup["operator2_user"]["id"]
  776. # Create archive for operator2
  777. archive = await archive_factory(printer.id, created_by_id=user_id)
  778. archive_id = archive.id
  779. # Delete user without deleting items
  780. response = await async_client.delete(
  781. f"/api/v1/users/{user_id}?delete_items=false",
  782. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  783. )
  784. assert response.status_code == 204
  785. # Verify archive still exists but is now ownerless
  786. archive_response = await async_client.get(
  787. f"/api/v1/archives/{archive_id}",
  788. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  789. )
  790. assert archive_response.status_code == 200
  791. assert archive_response.json()["created_by_id"] is None
  792. @pytest.mark.asyncio
  793. @pytest.mark.integration
  794. async def test_delete_user_with_items(
  795. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  796. ):
  797. """Verify deleting user with delete_items=true removes their items."""
  798. printer = await printer_factory()
  799. # Create a new user with items
  800. create_response = await async_client.post(
  801. "/api/v1/users/",
  802. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  803. json={
  804. "username": "deletewithitems",
  805. "password": "Password123!",
  806. },
  807. )
  808. user_id = create_response.json()["id"]
  809. # Create archive for this user
  810. archive = await archive_factory(printer.id, created_by_id=user_id)
  811. archive_id = archive.id
  812. # Delete user WITH deleting items
  813. response = await async_client.delete(
  814. f"/api/v1/users/{user_id}?delete_items=true",
  815. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  816. )
  817. assert response.status_code == 204
  818. # Verify archive was deleted
  819. archive_response = await async_client.get(
  820. f"/api/v1/archives/{archive_id}",
  821. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  822. )
  823. assert archive_response.status_code == 404
  824. class TestReadIDORClosure(TestOwnershipPermissionsSetup):
  825. """Regression tests pinning maziggy/bambuddy-security #2 — IDOR on
  826. archives / library / queue read paths.
  827. Before the fix, ARCHIVES_READ / LIBRARY_READ / QUEUE_READ were flat
  828. "see everything" permissions even though the write side was split into
  829. OWN/ALL. An operator with only ARCHIVES_READ could read, download, and
  830. queue any user's archive via direct id reference. These tests pin the
  831. bambuddy_archive_idor.py and bambuddy_archive_viewer_idor.py PoC paths
  832. so the IDOR can't regress silently.
  833. """
  834. @pytest.mark.asyncio
  835. @pytest.mark.integration
  836. async def test_operator_get_others_archive_returns_404_not_200(
  837. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  838. ):
  839. """PoC #2 read path. operator1 GET /archives/{id} where id is admin's
  840. archive must NOT leak the row. 404 (not 403) so the operator can't
  841. enumerate which ids exist — same shape as a nonexistent id."""
  842. printer = await printer_factory()
  843. archive = await archive_factory(
  844. printer.id,
  845. print_name="Admin Archive",
  846. created_by_id=auth_setup["admin_user"]["id"],
  847. )
  848. response = await async_client.get(
  849. f"/api/v1/archives/{archive.id}",
  850. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  851. )
  852. assert response.status_code == 404
  853. @pytest.mark.asyncio
  854. @pytest.mark.integration
  855. async def test_operator_download_others_archive_returns_404(
  856. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  857. ):
  858. """Viewer-IDOR PoC path: GET /archives/{id}/download on admin's archive.
  859. Before the fix this streamed the 3MF body straight to a viewer-tier
  860. token."""
  861. printer = await printer_factory()
  862. archive = await archive_factory(
  863. printer.id,
  864. print_name="Admin Archive 2",
  865. created_by_id=auth_setup["admin_user"]["id"],
  866. )
  867. response = await async_client.get(
  868. f"/api/v1/archives/{archive.id}/download",
  869. headers={"Authorization": f"Bearer {auth_setup['viewer_token']}"},
  870. )
  871. assert response.status_code == 404
  872. @pytest.mark.asyncio
  873. @pytest.mark.integration
  874. async def test_operator_list_archives_excludes_others(
  875. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  876. ):
  877. """GET /archives/ must filter to own archives only for OWN-level callers."""
  878. printer = await printer_factory()
  879. own = await archive_factory(
  880. printer.id, print_name="Operator's Own", created_by_id=auth_setup["operator_user"]["id"]
  881. )
  882. others = await archive_factory(printer.id, print_name="Admin's", created_by_id=auth_setup["admin_user"]["id"])
  883. response = await async_client.get(
  884. "/api/v1/archives/",
  885. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  886. )
  887. assert response.status_code == 200
  888. returned_ids = {a["id"] for a in response.json()}
  889. assert own.id in returned_ids
  890. assert others.id not in returned_ids
  891. @pytest.mark.asyncio
  892. @pytest.mark.integration
  893. async def test_admin_list_archives_includes_all(
  894. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  895. ):
  896. """ARCHIVES_READ_ALL → admin sees own + every user's archives."""
  897. printer = await printer_factory()
  898. admin_archive = await archive_factory(
  899. printer.id, print_name="Admin's", created_by_id=auth_setup["admin_user"]["id"]
  900. )
  901. operator_archive = await archive_factory(
  902. printer.id, print_name="Operator's", created_by_id=auth_setup["operator_user"]["id"]
  903. )
  904. response = await async_client.get(
  905. "/api/v1/archives/",
  906. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  907. )
  908. assert response.status_code == 200
  909. returned_ids = {a["id"] for a in response.json()}
  910. assert admin_archive.id in returned_ids
  911. assert operator_archive.id in returned_ids
  912. @pytest.mark.asyncio
  913. @pytest.mark.integration
  914. async def test_operator_cannot_queue_others_archive(
  915. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  916. ):
  917. """PoC #2 queue path. POST /queue/ with admin's archive_id as
  918. operator1 must return 404, not create a queue item. Before the fix
  919. this returned 201 and queued the admin archive (Landon's CONFIRMED
  920. line in the PoC)."""
  921. printer = await printer_factory()
  922. archive = await archive_factory(
  923. printer.id,
  924. print_name="Admin Archive (queue-target)",
  925. created_by_id=auth_setup["admin_user"]["id"],
  926. )
  927. response = await async_client.post(
  928. "/api/v1/queue/",
  929. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  930. json={"archive_id": archive.id, "printer_id": printer.id, "quantity": 1},
  931. )
  932. assert response.status_code == 404
  933. @pytest.mark.asyncio
  934. @pytest.mark.integration
  935. async def test_admin_can_queue_others_archive(
  936. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  937. ):
  938. """Belt-and-suspenders for the ALL path: admin (ARCHIVES_READ_ALL) can
  939. queue a user's archive on their behalf — common workshop pattern."""
  940. printer = await printer_factory()
  941. archive = await archive_factory(
  942. printer.id,
  943. print_name="Operator's archive (queue by admin)",
  944. created_by_id=auth_setup["operator_user"]["id"],
  945. )
  946. response = await async_client.post(
  947. "/api/v1/queue/",
  948. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  949. json={"archive_id": archive.id, "printer_id": printer.id, "quantity": 1},
  950. )
  951. assert response.status_code == 200
  952. @pytest.mark.asyncio
  953. @pytest.mark.integration
  954. async def test_operator_get_others_library_file_returns_404(
  955. self, async_client: AsyncClient, auth_setup, db_session
  956. ):
  957. """Library IDOR closure (same shape as archives — closed in the same PR
  958. per maziggy/bambuddy-security #2)."""
  959. from backend.app.models.library import LibraryFile
  960. admin_file = LibraryFile(
  961. filename="admin_secret.3mf",
  962. file_path="library/admin_secret.3mf",
  963. file_type="3mf",
  964. file_size=2048,
  965. created_by_id=auth_setup["admin_user"]["id"],
  966. )
  967. db_session.add(admin_file)
  968. await db_session.commit()
  969. await db_session.refresh(admin_file)
  970. response = await async_client.get(
  971. f"/api/v1/library/files/{admin_file.id}",
  972. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  973. )
  974. assert response.status_code == 404
  975. @pytest.mark.asyncio
  976. @pytest.mark.integration
  977. async def test_operator_list_library_files_excludes_others(self, async_client: AsyncClient, auth_setup, db_session):
  978. from backend.app.models.library import LibraryFile
  979. own = LibraryFile(
  980. filename="my_file.3mf",
  981. file_path="library/my_file.3mf",
  982. file_type="3mf",
  983. file_size=1024,
  984. created_by_id=auth_setup["operator_user"]["id"],
  985. )
  986. others = LibraryFile(
  987. filename="admin_file.3mf",
  988. file_path="library/admin_file.3mf",
  989. file_type="3mf",
  990. file_size=1024,
  991. created_by_id=auth_setup["admin_user"]["id"],
  992. )
  993. db_session.add_all([own, others])
  994. await db_session.commit()
  995. await db_session.refresh(own)
  996. await db_session.refresh(others)
  997. response = await async_client.get(
  998. "/api/v1/library/files",
  999. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1000. )
  1001. assert response.status_code == 200
  1002. returned_ids = {f["id"] for f in response.json()}
  1003. assert own.id in returned_ids
  1004. assert others.id not in returned_ids
  1005. @pytest.mark.asyncio
  1006. @pytest.mark.integration
  1007. async def test_operator_queue_list_excludes_others_items(
  1008. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1009. ):
  1010. """GET /queue/ must filter to own queue items only for OWN callers —
  1011. same shape as the archive list."""
  1012. from backend.app.models.print_queue import PrintQueueItem
  1013. printer = await printer_factory()
  1014. archive = await archive_factory(printer.id, print_name="A", created_by_id=auth_setup["operator_user"]["id"])
  1015. own_item = PrintQueueItem(
  1016. archive_id=archive.id,
  1017. printer_id=printer.id,
  1018. status="pending",
  1019. position=1,
  1020. created_by_id=auth_setup["operator_user"]["id"],
  1021. )
  1022. admin_item = PrintQueueItem(
  1023. archive_id=archive.id,
  1024. printer_id=printer.id,
  1025. status="pending",
  1026. position=2,
  1027. created_by_id=auth_setup["admin_user"]["id"],
  1028. )
  1029. db_session.add_all([own_item, admin_item])
  1030. await db_session.commit()
  1031. await db_session.refresh(own_item)
  1032. await db_session.refresh(admin_item)
  1033. response = await async_client.get(
  1034. "/api/v1/queue/",
  1035. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1036. )
  1037. assert response.status_code == 200
  1038. returned_ids = {q["id"] for q in response.json()}
  1039. assert own_item.id in returned_ids
  1040. assert admin_item.id not in returned_ids
  1041. @pytest.mark.asyncio
  1042. @pytest.mark.integration
  1043. async def test_operator_get_others_queue_item_returns_404(
  1044. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1045. ):
  1046. """Direct-id queue item access — same enumeration risk as archive get."""
  1047. from backend.app.models.print_queue import PrintQueueItem
  1048. printer = await printer_factory()
  1049. archive = await archive_factory(printer.id, print_name="A", created_by_id=auth_setup["admin_user"]["id"])
  1050. admin_item = PrintQueueItem(
  1051. archive_id=archive.id,
  1052. printer_id=printer.id,
  1053. status="pending",
  1054. position=1,
  1055. created_by_id=auth_setup["admin_user"]["id"],
  1056. )
  1057. db_session.add(admin_item)
  1058. await db_session.commit()
  1059. await db_session.refresh(admin_item)
  1060. response = await async_client.get(
  1061. f"/api/v1/queue/{admin_item.id}",
  1062. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1063. )
  1064. assert response.status_code == 404
  1065. @pytest.mark.asyncio
  1066. @pytest.mark.integration
  1067. async def test_auth_disabled_preserves_single_tenant_read_all(
  1068. self, async_client: AsyncClient, archive_factory, printer_factory
  1069. ):
  1070. """With auth disabled, ARCHIVES_READ resolves to read-all (can_modify_all=True
  1071. in require_ownership_permission's auth-disabled branch). Existing
  1072. single-user installs see no behavior change."""
  1073. printer = await printer_factory()
  1074. archive = await archive_factory(printer.id, print_name="Anonymous", created_by_id=None)
  1075. # No Authorization header — auth-disabled mode.
  1076. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1077. # Either 200 (auth disabled in this test session) or 401 (auth enabled
  1078. # from a prior test) — both are acceptable; the IDOR closure does not
  1079. # change auth-enable/disable behavior. Pin not-404 to avoid masking a
  1080. # regression where auth-disabled callers would lose access.
  1081. assert response.status_code in (200, 401)
  1082. # Every archive WRITE sub-resource route: (id, http method, path suffix, request kwargs).
  1083. # The ownership gate (_ensure_archive_visible) fires immediately after the fetch,
  1084. # before any resource-specific logic, so a not-owned / ownerless row 404s regardless
  1085. # of whether the timelapse / photo / source / f3d actually exists. Upload routes still
  1086. # need a body so FastAPI reaches the handler instead of 422-ing on the missing File(...).
  1087. _WRITE_SUBRESOURCE_ROUTES = [
  1088. ("favorite", "post", "/favorite", {}),
  1089. ("timelapse_delete", "delete", "/timelapse", {}),
  1090. ("photo_upload", "post", "/photos", {"files": {"file": ("x.jpg", b"\x89PNG\r\n\x1a\n", "image/jpeg")}}),
  1091. ("photo_delete", "delete", "/photos/nonexistent.jpg", {}),
  1092. ("project_page", "patch", "/project-page", {"json": {"title": "hijacked"}}),
  1093. ("source_upload", "post", "/source", {"files": {"file": ("x.3mf", b"PK\x03\x04", "application/octet-stream")}}),
  1094. ("source_delete", "delete", "/source", {}),
  1095. ("f3d_upload", "post", "/f3d", {"files": {"file": ("x.f3d", b"f3d-bytes", "application/octet-stream")}}),
  1096. ("f3d_delete", "delete", "/f3d", {}),
  1097. ]
  1098. class TestWriteSubResourceIDORClosure(TestOwnershipPermissionsSetup):
  1099. """Regression tests for the archive write SUB-RESOURCE IDOR.
  1100. The read sub-resource routes were closed under maziggy/bambuddy-security #2
  1101. via ``_ensure_archive_visible``, but the *write* sub-resource routes
  1102. (favorite, timelapse, photos, project-page, source, f3d) were left gating
  1103. on the bare ``RequirePermissionIfAuthEnabled(ARCHIVES_*_OWN)`` scope and
  1104. fetched the row by id only — never comparing ``created_by_id`` to the
  1105. caller. An operator holding only ``ARCHIVES_*_OWN`` (or an API key with
  1106. ``can_manage_archives``) could delete/overwrite files on ANY user's
  1107. archive, most severely rewriting the project-page metadata inside another
  1108. user's ``.3mf`` on disk. Each route is now gated by
  1109. ``require_ownership_permission`` + ``_ensure_archive_visible`` → 404 (not
  1110. 403, to stay non-enumerable and match the read side) on a not-owned or
  1111. ownerless row.
  1112. """
  1113. @pytest.mark.parametrize(
  1114. "name,method,suffix,kwargs",
  1115. _WRITE_SUBRESOURCE_ROUTES,
  1116. ids=[r[0] for r in _WRITE_SUBRESOURCE_ROUTES],
  1117. )
  1118. @pytest.mark.asyncio
  1119. @pytest.mark.integration
  1120. async def test_operator_cannot_write_others_archive_subresource(
  1121. self,
  1122. async_client: AsyncClient,
  1123. auth_setup,
  1124. archive_factory,
  1125. printer_factory,
  1126. db_session,
  1127. name,
  1128. method,
  1129. suffix,
  1130. kwargs,
  1131. ):
  1132. """SECURITY.md rule 4: right credentials, wrong ownership → 404.
  1133. operator1 (ARCHIVES_*_OWN) targeting a route on admin's archive.
  1134. """
  1135. printer = await printer_factory()
  1136. archive = await archive_factory(
  1137. printer.id,
  1138. print_name="Admin's Archive",
  1139. created_by_id=auth_setup["admin_user"]["id"],
  1140. )
  1141. response = await getattr(async_client, method)(
  1142. f"/api/v1/archives/{archive.id}{suffix}",
  1143. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1144. **kwargs,
  1145. )
  1146. assert response.status_code == 404, f"{name}: expected 404, got {response.status_code}"
  1147. @pytest.mark.parametrize(
  1148. "name,method,suffix,kwargs",
  1149. _WRITE_SUBRESOURCE_ROUTES,
  1150. ids=[r[0] for r in _WRITE_SUBRESOURCE_ROUTES],
  1151. )
  1152. @pytest.mark.asyncio
  1153. @pytest.mark.integration
  1154. async def test_operator_cannot_write_ownerless_archive_subresource(
  1155. self,
  1156. async_client: AsyncClient,
  1157. auth_setup,
  1158. archive_factory,
  1159. printer_factory,
  1160. db_session,
  1161. name,
  1162. method,
  1163. suffix,
  1164. kwargs,
  1165. ):
  1166. """Ownerless rows (created_by_id = null, legacy data) require *_ALL — an
  1167. operator with only *_OWN has no 'I own this' claim, so fail closed → 404."""
  1168. printer = await printer_factory()
  1169. archive = await archive_factory(
  1170. printer.id,
  1171. print_name="Ownerless Archive",
  1172. created_by_id=None,
  1173. )
  1174. response = await getattr(async_client, method)(
  1175. f"/api/v1/archives/{archive.id}{suffix}",
  1176. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1177. **kwargs,
  1178. )
  1179. assert response.status_code == 404, f"{name}: expected 404, got {response.status_code}"
  1180. @pytest.mark.asyncio
  1181. @pytest.mark.integration
  1182. async def test_operator_can_favorite_own_archive(
  1183. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1184. ):
  1185. """Positive control: the owner still gets through the new gate. Favorite
  1186. is the one write sub-resource that needs no pre-existing file, so it
  1187. cleanly proves the *_OWN happy path returns 200 (not a false 404)."""
  1188. printer = await printer_factory()
  1189. archive = await archive_factory(
  1190. printer.id,
  1191. print_name="Operator's Own",
  1192. created_by_id=auth_setup["operator_user"]["id"],
  1193. )
  1194. response = await async_client.post(
  1195. f"/api/v1/archives/{archive.id}/favorite",
  1196. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1197. )
  1198. assert response.status_code == 200
  1199. assert response.json()["is_favorite"] is True
  1200. @pytest.mark.asyncio
  1201. @pytest.mark.integration
  1202. async def test_admin_can_favorite_any_archive(
  1203. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1204. ):
  1205. """Positive control for the *_ALL path: admin can act on a user's archive."""
  1206. printer = await printer_factory()
  1207. archive = await archive_factory(
  1208. printer.id,
  1209. print_name="Operator's Own",
  1210. created_by_id=auth_setup["operator_user"]["id"],
  1211. )
  1212. response = await async_client.post(
  1213. f"/api/v1/archives/{archive.id}/favorite",
  1214. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1215. )
  1216. assert response.status_code == 200
  1217. class TestSliceOwnershipPermissions(TestOwnershipPermissionsSetup):
  1218. """IDOR regression: slicing and slice-job polling must honour per-row ownership.
  1219. Before the fix, ``POST /library/files/{id}/slice`` and
  1220. ``POST /archives/{id}/slice`` gated only on ``LIBRARY_UPLOAD``, so a
  1221. READ_OWN operator could slice another user's model by raw id even though a
  1222. direct GET on that id returned 404 — the sliced output was then attributed
  1223. to and downloadable by the requester. ``GET /slice-jobs/{id}`` had no owner
  1224. scoping at all. ``POST /slicer-pipelines/{id}/run`` (and check-eligibility)
  1225. resolved the source by raw id with the same gap.
  1226. The slice route enforces the gate before touching the source bytes, so the
  1227. owner/READ_ALL "control" cases reach the later on-disk check (a distinct 404
  1228. detail) rather than a real slice — enough to prove the gate lets them past.
  1229. """
  1230. # Any preset triplet: the ownership 404 fires before preset resolution.
  1231. _SLICE_BODY = {"printer_preset_id": 1, "process_preset_id": 2, "filament_preset_id": 3}
  1232. @pytest.fixture
  1233. async def library_file_factory(self, db_session):
  1234. _counter = [0]
  1235. async def _create_file(**kwargs):
  1236. from backend.app.models.library import LibraryFile
  1237. _counter[0] += 1
  1238. defaults = {
  1239. "filename": f"slice_src_{_counter[0]}.3mf",
  1240. "file_path": f"library/slice_src_{_counter[0]}.3mf",
  1241. "file_type": "3mf",
  1242. "file_size": 1024,
  1243. }
  1244. defaults.update(kwargs)
  1245. row = LibraryFile(**defaults)
  1246. db_session.add(row)
  1247. await db_session.commit()
  1248. await db_session.refresh(row)
  1249. return row
  1250. return _create_file
  1251. # --- library file slice ------------------------------------------------
  1252. @pytest.mark.asyncio
  1253. @pytest.mark.integration
  1254. async def test_operator_cannot_slice_others_library_file(self, async_client, auth_setup, library_file_factory):
  1255. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  1256. resp = await async_client.post(
  1257. f"/api/v1/library/files/{file.id}/slice",
  1258. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1259. json=self._SLICE_BODY,
  1260. )
  1261. assert resp.status_code == 404
  1262. # 404 (not 403) so a probing operator can't tell the id exists.
  1263. assert resp.json()["detail"] == "File not found"
  1264. @pytest.mark.asyncio
  1265. @pytest.mark.integration
  1266. async def test_operator_can_slice_own_library_file(self, async_client, auth_setup, library_file_factory):
  1267. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  1268. resp = await async_client.post(
  1269. f"/api/v1/library/files/{file.id}/slice",
  1270. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1271. json=self._SLICE_BODY,
  1272. )
  1273. # Past the ownership gate — only the on-disk source is missing in tests.
  1274. assert resp.status_code == 404
  1275. assert resp.json()["detail"] == "Source file missing on disk"
  1276. @pytest.mark.asyncio
  1277. @pytest.mark.integration
  1278. async def test_admin_can_slice_any_library_file(self, async_client, auth_setup, library_file_factory):
  1279. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  1280. resp = await async_client.post(
  1281. f"/api/v1/library/files/{file.id}/slice",
  1282. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1283. json=self._SLICE_BODY,
  1284. )
  1285. # READ_ALL passes the gate even on another user's file.
  1286. assert resp.status_code == 404
  1287. assert resp.json()["detail"] == "Source file missing on disk"
  1288. # --- archive slice -----------------------------------------------------
  1289. @pytest.mark.asyncio
  1290. @pytest.mark.integration
  1291. async def test_operator_cannot_slice_others_archive(
  1292. self, async_client, auth_setup, archive_factory, printer_factory
  1293. ):
  1294. printer = await printer_factory()
  1295. archive = await archive_factory(printer.id, created_by_id=auth_setup["operator2_user"]["id"])
  1296. resp = await async_client.post(
  1297. f"/api/v1/archives/{archive.id}/slice",
  1298. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1299. json=self._SLICE_BODY,
  1300. )
  1301. assert resp.status_code == 404
  1302. assert resp.json()["detail"] == "Archive not found"
  1303. @pytest.mark.asyncio
  1304. @pytest.mark.integration
  1305. async def test_operator_can_slice_own_archive(self, async_client, auth_setup, archive_factory, printer_factory):
  1306. printer = await printer_factory()
  1307. archive = await archive_factory(printer.id, created_by_id=auth_setup["operator_user"]["id"])
  1308. resp = await async_client.post(
  1309. f"/api/v1/archives/{archive.id}/slice",
  1310. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1311. json=self._SLICE_BODY,
  1312. )
  1313. # Past the gate — the archive's source file isn't on disk in tests.
  1314. assert resp.status_code == 404
  1315. assert resp.json()["detail"] == "Archive source file missing on disk"
  1316. # --- slice-job polling -------------------------------------------------
  1317. @pytest.mark.asyncio
  1318. @pytest.mark.integration
  1319. async def test_slice_job_polling_is_owner_scoped(self, async_client, auth_setup):
  1320. from backend.app.services.slice_dispatch import slice_dispatch
  1321. async def _noop(_job_id):
  1322. return {}
  1323. job = await slice_dispatch.enqueue(
  1324. kind="library_file",
  1325. source_id=1,
  1326. source_name="secret_model.3mf",
  1327. owner_id=auth_setup["operator2_user"]["id"],
  1328. run=_noop,
  1329. )
  1330. # Non-owner without READ_ALL cannot see the job (404, not 403).
  1331. other = await async_client.get(
  1332. f"/api/v1/slice-jobs/{job.id}",
  1333. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1334. )
  1335. assert other.status_code == 404
  1336. # The owner and a READ_ALL admin can.
  1337. owner = await async_client.get(
  1338. f"/api/v1/slice-jobs/{job.id}",
  1339. headers={"Authorization": f"Bearer {auth_setup['operator2_token']}"},
  1340. )
  1341. assert owner.status_code == 200
  1342. admin = await async_client.get(
  1343. f"/api/v1/slice-jobs/{job.id}",
  1344. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1345. )
  1346. assert admin.status_code == 200
  1347. # --- pipeline source resolution ----------------------------------------
  1348. @pytest.mark.asyncio
  1349. @pytest.mark.integration
  1350. async def test_pipeline_run_cannot_reference_others_library_file(
  1351. self, async_client, auth_setup, library_file_factory, db_session
  1352. ):
  1353. """A pipeline runner with READ_OWN cannot resolve another user's source.
  1354. The built-in Operators group has no pipeline permissions, so this uses a
  1355. custom group carrying PIPELINES_RUN + READ_OWN — the realistic shape of
  1356. the exposure. check-eligibility resolves the source before any
  1357. eligibility work, so the ownership gate is what returns 404.
  1358. """
  1359. from backend.app.models.slicer_pipeline import SlicerPipeline
  1360. admin_headers = {"Authorization": f"Bearer {auth_setup['admin_token']}"}
  1361. group_resp = await async_client.post(
  1362. "/api/v1/groups/",
  1363. headers=admin_headers,
  1364. json={
  1365. "name": "pipeline_runners",
  1366. "permissions": [
  1367. "pipelines:read",
  1368. "pipelines:run",
  1369. "library:read_own",
  1370. "archives:read_own",
  1371. ],
  1372. },
  1373. )
  1374. assert group_resp.status_code == 201, group_resp.text
  1375. group_id = group_resp.json()["id"]
  1376. await async_client.post(
  1377. "/api/v1/users/",
  1378. headers=admin_headers,
  1379. json={"username": "runner1", "password": "Runnerpass1!", "group_ids": [group_id]},
  1380. )
  1381. runner_login = await async_client.post(
  1382. "/api/v1/auth/login",
  1383. json={"username": "runner1", "password": "Runnerpass1!"},
  1384. )
  1385. runner_token = runner_login.json()["access_token"]
  1386. pipeline = SlicerPipeline(
  1387. name="Cross-user pipeline",
  1388. printer_preset_source="local",
  1389. printer_preset_id="1",
  1390. process_preset_source="local",
  1391. process_preset_id="2",
  1392. filament_presets_json="[]",
  1393. target_kind="printer_class",
  1394. target_model_class="Bambu Lab X1 Carbon",
  1395. )
  1396. db_session.add(pipeline)
  1397. await db_session.commit()
  1398. await db_session.refresh(pipeline)
  1399. # Source owned by operator2, not the runner.
  1400. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  1401. resp = await async_client.post(
  1402. f"/api/v1/slicer-pipelines/{pipeline.id}/check-eligibility",
  1403. headers={"Authorization": f"Bearer {runner_token}"},
  1404. json={"source_library_file_id": file.id},
  1405. )
  1406. assert resp.status_code == 404
  1407. assert resp.json()["detail"] == "File not found"