test_overlay_status_api.py 11 KB

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