test_cloud_token_expiry.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. """Tests for Bambu Cloud sign-in expiry detection.
  2. Bambu's access token is opaque — no readable expiry — and Bambuddy does not
  3. persist the refresh token, so the only authority on whether a stored token still
  4. works is Bambu itself. Bambuddy used to pretend otherwise: ``set_token()``
  5. stamped ``token_expiry = now + 30 days`` *every time a stored token was loaded*,
  6. which reset the expiry check on every request and made ``is_authenticated``
  7. incapable of ever returning False. ``/cloud/status`` therefore reported
  8. "connected" indefinitely while every cloud call 401'd, and the user was shown
  9. Bambu's own ``{"error": "Please login."}`` as a toast — on a UI that was
  10. simultaneously telling them they were signed in.
  11. These tests pin: the expiry is no longer invented, a 401 is recorded durably,
  12. a Bambu outage does not masquerade as an expired sign-in, and a fresh login
  13. clears the flag.
  14. """
  15. from __future__ import annotations
  16. from datetime import datetime, timezone
  17. from unittest.mock import AsyncMock, MagicMock
  18. import httpx
  19. import pytest
  20. from backend.app.api.routes.cloud import (
  21. CLOUD_EMAIL_KEY,
  22. CLOUD_REGION_KEY,
  23. CLOUD_TOKEN_INVALID_KEY,
  24. CLOUD_TOKEN_KEY,
  25. clear_token,
  26. is_cloud_token_invalid,
  27. store_token,
  28. )
  29. from backend.app.models.settings import Settings
  30. from backend.app.services import bambu_cloud as bc
  31. from backend.app.services.bambu_cloud import BambuCloudService
  32. @pytest.fixture(autouse=True)
  33. def _clear_validation_cache():
  34. """The validation verdict cache is module-level; don't leak across tests."""
  35. bc.invalidate_validation_cache()
  36. yield
  37. bc.invalidate_validation_cache()
  38. # Bambu's genuine "token expired" 401 body — the only 401 that means sign-out.
  39. _EXPIRY_401_BODY = {"code": 4, "error": "Please login.", "message": ""}
  40. def _service(
  41. status_code: int = 200,
  42. *,
  43. on_auth_failure=None,
  44. raises: Exception | None = None,
  45. body: object | None = None,
  46. json_raises: bool = False,
  47. ):
  48. svc = BambuCloudService(client=MagicMock(spec=httpx.AsyncClient), on_auth_failure=on_auth_failure)
  49. resp = MagicMock()
  50. resp.status_code = status_code
  51. # A 401 defaults to Bambu's expiry body so existing "rejected token" cases
  52. # mean a real expiry; pass body= to exercise a transient/benign 401.
  53. if json_raises:
  54. resp.json = MagicMock(side_effect=ValueError("not json"))
  55. else:
  56. resp.json = MagicMock(return_value=_EXPIRY_401_BODY if (body is None and status_code == 401) else (body or {}))
  57. svc._client.get = AsyncMock(side_effect=raises) if raises else AsyncMock(return_value=resp)
  58. return svc
  59. class TestNoInventedExpiry:
  60. def test_set_token_records_no_expiry(self):
  61. """The bug in one line: this used to be ``now + 30 days``, re-derived on
  62. every request from a token of entirely unknown age."""
  63. svc = _service()
  64. svc.set_token("stored-token-of-unknown-age")
  65. assert svc.token_expiry is None
  66. def test_is_authenticated_means_loaded_not_accepted(self):
  67. """It still answers True for a loaded token — that is all it ever knew.
  68. The point is that nobody may now read it as "Bambu accepts this"."""
  69. svc = _service()
  70. assert svc.is_authenticated is False
  71. svc.set_token("stored-token")
  72. assert svc.is_authenticated is True
  73. class TestValidateToken:
  74. @pytest.mark.asyncio
  75. async def test_accepted_token_returns_true(self):
  76. svc = _service(200)
  77. svc.set_token("good-token")
  78. assert await svc.validate_token() is True
  79. @pytest.mark.asyncio
  80. async def test_rejected_token_returns_false(self):
  81. svc = _service(401) # defaults to Bambu's genuine expiry body
  82. svc.set_token("dead-token")
  83. assert await svc.validate_token() is False
  84. @pytest.mark.asyncio
  85. async def test_transient_401_is_unknown_not_invalid(self):
  86. """A 401 WITHOUT Bambu's expiry signature is edge/endpoint noise, not a
  87. dead token — it must read as unknown, never sign the user out. This is
  88. the regression that logged users out on a single stray 401."""
  89. svc = _service(401, body={"code": 1, "error": "forbidden"})
  90. svc.set_token("good-token")
  91. assert await svc.validate_token() is None
  92. @pytest.mark.asyncio
  93. async def test_unparseable_401_is_unknown_not_invalid(self):
  94. svc = _service(401, json_raises=True)
  95. svc.set_token("good-token")
  96. assert await svc.validate_token() is None
  97. @pytest.mark.asyncio
  98. async def test_expiry_signature_via_please_login_text(self):
  99. """The `code:4` field is primary, but the "Please login." text alone
  100. (no/other code) is still accepted as the expiry signal."""
  101. svc = _service(401, body={"error": "Please login.", "message": ""})
  102. svc.set_token("dead-token")
  103. assert await svc.validate_token() is False
  104. @pytest.mark.asyncio
  105. async def test_no_token_is_not_authenticated(self):
  106. svc = _service(200)
  107. assert await svc.validate_token() is False
  108. @pytest.mark.asyncio
  109. async def test_network_failure_is_unknown_not_invalid(self):
  110. """A Bambu outage must never present as "your sign-in expired" — that
  111. would sign every user out of a perfectly good session."""
  112. svc = _service(raises=httpx.ConnectError("no route to host"))
  113. svc.set_token("good-token")
  114. assert await svc.validate_token() is None
  115. @pytest.mark.asyncio
  116. async def test_server_error_is_unknown_not_invalid(self):
  117. svc = _service(503)
  118. svc.set_token("good-token")
  119. assert await svc.validate_token() is None
  120. @pytest.mark.asyncio
  121. async def test_cloudflare_challenge_is_unknown_not_invalid(self):
  122. """418/403 from Bambu's anti-abuse edge means the *request* was refused,
  123. not the token. Declaring the credential dead there would log users out
  124. whenever Cloudflare gets suspicious of their IP."""
  125. svc = _service(418)
  126. svc.set_token("good-token")
  127. assert await svc.validate_token() is None
  128. @pytest.mark.asyncio
  129. async def test_verdict_is_cached(self):
  130. """/cloud/status is polled by several components; without the cache each
  131. render would put a Bambu round-trip in front of the settings page."""
  132. svc = _service(200)
  133. svc.set_token("good-token")
  134. assert await svc.validate_token() is True
  135. assert await svc.validate_token() is True
  136. assert svc._client.get.await_count == 1
  137. @pytest.mark.asyncio
  138. async def test_cache_is_keyed_per_token(self):
  139. svc = _service(200)
  140. svc.set_token("token-a")
  141. assert await svc.validate_token() is True
  142. other = _service(401)
  143. other.set_token("token-b")
  144. assert await other.validate_token() is False, "a different token must not inherit the cached verdict"
  145. @pytest.mark.asyncio
  146. async def test_login_drops_a_cached_rejection(self):
  147. """Re-login must not leave the user staring at "sign-in expired" for the
  148. rest of the cache TTL."""
  149. svc = _service(401)
  150. svc.set_token("tok")
  151. assert await svc.validate_token() is False
  152. fresh = _service(200)
  153. fresh._set_tokens({"accessToken": "tok"}) # same string, freshly minted upstream
  154. assert await fresh.validate_token() is True
  155. class TestAuthFailureCallback:
  156. @pytest.mark.asyncio
  157. async def test_401_fires_the_callback(self):
  158. calls: list[int] = []
  159. async def _cb() -> None:
  160. calls.append(1)
  161. svc = _service(401, on_auth_failure=_cb)
  162. svc.set_token("dead-token")
  163. await svc.validate_token()
  164. assert calls == [1]
  165. @pytest.mark.asyncio
  166. async def test_reported_once_per_service(self):
  167. """A route that makes several cloud calls must not write the flag once
  168. per call."""
  169. calls: list[int] = []
  170. async def _cb() -> None:
  171. calls.append(1)
  172. svc = _service(401, on_auth_failure=_cb)
  173. svc.set_token("dead-token")
  174. resp = MagicMock()
  175. resp.status_code = 401
  176. resp.json = MagicMock(return_value=_EXPIRY_401_BODY)
  177. await svc._note_response(resp)
  178. await svc._note_response(resp)
  179. await svc._note_response(resp)
  180. assert calls == [1]
  181. @pytest.mark.asyncio
  182. async def test_transient_401_does_not_fire_the_callback(self):
  183. """A benign 401 must not durably invalidate — the callback that persists
  184. the dead-token flag stays untouched."""
  185. calls: list[int] = []
  186. async def _cb() -> None:
  187. calls.append(1)
  188. svc = _service(401, on_auth_failure=_cb, body={"code": 1, "error": "forbidden"})
  189. svc.set_token("good-token")
  190. await svc.validate_token()
  191. assert calls == []
  192. @pytest.mark.asyncio
  193. async def test_success_does_not_fire_the_callback(self):
  194. calls: list[int] = []
  195. async def _cb() -> None:
  196. calls.append(1)
  197. svc = _service(200, on_auth_failure=_cb)
  198. svc.set_token("good-token")
  199. await svc.validate_token()
  200. assert calls == []
  201. @pytest.mark.asyncio
  202. async def test_callback_failure_does_not_mask_the_401(self):
  203. """Recording the dead credential is bookkeeping. If it throws, the caller
  204. must still get the auth failure it was actually waiting for."""
  205. async def _cb() -> None:
  206. raise RuntimeError("database is on fire")
  207. svc = _service(401, on_auth_failure=_cb)
  208. svc.set_token("dead-token")
  209. assert await svc.validate_token() is False
  210. class TestPersistedFlag:
  211. """Auth-disabled deployments keep cloud credentials in the Settings table."""
  212. @pytest.mark.asyncio
  213. async def test_absent_by_default(self, db_session):
  214. assert await is_cloud_token_invalid(db_session, None) is False
  215. @pytest.mark.asyncio
  216. async def test_set_flag_is_read_back(self, db_session):
  217. db_session.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value=datetime.now(timezone.utc).isoformat()))
  218. await db_session.commit()
  219. assert await is_cloud_token_invalid(db_session, None) is True
  220. @pytest.mark.asyncio
  221. async def test_fresh_login_clears_the_flag(self, db_session):
  222. """Otherwise the new sign-in is reported as expired the instant it's stored."""
  223. db_session.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value="2026-07-14T07:00:00+00:00"))
  224. await db_session.commit()
  225. await store_token(db_session, "brand-new-token", "user@example.com", "global", None)
  226. assert await is_cloud_token_invalid(db_session, None) is False
  227. @pytest.mark.asyncio
  228. async def test_logout_clears_the_flag(self, db_session):
  229. for key, value in [
  230. (CLOUD_TOKEN_KEY, "dead"),
  231. (CLOUD_EMAIL_KEY, "user@example.com"),
  232. (CLOUD_REGION_KEY, "global"),
  233. (CLOUD_TOKEN_INVALID_KEY, "2026-07-14T07:00:00+00:00"),
  234. ]:
  235. db_session.add(Settings(key=key, value=value))
  236. await db_session.commit()
  237. await clear_token(db_session, None)
  238. assert await is_cloud_token_invalid(db_session, None) is False
  239. class TestStatusRoute:
  240. """The endpoint that was lying. ``GET /cloud/status`` drives the "Connected
  241. as ..." bar on the Profiles page and the green dot in Settings."""
  242. async def _store(self, db_session, *, invalid: bool = False):
  243. db_session.add(Settings(key=CLOUD_TOKEN_KEY, value="stored-token"))
  244. db_session.add(Settings(key=CLOUD_EMAIL_KEY, value="user@example.com"))
  245. db_session.add(Settings(key=CLOUD_REGION_KEY, value="global"))
  246. if invalid:
  247. db_session.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value="2026-07-14T07:00:00+00:00"))
  248. await db_session.commit()
  249. @pytest.mark.asyncio
  250. async def test_no_token_is_not_expired(self, async_client, db_session):
  251. body = (await async_client.get("/api/v1/cloud/status")).json()
  252. assert body["is_authenticated"] is False
  253. assert body["sign_in_expired"] is False
  254. @pytest.mark.asyncio
  255. async def test_token_bambu_rejects_reports_expired(self, async_client, db_session, monkeypatch):
  256. """The whole bug: a stored token Bambu no longer accepts used to come back
  257. as ``is_authenticated: true``, forever."""
  258. await self._store(db_session)
  259. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=False))
  260. body = (await async_client.get("/api/v1/cloud/status")).json()
  261. assert body["is_authenticated"] is False
  262. assert body["sign_in_expired"] is True
  263. assert body["email"] is None
  264. @pytest.mark.asyncio
  265. async def test_token_bambu_accepts_reports_connected(self, async_client, db_session, monkeypatch):
  266. await self._store(db_session)
  267. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=True))
  268. body = (await async_client.get("/api/v1/cloud/status")).json()
  269. assert body["is_authenticated"] is True
  270. assert body["sign_in_expired"] is False
  271. assert body["email"] == "user@example.com"
  272. @pytest.mark.asyncio
  273. async def test_bambu_unreachable_keeps_the_user_signed_in(self, async_client, db_session, monkeypatch):
  274. """Unknown is not invalid. A Bambu outage must not log the whole install
  275. out of the cloud."""
  276. await self._store(db_session)
  277. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=None))
  278. body = (await async_client.get("/api/v1/cloud/status")).json()
  279. assert body["is_authenticated"] is True
  280. assert body["sign_in_expired"] is False
  281. @pytest.mark.asyncio
  282. async def test_bambu_unreachable_does_not_resurrect_a_known_dead_token(self, async_client, db_session, monkeypatch):
  283. """...but "unknown" must fall back to what we last knew, not to True."""
  284. await self._store(db_session, invalid=True)
  285. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=None))
  286. body = (await async_client.get("/api/v1/cloud/status")).json()
  287. assert body["is_authenticated"] is False
  288. assert body["sign_in_expired"] is True
  289. @pytest.mark.asyncio
  290. async def test_known_dead_token_does_not_re_ask_bambu(self, async_client, db_session, monkeypatch):
  291. """Only a new login can revive it, and that clears the flag — so polling
  292. Bambu on every status call would be pure waste."""
  293. await self._store(db_session, invalid=True)
  294. validate = AsyncMock(return_value=False)
  295. monkeypatch.setattr(BambuCloudService, "validate_token", validate)
  296. await async_client.get("/api/v1/cloud/status")
  297. validate.assert_not_awaited()