test_updates_api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. """Integration tests for Updates API endpoints."""
  2. from pathlib import Path
  3. from unittest.mock import AsyncMock, MagicMock, patch
  4. import pytest
  5. from httpx import AsyncClient
  6. class TestUpdatesAPI:
  7. @pytest.fixture(autouse=True)
  8. def _reset_update_status(self):
  9. """Isolate the module-global ``_update_status`` between tests.
  10. ``POST /updates/apply`` short-circuits (line 850) when ``_update_status``
  11. is ``"downloading"``/``"installing"``, returning a payload WITHOUT the
  12. per-branch keys (``is_windows_installer`` etc.). A prior test that let an
  13. apply flow run leaves the global mid-update, so a later test in the same
  14. parallel worker hits the guard instead of its intended branch. This is
  15. order-dependent — it passes locally but flakes on CI's sharded run
  16. (``test_apply_update_windows_installer_rejection`` KeyError). Reset to
  17. idle before every test so the guard never fires spuriously.
  18. """
  19. from backend.app.api.routes import updates as updates_module
  20. updates_module._update_status = {"status": "idle", "progress": 0, "message": "", "error": None}
  21. yield
  22. @pytest.mark.asyncio
  23. async def test_get_version(self, async_client: AsyncClient):
  24. response = await async_client.get("/api/v1/updates/version")
  25. assert response.status_code == 200
  26. @pytest.mark.asyncio
  27. async def test_apply_update_docker_rejection(self, async_client: AsyncClient):
  28. with (
  29. patch("backend.app.api.routes.updates._is_ha_addon", return_value=False),
  30. patch("backend.app.api.routes.updates._is_docker_environment", return_value=True),
  31. ):
  32. response = await async_client.post("/api/v1/updates/apply")
  33. result = response.json()
  34. assert result["success"] is False
  35. assert result["is_docker"] is True
  36. assert result.get("is_ha_addon") is not True
  37. # Docker message tells the user to docker compose, not HA.
  38. assert "Docker Compose" in result["message"]
  39. @pytest.mark.asyncio
  40. async def test_apply_update_ha_addon_rejection(self, async_client: AsyncClient):
  41. """HA addons are also Docker, so the route must check HA first and
  42. return the HA-specific message — otherwise users see "run docker
  43. compose" advice they can't follow."""
  44. with (
  45. patch("backend.app.api.routes.updates._is_ha_addon", return_value=True),
  46. patch("backend.app.api.routes.updates._is_docker_environment", return_value=True),
  47. ):
  48. response = await async_client.post("/api/v1/updates/apply")
  49. result = response.json()
  50. assert result["success"] is False
  51. assert result["is_ha_addon"] is True
  52. assert result["is_docker"] is True
  53. assert "Home Assistant" in result["message"]
  54. assert "Docker Compose" not in result["message"]
  55. @pytest.mark.asyncio
  56. async def test_apply_update_non_docker(self, async_client: AsyncClient):
  57. """Test non-Docker path - mock _perform_update + _discover_target_release
  58. to prevent side effects (network call to GitHub releases API + actual
  59. git/pip subprocesses)."""
  60. with (
  61. patch("backend.app.api.routes.updates._is_ha_addon", return_value=False),
  62. patch("backend.app.api.routes.updates._is_docker_environment", return_value=False),
  63. patch(
  64. "backend.app.api.routes.updates._discover_target_release",
  65. new_callable=AsyncMock,
  66. return_value="v9.9.9",
  67. ),
  68. patch("backend.app.api.routes.updates._perform_update", new_callable=AsyncMock),
  69. ):
  70. response = await async_client.post("/api/v1/updates/apply")
  71. assert response.json()["success"] is True
  72. def test_is_docker_with_dockerenv(self):
  73. from backend.app.api.routes.updates import _is_docker_environment
  74. with patch("os.path.exists", return_value=True):
  75. assert _is_docker_environment() is True
  76. def test_is_ha_addon_detects_supervisor_token(self):
  77. """HA Supervisor sets SUPERVISOR_TOKEN on every addon container.
  78. That env-var alone is the canonical HA-addon signal."""
  79. from backend.app.api.routes.updates import _is_ha_addon
  80. with patch.dict("os.environ", {"SUPERVISOR_TOKEN": "abc123"}, clear=False):
  81. assert _is_ha_addon() is True
  82. def test_is_ha_addon_false_outside_supervisor(self):
  83. from backend.app.api.routes.updates import _is_ha_addon
  84. with patch.dict("os.environ", {}, clear=True):
  85. assert _is_ha_addon() is False
  86. def test_is_ha_addon_empty_token_treated_as_unset(self):
  87. """An empty string is not a real token — guard against shells that
  88. export the variable empty."""
  89. from backend.app.api.routes.updates import _is_ha_addon
  90. with patch.dict("os.environ", {"SUPERVISOR_TOKEN": ""}, clear=False):
  91. assert _is_ha_addon() is False
  92. @pytest.mark.asyncio
  93. async def test_check_returns_ha_addon_flag_and_method(self, async_client: AsyncClient):
  94. """`/updates/check` must surface the deployment shape so the frontend
  95. can pick the right CTA. HA must take precedence over Docker because
  96. HA addons run *inside* a Docker container — checking docker first
  97. would mis-classify them."""
  98. import httpx as _httpx
  99. fake_release = {
  100. "tag_name": "v999.9.9",
  101. "name": "Far Future Release",
  102. "body": "",
  103. "html_url": "https://example.invalid/r",
  104. "published_at": "2099-01-01T00:00:00Z",
  105. }
  106. class _Resp:
  107. status_code = 200
  108. def raise_for_status(self):
  109. return None
  110. def json(self):
  111. return [fake_release]
  112. class _FakeClient:
  113. async def __aenter__(self):
  114. return self
  115. async def __aexit__(self, *_):
  116. return None
  117. async def get(self, *_, **__):
  118. return _Resp()
  119. with (
  120. patch.object(_httpx, "AsyncClient", _FakeClient),
  121. patch("backend.app.api.routes.updates._is_ha_addon", return_value=True),
  122. patch("backend.app.api.routes.updates._is_docker_environment", return_value=True),
  123. ):
  124. response = await async_client.get("/api/v1/updates/check")
  125. body = response.json()
  126. assert body["is_ha_addon"] is True
  127. assert body["update_method"] == "ha_addon"
  128. # is_docker is preserved alongside so older frontend bundles still
  129. # hit a managed-deployment branch (degrades to Docker UX) instead of
  130. # rendering the in-app Install button.
  131. assert body["is_docker"] is True
  132. @pytest.mark.asyncio
  133. async def test_check_docker_only_returns_docker_method(self, async_client: AsyncClient):
  134. import httpx as _httpx
  135. fake_release = {
  136. "tag_name": "v999.9.9",
  137. "name": "Far Future Release",
  138. "body": "",
  139. "html_url": "https://example.invalid/r",
  140. "published_at": "2099-01-01T00:00:00Z",
  141. }
  142. class _Resp:
  143. status_code = 200
  144. def raise_for_status(self):
  145. return None
  146. def json(self):
  147. return [fake_release]
  148. class _FakeClient:
  149. async def __aenter__(self):
  150. return self
  151. async def __aexit__(self, *_):
  152. return None
  153. async def get(self, *_, **__):
  154. return _Resp()
  155. with (
  156. patch.object(_httpx, "AsyncClient", _FakeClient),
  157. patch("backend.app.api.routes.updates._is_ha_addon", return_value=False),
  158. patch("backend.app.api.routes.updates._is_docker_environment", return_value=True),
  159. ):
  160. response = await async_client.get("/api/v1/updates/check")
  161. body = response.json()
  162. assert body["is_ha_addon"] is False
  163. assert body["is_docker"] is True
  164. assert body["update_method"] == "docker"
  165. @pytest.mark.asyncio
  166. async def test_check_backs_off_after_github_rate_limit(self, async_client: AsyncClient):
  167. """#1420: once GitHub returns 403 with X-RateLimit-Remaining=0, the
  168. next call must short-circuit on the backoff window instead of hitting
  169. api.github.com again. Otherwise the user's logs flood with rate-limit
  170. errors and Bambuddy keeps adding to whatever throttle GitHub applies."""
  171. import time
  172. import httpx as _httpx
  173. import backend.app.api.routes.updates as updates_module
  174. # Reset module-level backoff state between tests.
  175. updates_module._github_rate_limit_until = 0.0
  176. # Future reset time, ~10 minutes ahead — the backoff window we expect.
  177. future_reset = time.time() + 600
  178. class _RateLimitedResp:
  179. status_code = 403
  180. headers = {
  181. "X-RateLimit-Remaining": "0",
  182. "X-RateLimit-Reset": str(int(future_reset)),
  183. }
  184. text = "API rate limit exceeded"
  185. def raise_for_status(self):
  186. raise _httpx.HTTPStatusError("403", request=None, response=self)
  187. def json(self):
  188. return {"message": "API rate limit exceeded"}
  189. call_counter = {"n": 0}
  190. class _FakeClient:
  191. async def __aenter__(self):
  192. return self
  193. async def __aexit__(self, *_):
  194. return None
  195. async def get(self, *_, **__):
  196. call_counter["n"] += 1
  197. return _RateLimitedResp()
  198. try:
  199. with patch.object(_httpx, "AsyncClient", _FakeClient):
  200. first = await async_client.get("/api/v1/updates/check")
  201. second = await async_client.get("/api/v1/updates/check")
  202. finally:
  203. updates_module._github_rate_limit_until = 0.0
  204. # First request reached httpx; second short-circuited on the backoff.
  205. assert call_counter["n"] == 1
  206. first_body = first.json()
  207. second_body = second.json()
  208. assert "rate limit" in (first_body.get("error") or "").lower()
  209. assert "rate limit" in (second_body.get("error") or "").lower()
  210. # Backoff window roughly matches the X-RateLimit-Reset header.
  211. assert second_body.get("retry_after_seconds", 0) > 0
  212. def test_parse_version(self):
  213. from backend.app.api.routes.updates import parse_version
  214. assert parse_version("0.1.5")[:3] == (0, 1, 5)
  215. def test_is_newer_version(self):
  216. from backend.app.api.routes.updates import is_newer_version
  217. assert is_newer_version("0.1.5", "0.1.5b7") is True
  218. def test_parse_github_remote_recognises_ssh_https_and_dotgit(self):
  219. """`_parse_github_remote` must accept the four canonical forms `git
  220. remote -v` prints; anything else returns None so callers can treat
  221. it as 'reset to expected URL'."""
  222. from backend.app.api.routes.updates import _parse_github_remote
  223. assert _parse_github_remote("git@github.com:maziggy/bambuddy.git") == (
  224. "maziggy",
  225. "bambuddy",
  226. )
  227. assert _parse_github_remote("git@github.com:maziggy/bambuddy") == (
  228. "maziggy",
  229. "bambuddy",
  230. )
  231. assert _parse_github_remote("https://github.com/maziggy/bambuddy.git") == (
  232. "maziggy",
  233. "bambuddy",
  234. )
  235. assert _parse_github_remote("https://github.com/maziggy/bambuddy") == (
  236. "maziggy",
  237. "bambuddy",
  238. )
  239. # Non-GitHub host → None (we don't claim ownership over arbitrary
  240. # forge URLs).
  241. assert _parse_github_remote("git@gitlab.com:maziggy/bambuddy.git") is None
  242. # Empty / malformed → None.
  243. assert _parse_github_remote("") is None
  244. assert _parse_github_remote("not-a-url") is None
  245. assert _parse_github_remote("https://github.com/maziggy") is None # no /repo
  246. @pytest.mark.asyncio
  247. async def test_perform_update_preserves_ssh_origin_when_pointing_at_correct_repo(self, tmp_path):
  248. """Regression for the developer-checkout footgun: if origin already
  249. points at github.com/maziggy/bambuddy via SSH, the updater must
  250. leave it alone instead of clobbering it with HTTPS. Pre-fix, every
  251. Apply Update click rewrote `git@github.com:...` to `https://...`,
  252. breaking subsequent `git push` for any developer testing the
  253. upgrade flow against their own checkout."""
  254. from backend.app.api.routes import updates as updates_module
  255. app_dir = tmp_path / "app"
  256. data_dir = tmp_path / "app" / "data"
  257. app_dir.mkdir()
  258. data_dir.mkdir()
  259. (app_dir / "requirements.txt").write_text("fastapi\n")
  260. calls: list[dict] = []
  261. async def fake_create_subprocess_exec(*args, **kwargs):
  262. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  263. proc = MagicMock()
  264. # When the updater asks `git remote get-url origin`, return the
  265. # SSH URL. Every other subprocess returns successfully with no
  266. # output.
  267. if "get-url" in args and "origin" in args:
  268. proc.communicate = AsyncMock(return_value=(b"git@github.com:maziggy/bambuddy.git\n", b""))
  269. else:
  270. proc.communicate = AsyncMock(return_value=(b"", b""))
  271. proc.returncode = 0
  272. return proc
  273. with (
  274. patch.object(updates_module.settings, "base_dir", data_dir),
  275. patch.object(updates_module.settings, "app_dir", app_dir),
  276. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  277. patch.object(
  278. updates_module.asyncio,
  279. "create_subprocess_exec",
  280. side_effect=fake_create_subprocess_exec,
  281. ),
  282. ):
  283. await updates_module._perform_update("v0.2.4b1")
  284. # The updater MUST NOT have run `git remote set-url origin <https>`
  285. # because origin already pointed at the right repo over SSH.
  286. set_url_calls = [c for c in calls if "set-url" in c["args"] and "origin" in c["args"]]
  287. assert not set_url_calls, (
  288. "Updater clobbered an SSH origin pointing at the correct repo. "
  289. "Captured set-url calls: " + repr([c["args"] for c in set_url_calls])
  290. )
  291. @pytest.mark.asyncio
  292. async def test_perform_update_resets_origin_when_pointing_elsewhere(self, tmp_path):
  293. """Defensive: if origin points at a fork or unrelated repo (or is
  294. missing), the updater should still rewrite it to the canonical
  295. HTTPS URL so subsequent fetch / reset works against the right
  296. repo. This is the original behaviour that the SSH-preservation
  297. fix above must NOT regress."""
  298. from backend.app.api.routes import updates as updates_module
  299. from backend.app.core.config import GITHUB_REPO
  300. app_dir = tmp_path / "app"
  301. data_dir = tmp_path / "app" / "data"
  302. app_dir.mkdir()
  303. data_dir.mkdir()
  304. (app_dir / "requirements.txt").write_text("fastapi\n")
  305. calls: list[dict] = []
  306. async def fake_create_subprocess_exec(*args, **kwargs):
  307. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  308. proc = MagicMock()
  309. # origin is set to a fork — must be rewritten.
  310. if "get-url" in args and "origin" in args:
  311. proc.communicate = AsyncMock(return_value=(b"git@github.com:somefork/bambuddy.git\n", b""))
  312. else:
  313. proc.communicate = AsyncMock(return_value=(b"", b""))
  314. proc.returncode = 0
  315. return proc
  316. with (
  317. patch.object(updates_module.settings, "base_dir", data_dir),
  318. patch.object(updates_module.settings, "app_dir", app_dir),
  319. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  320. patch.object(
  321. updates_module.asyncio,
  322. "create_subprocess_exec",
  323. side_effect=fake_create_subprocess_exec,
  324. ),
  325. ):
  326. await updates_module._perform_update("v0.2.4b1")
  327. set_url_calls = [c for c in calls if "set-url" in c["args"] and "origin" in c["args"]]
  328. assert set_url_calls, "Updater must rewrite origin when it points at a fork."
  329. rewritten_to = set_url_calls[0]["args"][-1]
  330. assert rewritten_to == f"https://github.com/{GITHUB_REPO}.git", (
  331. f"Expected origin to be reset to canonical HTTPS URL; got: {rewritten_to}"
  332. )
  333. @pytest.mark.asyncio
  334. async def test_perform_update_resets_to_target_ref_not_hardcoded_main(self, tmp_path):
  335. """Regression for the hardcoded-`origin/main` limitation: the in-app
  336. updater must reset to the caller-supplied target ref (typically a
  337. release tag like `v0.2.4b1` discovered from the GitHub releases API)
  338. so beta releases that don't live on main can actually be installed.
  339. Pre-fix, `_perform_update` issued `git reset --hard origin/main`
  340. verbatim and silently no-op'd whenever the latest release wasn't on
  341. main — leaving a 0.2.3.x user clicking *Apply Update* stranded on
  342. 0.2.3.x. Also asserts the fetch step uses `--tags` so a tag ref is
  343. actually resolvable post-fetch."""
  344. from backend.app.api.routes import updates as updates_module
  345. app_dir = tmp_path / "app"
  346. data_dir = tmp_path / "app" / "data"
  347. app_dir.mkdir()
  348. data_dir.mkdir()
  349. (app_dir / "requirements.txt").write_text("fastapi\n")
  350. calls: list[dict] = []
  351. async def fake_create_subprocess_exec(*args, **kwargs):
  352. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  353. proc = MagicMock()
  354. if "get-url" in args and "origin" in args:
  355. proc.communicate = AsyncMock(return_value=(b"git@github.com:maziggy/bambuddy.git\n", b""))
  356. else:
  357. proc.communicate = AsyncMock(return_value=(b"", b""))
  358. proc.returncode = 0
  359. return proc
  360. with (
  361. patch.object(updates_module.settings, "base_dir", data_dir),
  362. patch.object(updates_module.settings, "app_dir", app_dir),
  363. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  364. patch.object(
  365. updates_module.asyncio,
  366. "create_subprocess_exec",
  367. side_effect=fake_create_subprocess_exec,
  368. ),
  369. ):
  370. await updates_module._perform_update("v0.2.4b1")
  371. # Reset target must be the caller-supplied ref, not "origin/main".
  372. reset_calls = [c for c in calls if "reset" in c["args"] and "--hard" in c["args"]]
  373. assert reset_calls, "git reset must be invoked"
  374. reset_target = reset_calls[0]["args"][-1]
  375. assert reset_target == "v0.2.4b1", (
  376. f"Expected reset target to be the caller-supplied ref 'v0.2.4b1'; "
  377. f"got {reset_target!r}. Regression to a hardcoded 'origin/main' "
  378. "would re-introduce the in-app-updater-can't-install-betas bug."
  379. )
  380. # Fetch must include --tags so v0.2.4b1 (a tag) is locally resolvable.
  381. fetch_calls = [c for c in calls if "fetch" in c["args"]]
  382. assert fetch_calls
  383. assert "--tags" in fetch_calls[0]["args"], (
  384. "Fetch must use --tags so release-tag refs (the production path "
  385. "for tag-based updates) are resolvable for the subsequent reset. "
  386. f"Captured fetch call: {fetch_calls[0]['args']}"
  387. )
  388. # Fetch must include --force so a re-pointed tag on the remote
  389. # (common after re-tagging a release post-release-notes edit) doesn't
  390. # surface as "Failed to fetch updates" to the user just because their
  391. # local copy of the moved tag would be clobbered. The relevant target
  392. # ref is fetched fine; we only want git's tag-clobber to be silent.
  393. assert "--force" in fetch_calls[0]["args"], (
  394. "Fetch must use --force so re-pointed tags on the remote don't "
  395. "fail the whole fetch (the rest of the refs update cleanly). "
  396. f"Captured fetch call: {fetch_calls[0]['args']}"
  397. )
  398. @pytest.mark.asyncio
  399. async def test_apply_update_passes_discovered_release_to_perform_update(self, async_client: AsyncClient):
  400. """End-to-end glue: the route handler calls `_discover_target_release`
  401. to pick the tag (respecting include_beta_updates), then schedules
  402. `_perform_update` with that tag — not with no arg, not with main."""
  403. from backend.app.api.routes import updates as updates_module
  404. captured_ref: list[str] = []
  405. async def fake_perform_update(target_ref):
  406. captured_ref.append(target_ref)
  407. async def fake_discover(_db):
  408. return "v0.2.4b1"
  409. with (
  410. patch.object(updates_module, "_is_ha_addon", return_value=False),
  411. patch.object(updates_module, "_is_docker_environment", return_value=False),
  412. patch.object(updates_module, "_perform_update", side_effect=fake_perform_update),
  413. patch.object(updates_module, "_discover_target_release", side_effect=fake_discover),
  414. ):
  415. response = await async_client.post("/api/v1/updates/apply")
  416. assert response.json()["success"] is True
  417. assert captured_ref == ["v0.2.4b1"], (
  418. f"apply_update must pass the discovered tag to _perform_update; captured invocations: {captured_ref}"
  419. )
  420. @pytest.mark.asyncio
  421. async def test_apply_update_returns_clear_error_when_no_release_resolves(self, async_client: AsyncClient):
  422. """If GitHub is unreachable or no release matches the user's channel,
  423. the route returns a useful error instead of silently kicking off an
  424. update that can't possibly land. Avoids the previous failure mode
  425. where in-app update appeared to succeed but did nothing."""
  426. from backend.app.api.routes import updates as updates_module
  427. async def fake_discover(_db):
  428. return None
  429. # The route guards against a concurrent update via the module-global
  430. # `_update_status` — reset it so a previous test that left the status
  431. # mid-flight doesn't short-circuit this one.
  432. updates_module._update_status = {"status": "idle", "progress": 0, "message": "", "error": None}
  433. with (
  434. patch.object(updates_module, "_is_ha_addon", return_value=False),
  435. patch.object(updates_module, "_is_docker_environment", return_value=False),
  436. patch.object(updates_module, "_discover_target_release", side_effect=fake_discover),
  437. ):
  438. response = await async_client.post("/api/v1/updates/apply")
  439. body = response.json()
  440. assert body["success"] is False
  441. assert "release" in body["message"].lower()
  442. @pytest.mark.asyncio
  443. async def test_perform_update_runs_pip_in_app_dir_not_data_dir(self, tmp_path):
  444. """Native install: `requirements.txt` lives at INSTALL_PATH (the source-
  445. code dir), NOT at DATA_DIR (where systemd sets DATA_DIR=INSTALL_PATH/data).
  446. Pre-fix, the updater ran `pip install -r requirements.txt` with
  447. `cwd=settings.base_dir`, which on a native install resolves to the data
  448. dir — `requirements.txt` isn't there and pip fails with `Could not open
  449. requirements file`. The fix: pip's cwd is `settings.app_dir` (the source
  450. tree) so it can actually find the file.
  451. This test mocks every subprocess so it can capture the cwd of each call
  452. and assert that the pip step runs in app_dir while git steps continue
  453. to run in base_dir (their existing behaviour — git walks up to find
  454. `.git` so that path keeps working)."""
  455. from backend.app.api.routes import updates as updates_module
  456. # Set up fake install layout: app_dir has requirements.txt, data_dir is
  457. # a sibling (mirroring `INSTALL_PATH=/opt/bambuddy`, `DATA_DIR=/opt/bambuddy/data`).
  458. app_dir = tmp_path / "app"
  459. data_dir = tmp_path / "app" / "data"
  460. app_dir.mkdir()
  461. data_dir.mkdir()
  462. (app_dir / "requirements.txt").write_text("fastapi\n")
  463. # Capture every subprocess call's cwd + the executable token.
  464. calls: list[dict] = []
  465. async def fake_create_subprocess_exec(*args, **kwargs):
  466. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  467. proc = MagicMock()
  468. proc.communicate = AsyncMock(return_value=(b"", b""))
  469. proc.returncode = 0
  470. return proc
  471. with (
  472. patch.object(updates_module.settings, "base_dir", data_dir),
  473. patch.object(updates_module.settings, "app_dir", app_dir),
  474. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  475. patch.object(
  476. updates_module.asyncio,
  477. "create_subprocess_exec",
  478. side_effect=fake_create_subprocess_exec,
  479. ),
  480. ):
  481. await updates_module._perform_update("v0.2.4b1")
  482. # Find the pip invocation (sys.executable + "-m" + "pip" + "install").
  483. pip_calls = [c for c in calls if "pip" in c["args"] and "install" in c["args"]]
  484. assert pip_calls, "pip install was never invoked. Captured: " + repr([c["args"] for c in calls])
  485. pip_cwd = pip_calls[0]["cwd"]
  486. assert pip_cwd == str(app_dir), (
  487. f"pip install must run in app_dir ({app_dir}) so it finds "
  488. f"requirements.txt; got cwd={pip_cwd}. Regression to base_dir "
  489. f"breaks every native-install upgrade."
  490. )
  491. # Sanity check: the requirements.txt that pip would read actually exists
  492. # at the captured cwd. If this fails the cwd is wrong even if it isn't
  493. # base_dir — useful diagnostic if someone refactors path handling.
  494. assert (Path(pip_cwd) / "requirements.txt").exists()
  495. @pytest.mark.asyncio
  496. async def test_perform_update_runs_git_in_app_dir_when_data_dir_on_separate_mount(self, tmp_path):
  497. """Regression for #1715: when DATA_DIR is on a path separate from the
  498. install (e.g. WorkingDirectory=/opt/bambuddy + DATA_DIR=/srv/bambuddy/data),
  499. ``base_dir`` and the repo working tree are on different mounts. Pre-fix,
  500. every git subprocess (`remote get-url`, `remote set-url`, `fetch`,
  501. `reset --hard`) used ``cwd=base_dir`` — and git could no longer walk up
  502. to find ``.git`` because the data dir is not a subdir of the repo.
  503. Every update failed with "not a git repository". The fix routes every
  504. git step (and the embedded ``safe.directory`` config) through
  505. ``app_dir`` instead. This test pins the cwd of all four git steps so a
  506. future refactor that re-introduces ``base_dir`` for any of them surfaces
  507. loudly here instead of silently re-breaking native installs."""
  508. from backend.app.api.routes import updates as updates_module
  509. # Separate-mount layout: app_dir and data_dir are SIBLINGS, not parent/
  510. # child. base_dir is not under app_dir, so git cannot walk up.
  511. app_dir = tmp_path / "opt" / "bambuddy"
  512. data_dir = tmp_path / "srv" / "bambuddy" / "data"
  513. app_dir.mkdir(parents=True)
  514. data_dir.mkdir(parents=True)
  515. (app_dir / "requirements.txt").write_text("fastapi\n")
  516. calls: list[dict] = []
  517. async def fake_create_subprocess_exec(*args, **kwargs):
  518. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  519. proc = MagicMock()
  520. if "get-url" in args and "origin" in args:
  521. proc.communicate = AsyncMock(return_value=(b"git@github.com:maziggy/bambuddy.git\n", b""))
  522. else:
  523. proc.communicate = AsyncMock(return_value=(b"", b""))
  524. proc.returncode = 0
  525. return proc
  526. with (
  527. patch.object(updates_module.settings, "base_dir", data_dir),
  528. patch.object(updates_module.settings, "app_dir", app_dir),
  529. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  530. patch.object(
  531. updates_module.asyncio,
  532. "create_subprocess_exec",
  533. side_effect=fake_create_subprocess_exec,
  534. ),
  535. ):
  536. await updates_module._perform_update("v0.2.4b1")
  537. # Every git subprocess must run in app_dir (the working tree). A
  538. # regression to base_dir would silently break #1715-class installs.
  539. git_calls = [c for c in calls if c["args"] and c["args"][0] == "/usr/bin/git"]
  540. assert git_calls, "no git subprocess was invoked; setup is wrong"
  541. wrong_cwd = [c for c in git_calls if c["cwd"] != str(app_dir)]
  542. assert not wrong_cwd, (
  543. "git subprocess ran with cwd != app_dir; #1715 would resurface. "
  544. f"Offending calls: {[(c['args'][1:5], c['cwd']) for c in wrong_cwd]}"
  545. )
  546. # ``safe.directory`` must equal app_dir (the repo root git discovers),
  547. # not the data dir — otherwise git refuses with "dubious ownership"
  548. # even when the cwd is technically correct.
  549. safe_dir_configs = [
  550. arg for c in git_calls for arg in c["args"] if isinstance(arg, str) and arg.startswith("safe.directory=")
  551. ]
  552. assert safe_dir_configs, "safe.directory config was never set on git calls"
  553. assert all(s == f"safe.directory={app_dir}" for s in safe_dir_configs), (
  554. f"safe.directory must point at app_dir ({app_dir}); got {safe_dir_configs}"
  555. )
  556. # --- Windows installer update_method ---
  557. # The Inno-Setup installer stages backend source via ``copytree`` (no
  558. # ``.git``) and does not bundle ``git.exe``. The git-fetch update path
  559. # therefore can't run on those installs — surface a distinct
  560. # ``update_method`` and a release-asset download link instead.
  561. def test_is_windows_installer_install_true_when_no_dot_git(self, tmp_path: Path):
  562. from backend.app.api.routes import updates as updates_module
  563. with (
  564. patch.object(updates_module.sys, "platform", "win32"),
  565. patch.object(updates_module.settings, "app_dir", tmp_path),
  566. ):
  567. assert updates_module._is_windows_installer_install() is True
  568. def test_is_windows_installer_install_false_on_dev_checkout(self, tmp_path: Path):
  569. """A Windows developer with a real ``git clone`` keeps the git path."""
  570. from backend.app.api.routes import updates as updates_module
  571. (tmp_path / ".git").mkdir()
  572. with (
  573. patch.object(updates_module.sys, "platform", "win32"),
  574. patch.object(updates_module.settings, "app_dir", tmp_path),
  575. ):
  576. assert updates_module._is_windows_installer_install() is False
  577. def test_is_windows_installer_install_false_off_windows(self, tmp_path: Path):
  578. from backend.app.api.routes import updates as updates_module
  579. with (
  580. patch.object(updates_module.sys, "platform", "linux"),
  581. patch.object(updates_module.settings, "app_dir", tmp_path),
  582. ):
  583. assert updates_module._is_windows_installer_install() is False
  584. def test_find_windows_installer_asset_prefers_versioned(self):
  585. from backend.app.api.routes.updates import _find_windows_installer_asset
  586. release = {
  587. "assets": [
  588. {"name": "bambuddy-0.2.5b1-windows-x64-setup.exe", "browser_download_url": "https://x/v.exe"},
  589. {"name": "bambuddy-windows-x64-setup.exe", "browser_download_url": "https://x/alias.exe"},
  590. {"name": "checksums.txt", "browser_download_url": "https://x/c.txt"},
  591. ],
  592. }
  593. assert _find_windows_installer_asset(release) == "https://x/v.exe"
  594. def test_find_windows_installer_asset_falls_back_to_alias(self):
  595. from backend.app.api.routes.updates import _find_windows_installer_asset
  596. release = {
  597. "assets": [
  598. {"name": "bambuddy-windows-x64-setup.exe", "browser_download_url": "https://x/alias.exe"},
  599. ],
  600. }
  601. assert _find_windows_installer_asset(release) == "https://x/alias.exe"
  602. def test_find_windows_installer_asset_none_when_missing(self):
  603. from backend.app.api.routes.updates import _find_windows_installer_asset
  604. assert _find_windows_installer_asset({"assets": []}) is None
  605. assert _find_windows_installer_asset({}) is None
  606. @pytest.mark.asyncio
  607. async def test_apply_update_windows_installer_rejection(self, async_client: AsyncClient):
  608. """Direct POST /apply on a Windows-installer install must be rejected
  609. with a friendly message — the git path would error out with "git not
  610. found" (or worse, "not a git repository") if it ran."""
  611. with (
  612. patch("backend.app.api.routes.updates._is_ha_addon", return_value=False),
  613. patch("backend.app.api.routes.updates._is_docker_environment", return_value=False),
  614. patch(
  615. "backend.app.api.routes.updates._is_windows_installer_install",
  616. return_value=True,
  617. ),
  618. ):
  619. response = await async_client.post("/api/v1/updates/apply")
  620. result = response.json()
  621. assert result["success"] is False
  622. assert result["is_windows_installer"] is True
  623. assert "installer" in result["message"].lower()
  624. @pytest.mark.asyncio
  625. async def test_check_windows_installer_returns_method_and_url(self, async_client: AsyncClient):
  626. """/updates/check must surface update_method=windows_installer plus
  627. the installer .exe URL so the frontend can render a Download button
  628. instead of the in-app Install button."""
  629. import httpx as _httpx
  630. fake_release = {
  631. # Non-prerelease tag — beta-channel filter defaults to off, so a
  632. # `b1` suffix would be skipped and the route would return
  633. # "No releases found" before reaching update_method.
  634. "tag_name": "v999.9.9",
  635. "name": "v999.9.9",
  636. "body": "",
  637. "html_url": "https://github.com/maziggy/bambuddy/releases/tag/v999.9.9",
  638. "published_at": "2099-01-01T00:00:00Z",
  639. "assets": [
  640. {
  641. "name": "bambuddy-999.9.9-windows-x64-setup.exe",
  642. "browser_download_url": "https://github.com/maziggy/bambuddy/releases/download/v999.9.9/bambuddy-999.9.9-windows-x64-setup.exe",
  643. },
  644. ],
  645. }
  646. class _Resp:
  647. status_code = 200
  648. def raise_for_status(self):
  649. return None
  650. def json(self):
  651. return [fake_release]
  652. class _FakeClient:
  653. async def __aenter__(self):
  654. return self
  655. async def __aexit__(self, *_):
  656. return None
  657. async def get(self, *_, **__):
  658. return _Resp()
  659. with (
  660. patch.object(_httpx, "AsyncClient", _FakeClient),
  661. patch("backend.app.api.routes.updates._is_ha_addon", return_value=False),
  662. patch("backend.app.api.routes.updates._is_docker_environment", return_value=False),
  663. patch(
  664. "backend.app.api.routes.updates._is_windows_installer_install",
  665. return_value=True,
  666. ),
  667. ):
  668. response = await async_client.get("/api/v1/updates/check")
  669. body = response.json()
  670. assert "update_method" in body, f"unexpected response shape: {body}"
  671. assert body["update_method"] == "windows_installer"
  672. assert body["is_windows_installer"] is True
  673. assert body["installer_download_url"].endswith("bambuddy-999.9.9-windows-x64-setup.exe")