test_overlay_status_api.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. """Integration tests for the token-authenticated streaming-overlay feed (#2613).
  2. Like the Cam Wall feed, the overlay endpoint exists as its own scope-gated
  3. route because a kiosk/OBS URL is not a secret. But it is deliberately *wider*
  4. than the Cam Wall: it names the file being printed (the overlay draws the part
  5. on screen). So the tests that matter are the scope boundaries — an overlay
  6. token must not reach the Cam Wall feed and vice versa, a camwall token must not
  7. reach the overlay feed (that would leak the filename it is trusted to hide) —
  8. plus the positive path and the disconnected-printer shape.
  9. """
  10. from __future__ import annotations
  11. import pytest
  12. from httpx import AsyncClient
  13. from backend.app.core.printer_scope import ALL_PRINTERS
  14. from backend.tests.overlay_helpers import mint_token, setup_admin
  15. pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
  16. @pytest.fixture
  17. async def printer_row(db_session):
  18. """Insert the printer straight into the DB.
  19. POST /printers probes the real device before it will store a row, and there
  20. is no printer on the other end of a test run.
  21. """
  22. from backend.app.models.printer import Printer
  23. printer = Printer(
  24. name="Stream P1S",
  25. ip_address="192.168.1.88",
  26. access_code="12345678",
  27. serial_number="01P00A000000002",
  28. model="P1S",
  29. )
  30. db_session.add(printer)
  31. await db_session.commit()
  32. return printer
  33. class TestOverlayFeedAuth:
  34. async def test_no_token_is_rejected(self, async_client: AsyncClient, printer_row):
  35. await setup_admin(async_client, suffix="_notoken")
  36. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status")
  37. assert response.status_code == 401
  38. async def test_garbage_token_is_rejected(self, async_client: AsyncClient, printer_row):
  39. await setup_admin(async_client, suffix="_garbage")
  40. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token=bblt_aaaaaaaa_nope")
  41. assert response.status_code == 401
  42. async def test_camera_stream_token_cannot_reach_the_feed(self, async_client: AsyncClient, printer_row):
  43. """A ``camera_stream`` token was handed out for video alone — it must not
  44. acquire the live print status (and filename) just because a new feature
  45. shipped.
  46. """
  47. jwt = await setup_admin(async_client, suffix="_streamscope")
  48. stream_token = await mint_token(async_client, jwt, scope="camera_stream")
  49. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={stream_token}")
  50. assert response.status_code == 401
  51. async def test_camwall_token_cannot_reach_the_feed(self, async_client: AsyncClient, printer_row):
  52. """The crux of a *separate* scope from camwall.
  53. A Cam Wall token is trusted precisely because it can never name the part
  54. being printed. The overlay feed does name it, so a camwall token must be
  55. rejected here — otherwise every wall token silently gains filename
  56. visibility.
  57. """
  58. jwt = await setup_admin(async_client, suffix="_camwallscope")
  59. camwall_token = await mint_token(async_client, jwt, scope="camwall")
  60. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={camwall_token}")
  61. assert response.status_code == 401
  62. async def test_overlay_token_reaches_the_feed(self, async_client: AsyncClient, printer_row):
  63. jwt = await setup_admin(async_client, suffix="_rightscope")
  64. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  65. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={overlay_token}")
  66. assert response.status_code == 200, response.text
  67. assert response.json()["name"] == "Stream P1S"
  68. async def test_revoked_overlay_token_is_rejected(self, async_client: AsyncClient, printer_row):
  69. jwt = await setup_admin(async_client, suffix="_revoked")
  70. created = await async_client.post(
  71. "/api/v1/auth/tokens",
  72. headers={"Authorization": f"Bearer {jwt}"},
  73. json={"name": "obs", "expires_in_days": 30, "scope": "overlay"},
  74. )
  75. overlay_token = created.json()["token"]
  76. await async_client.delete(
  77. f"/api/v1/auth/tokens/{created.json()['id']}",
  78. headers={"Authorization": f"Bearer {jwt}"},
  79. )
  80. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={overlay_token}")
  81. assert response.status_code == 401
  82. class TestOverlayFeedPayload:
  83. async def test_payload_shape_includes_filename_fields(self, async_client: AsyncClient, printer_row):
  84. """Unlike the Cam Wall, the overlay *does* carry the filename fields —
  85. that is what distinguishes the scope. Assert the exact key set so the
  86. payload can't silently grow to leak more than the overlay draws.
  87. """
  88. jwt = await setup_admin(async_client, suffix="_payload")
  89. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  90. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={overlay_token}")
  91. assert response.status_code == 200
  92. entry = response.json()
  93. # Never the secrets — the URL is on a public stream.
  94. for leaked in ("serial_number", "ip_address", "access_code"):
  95. assert leaked not in entry, f"{leaked} must not be served to an overlay token"
  96. assert set(entry) == {
  97. "id",
  98. "name",
  99. "model",
  100. "camera_rotation",
  101. "connected",
  102. "state",
  103. "current_print",
  104. "gcode_file",
  105. "progress",
  106. "remaining_time",
  107. "layer_num",
  108. "total_layers",
  109. "stg_cur_name",
  110. "temperatures",
  111. "time_format",
  112. }
  113. async def test_disconnected_printer_reports_connected_false(self, async_client: AsyncClient, printer_row):
  114. """No MQTT client runs in tests, so the printer has no state — the
  115. overlay must render its offline state rather than erroring.
  116. """
  117. jwt = await setup_admin(async_client, suffix="_offline")
  118. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  119. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={overlay_token}")
  120. entry = response.json()
  121. assert entry["model"] == "P1S"
  122. assert entry["connected"] is False
  123. assert entry["state"] is None
  124. assert entry["current_print"] is None
  125. # Present but empty rather than absent (#1422): the overlay reads the
  126. # key unconditionally, and an offline printer simply has no readings.
  127. assert entry["temperatures"] == {}
  128. async def test_temperatures_are_filtered_not_passed_through(
  129. self, async_client: AsyncClient, printer_row, monkeypatch
  130. ):
  131. """#1422 — the overlay can draw nozzle/bed/chamber, so the feed carries
  132. them. It sends only the readings it draws: `state.temperatures` is also
  133. the MQTT client's working memory and holds private bookkeeping and
  134. derived heater flags that an overlay token has no business seeing.
  135. """
  136. from backend.app.services import printer_manager as pm
  137. class _FakeState:
  138. connected = True
  139. state = "RUNNING"
  140. current_print = "bracket.3mf"
  141. gcode_file = "/data/Metadata/plate_1.gcode"
  142. progress = 42.0
  143. remaining_time = 30
  144. layer_num = 10
  145. total_layers = 100
  146. stg_cur = -1
  147. temperatures = {
  148. "nozzle": 219.7,
  149. "nozzle_target": 220.0,
  150. "bed": 60.0,
  151. "bed_target": 60.0,
  152. "chamber": 38.0,
  153. "nozzle_heating": True,
  154. "_nozzle_target_set_time": 1754300000.0,
  155. }
  156. monkeypatch.setattr(pm.printer_manager, "get_status", lambda _pid: _FakeState())
  157. jwt = await setup_admin(async_client, suffix="_temps")
  158. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  159. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={overlay_token}")
  160. assert response.json()["model"] == "P1S"
  161. temps = response.json()["temperatures"]
  162. assert temps["nozzle"] == 219.7
  163. assert temps["nozzle_target"] == 220.0
  164. assert temps["bed"] == 60.0
  165. # The fixture printer is a P1S — no real chamber sensor, so the
  166. # meaningless reading is dropped rather than drawn on a live stream.
  167. assert "chamber" not in temps
  168. assert "nozzle_heating" not in temps
  169. assert "_nozzle_target_set_time" not in temps
  170. async def test_unknown_model_is_null(self, async_client: AsyncClient, printer_row, db_session):
  171. printer_row.model = None
  172. await db_session.commit()
  173. jwt = await setup_admin(async_client, suffix="_nomodel")
  174. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  175. response = await async_client.get(f"/api/v1/printers/{printer_row.id}/overlay-status?token={overlay_token}")
  176. assert response.status_code == 200
  177. assert response.json()["model"] is None
  178. async def test_unknown_printer_is_404_not_401(self, async_client: AsyncClient):
  179. """A valid token for a printer id that doesn't exist is a 404 — the token
  180. passed the gate, the resource simply isn't there.
  181. """
  182. jwt = await setup_admin(async_client, suffix="_404")
  183. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  184. response = await async_client.get(f"/api/v1/printers/99999/overlay-status?token={overlay_token}")
  185. assert response.status_code == 404
  186. class TestOverlayTokenReachesTheVideo:
  187. """The overlay draws the camera feed, so the same token has to satisfy the
  188. camera-stream gate.
  189. """
  190. async def test_overlay_token_passes_the_camera_stream_gate(self, async_client: AsyncClient):
  191. from backend.app.core.auth import verify_camera_stream_token
  192. jwt = await setup_admin(async_client, suffix="_video")
  193. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  194. assert await verify_camera_stream_token(overlay_token) == ALL_PRINTERS # admin-owned: every printer (#1727)
  195. async def test_overlay_gate_rejects_camera_stream_and_camwall(self, async_client: AsyncClient):
  196. from backend.app.core.auth import verify_overlay_token
  197. jwt = await setup_admin(async_client, suffix="_gate")
  198. stream_token = await mint_token(async_client, jwt, scope="camera_stream")
  199. camwall_token = await mint_token(async_client, jwt, scope="camwall", name="wall")
  200. assert await verify_overlay_token(stream_token) is None
  201. assert await verify_overlay_token(camwall_token) is None
  202. async def test_camwall_gate_rejects_an_overlay_token(self, async_client: AsyncClient):
  203. """Symmetric guard: the new scope must not widen the Cam Wall either."""
  204. from backend.app.core.auth import verify_camwall_token
  205. jwt = await setup_admin(async_client, suffix="_gate_camwall")
  206. overlay_token = await mint_token(async_client, jwt, scope="overlay")
  207. assert await verify_camwall_token(overlay_token) is None