test_ownership_permissions.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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