test_github_restore.py 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095
  1. """Unit tests for the Git backup restore service (#2656).
  2. Focus is on the per-category appliers: natural-key matching, the deliberate
  3. refusal to reuse the backup's primary keys, old_id -> new_id remapping for
  4. dependent rows, overwrite-vs-skip, the settings credential blocklist, and the
  5. K-profile paths that depend on live printers.
  6. """
  7. from datetime import datetime, timedelta
  8. from types import SimpleNamespace
  9. from unittest.mock import AsyncMock, MagicMock, patch
  10. import pytest
  11. from sqlalchemy import select
  12. from backend.app.models.archive import PrintArchive
  13. from backend.app.models.settings import Settings
  14. from backend.app.models.spool import Spool
  15. from backend.app.models.spool_usage_history import SpoolUsageHistory
  16. from backend.app.models.user import User
  17. from backend.app.schemas.github_backup import GitHubRestoreRequest, RestoreCategory
  18. from backend.app.services.github_restore import (
  19. _COMPANION_CREDENTIAL_ENV,
  20. _COMPANION_CREDENTIALS,
  21. _COMPANION_EXPOSURE_TOGGLES,
  22. ARCHIVES_PATH,
  23. SETTINGS_PATH,
  24. SPOOL_USAGE_PATH,
  25. SPOOLS_PATH,
  26. GitHubRestoreService,
  27. _CategoryTally,
  28. _is_blocked_setting_key,
  29. _is_protected_setting_key,
  30. _is_usable_credential,
  31. _parse_dt,
  32. _setting_value_is_true,
  33. _SettingsPlan,
  34. )
  35. def _service() -> GitHubRestoreService:
  36. return GitHubRestoreService()
  37. def _messages(tally: _CategoryTally) -> list[str]:
  38. """The English rendering of each note.
  39. Notes are ``{code, params, message}`` since they became translatable
  40. (#2656); asserting on the message keeps these tests readable while
  41. ``_codes`` covers the half a client actually keys on.
  42. """
  43. return [note["message"] for note in tally.notes]
  44. def _codes(tally: _CategoryTally) -> list[str]:
  45. return [note["code"] for note in tally.notes]
  46. class TestParseDt:
  47. def test_parses_str_datetime_the_backup_writes(self):
  48. assert _parse_dt("2026-07-27 06:02:05.123456") == datetime(2026, 7, 27, 6, 2, 5, 123456)
  49. def test_parses_iso_with_t_separator(self):
  50. assert _parse_dt("2026-07-27T06:02:05") == datetime(2026, 7, 27, 6, 2, 5)
  51. @pytest.mark.parametrize("value", ["", None, "not a date", 12345, {}])
  52. def test_returns_none_for_junk(self, value):
  53. assert _parse_dt(value) is None
  54. def test_an_offset_is_normalised_to_naive_utc(self):
  55. """Every DateTime column here is naive UTC; an aware value cannot be
  56. written to one without silently shifting the wall clock, nor compared
  57. against one without raising."""
  58. assert _parse_dt("2026-07-27T08:02:05+02:00") == datetime(2026, 7, 27, 6, 2, 5)
  59. assert _parse_dt("2026-07-27T06:02:05+00:00").tzinfo is None
  60. class TestSettingKeyBlocklist:
  61. @pytest.mark.parametrize(
  62. "key",
  63. [
  64. "bambu_cloud_token",
  65. "auth_secret_key",
  66. "ha_token",
  67. "prometheus_token",
  68. "printer_access_code",
  69. "smtp_password",
  70. "some_api_key",
  71. "ftp_passphrase",
  72. "MQTT_SECRET",
  73. ],
  74. )
  75. def test_credential_like_keys_are_blocked(self, key):
  76. assert _is_blocked_setting_key(key) is True
  77. @pytest.mark.parametrize(
  78. "key",
  79. ["low_stock_threshold", "currency", "theme", "local_backup_enabled", "timezone"],
  80. )
  81. def test_ordinary_keys_are_allowed(self, key):
  82. assert _is_blocked_setting_key(key) is False
  83. @pytest.mark.parametrize(
  84. "key",
  85. ["auth_enabled", "advanced_auth_enabled", "local_login_enabled", "setup_completed"],
  86. )
  87. def test_auth_policy_keys_are_protected(self, key):
  88. # Not credential-shaped, so the secret hints never catch them.
  89. assert _is_blocked_setting_key(key) is False
  90. assert _is_protected_setting_key(key) is True
  91. @pytest.mark.parametrize("key", ["currency", "ldap_enabled", "auth_secret_key"])
  92. def test_protected_set_is_only_the_auth_policy_keys(self, key):
  93. assert _is_protected_setting_key(key) is False
  94. def test_ha_token_from_env_is_deliberately_not_carved_out(self):
  95. """Recorded so the review's question about it is not re-litigated.
  96. ``ha_token_from_env`` looks like a false positive for the ``token`` hint,
  97. but it is only ever constructed in the settings GET response
  98. (``get_homeassistant_settings``). It is absent from ``AppSettingsUpdate``
  99. and so is never a ``Settings`` row — it cannot reach a backup, which
  100. makes an allowlist entry for it dead code.
  101. Carving it out would also be a live hole rather than a tidy-up: an
  102. attacker-authored ``settings/app_settings.json`` could then get a
  103. ``*token*``-named row written simply by choosing that name. This
  104. blocklist's whole job is belt-and-braces, so a name-shaped exception to
  105. it is exactly the wrong shape of fix.
  106. """
  107. assert _is_blocked_setting_key("ha_token_from_env") is True
  108. class TestCategoryTally:
  109. def test_a_note_carries_code_params_and_english(self):
  110. tally = _CategoryTally()
  111. tally.note("noData", "No data of this kind in this backup")
  112. tally.note("spoolUsageUnresolved", "2 usage record(s) skipped", count=2)
  113. assert tally.notes == [
  114. {"code": "noData", "params": {}, "message": "No data of this kind in this backup"},
  115. {"code": "spoolUsageUnresolved", "params": {"count": 2}, "message": "2 usage record(s) skipped"},
  116. ]
  117. def test_notes_are_deduplicated(self):
  118. tally = _CategoryTally()
  119. tally.note("noData", "same")
  120. tally.note("noData", "same")
  121. assert len(tally.notes) == 1
  122. def test_the_same_code_with_different_params_is_kept(self):
  123. """Two printers can both be offline, and the user needs both names."""
  124. tally = _CategoryTally()
  125. tally.note("kprofilesPrinterOffline", "A is not connected", printer="A")
  126. tally.note("kprofilesPrinterOffline", "B is not connected", printer="B")
  127. assert len(tally.notes) == 2
  128. def test_notes_are_bounded(self):
  129. tally = _CategoryTally()
  130. for i in range(50):
  131. tally.note("noData", f"note {i}", index=i)
  132. assert len(tally.notes) == 20
  133. class TestRestoreRequestSchema:
  134. def test_rejects_empty_category_list(self):
  135. with pytest.raises(ValueError):
  136. GitHubRestoreRequest(categories=[])
  137. def test_deduplicates_categories(self):
  138. request = GitHubRestoreRequest(
  139. categories=[RestoreCategory.SPOOLS, RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  140. )
  141. assert request.categories == [RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  142. def test_defaults_to_head(self):
  143. assert GitHubRestoreRequest(categories=[RestoreCategory.SPOOLS]).ref == "HEAD"
  144. @pytest.mark.parametrize("ref", ["HEAD", "abc1234", "a" * 40])
  145. def test_accepts_valid_refs(self, ref):
  146. assert GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS]).ref == ref
  147. @pytest.mark.parametrize("ref", ["abc", "main", "../etc/passwd", "a" * 41, "zzzzzzz", "abc 123"])
  148. def test_rejects_refs_that_are_not_object_names(self, ref):
  149. with pytest.raises(ValueError):
  150. GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS])
  151. class TestRestoreSettings:
  152. @pytest.mark.asyncio
  153. async def test_inserts_missing_keys(self, db_session):
  154. tally = _CategoryTally()
  155. payload = {"version": "1.0", "settings": {"currency": "EUR", "theme": "dark"}}
  156. await _service()._restore_settings(db_session, payload, overwrite=False, tally=tally)
  157. await db_session.commit()
  158. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  159. assert rows == {"currency": "EUR", "theme": "dark"}
  160. assert tally.restored == 2
  161. @pytest.mark.asyncio
  162. async def test_skips_existing_key_when_overwrite_off(self, db_session):
  163. db_session.add(Settings(key="currency", value="USD"))
  164. await db_session.commit()
  165. tally = _CategoryTally()
  166. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=False, tally=tally)
  167. await db_session.commit()
  168. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  169. assert row.value == "USD"
  170. assert tally.skipped == 1
  171. assert tally.restored == 0
  172. @pytest.mark.asyncio
  173. async def test_overwrites_existing_key_when_enabled(self, db_session):
  174. db_session.add(Settings(key="currency", value="USD"))
  175. await db_session.commit()
  176. tally = _CategoryTally()
  177. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=True, tally=tally)
  178. await db_session.commit()
  179. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  180. assert row.value == "EUR"
  181. assert tally.restored == 1
  182. @pytest.mark.asyncio
  183. async def test_credential_keys_are_never_restored(self, db_session):
  184. """A backup predating the collector's denylist can still contain secrets."""
  185. tally = _CategoryTally()
  186. payload = {"settings": {"currency": "EUR", "bambu_cloud_token": "leaked", "ha_token": "leaked"}}
  187. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  188. await db_session.commit()
  189. keys = {s.key for s in (await db_session.execute(select(Settings))).scalars().all()}
  190. assert keys == {"currency"}
  191. # Refusals are notes, not tally rows: the preview never counted these
  192. # keys, so counting them here would put the total above what the user
  193. # was shown before they pressed Restore.
  194. assert tally.skipped == 0
  195. assert any("credential-like" in note for note in _messages(tally))
  196. @pytest.mark.asyncio
  197. async def test_auth_settings_are_never_restored(self, db_session):
  198. """Restoring auth_enabled=false would disable auth behind the cache's back."""
  199. db_session.add(Settings(key="auth_enabled", value="true"))
  200. db_session.add(Settings(key="local_login_enabled", value="true"))
  201. await db_session.commit()
  202. tally = _CategoryTally()
  203. payload = {
  204. "settings": {
  205. "currency": "EUR",
  206. "auth_enabled": "false",
  207. "advanced_auth_enabled": "false",
  208. "local_login_enabled": "false",
  209. "setup_completed": "false",
  210. }
  211. }
  212. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  213. await db_session.commit()
  214. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  215. assert rows["auth_enabled"] == "true"
  216. assert rows["local_login_enabled"] == "true"
  217. assert "advanced_auth_enabled" not in rows
  218. assert "setup_completed" not in rows
  219. assert rows["currency"] == "EUR"
  220. assert tally.restored == 1
  221. # As above: refused keys are outside the preview's count, so outside the
  222. # tally too.
  223. assert tally.skipped == 0
  224. assert any("authentication setting" in note for note in _messages(tally))
  225. @pytest.mark.asyncio
  226. async def test_missing_payload_is_noted_not_fatal(self, db_session):
  227. tally = _CategoryTally()
  228. await _service()._restore_settings(db_session, None, overwrite=True, tally=tally)
  229. assert tally.restored == 0
  230. assert _codes(tally) == ["noData"]
  231. class TestSettingValueIsTrue:
  232. """Only the spellings a reader actually treats as "on" count as on."""
  233. @pytest.mark.parametrize("value", ["true", "TRUE", " True ", True])
  234. def test_on(self, value):
  235. assert _setting_value_is_true(value) is True
  236. @pytest.mark.parametrize("value", ["false", "1", "on", "yes", "", None, False, 0])
  237. def test_off(self, value):
  238. # "1"/"on"/"yes" are deliberately off: no reader in the codebase treats
  239. # them as on, so restoring one cannot switch anything on either.
  240. assert _setting_value_is_true(value) is False
  241. class TestUsableCredential:
  242. @pytest.mark.parametrize("value", ["s3cret", " x "])
  243. def test_present_values_are_usable(self, value):
  244. assert _is_usable_credential(value) is True
  245. @pytest.mark.parametrize("value", [None, "", " "])
  246. def test_absent_or_blank_is_not(self, value):
  247. # A present-but-blank prometheus_token row is exactly the `if token:`
  248. # hole in the metrics route, so it must not count as protection.
  249. assert _is_usable_credential(value) is False
  250. class TestCompanionCredentials:
  251. """Toggles whose safety depends on a credential the restore refuses to write.
  252. ``prometheus_enabled`` is the sharp one. ``/api/v1/metrics`` is a public
  253. route whose only gate is a non-empty ``prometheus_token``, so restoring the
  254. toggle onto an instance that has no token row publishes the entire metrics
  255. body to anyone who can reach the port — and with overwrite *off*, since the
  256. row is missing rather than present. The other four break an integration
  257. rather than open one, but they are the same shape.
  258. """
  259. async def _restore(self, db, tally=None, overwrite=False, **settings) -> _CategoryTally:
  260. tally = tally or _CategoryTally()
  261. await _service()._restore_settings(db, {"settings": settings}, overwrite=overwrite, tally=tally)
  262. await db.commit()
  263. return tally
  264. async def _rows(self, db) -> dict:
  265. return {s.key: s.value for s in (await db.execute(select(Settings))).scalars().all()}
  266. # --- The refusal itself ------------------------------------------------
  267. @pytest.mark.asyncio
  268. async def test_prometheus_toggle_is_refused_when_its_token_was_skipped(self, db_session):
  269. """The headline case: overwrite off, empty database, endpoint stays shut."""
  270. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  271. rows = await self._rows(db_session)
  272. assert rows == {"currency": "EUR"}
  273. assert any("prometheus_enabled" in note and "switched off" in note for note in _messages(tally))
  274. @pytest.mark.asyncio
  275. @pytest.mark.parametrize("toggle,credential", sorted(_COMPANION_CREDENTIALS.items()))
  276. async def test_every_pair_refuses_its_toggle(self, db_session, toggle, credential, monkeypatch):
  277. monkeypatch.delenv("HA_TOKEN", raising=False)
  278. await self._restore(db_session, **{toggle: "true", credential: "s3cret"})
  279. assert toggle not in await self._rows(db_session)
  280. @pytest.mark.asyncio
  281. async def test_ha_toggle_is_refused_when_the_environment_has_no_token(self, db_session, monkeypatch):
  282. monkeypatch.delenv("HA_TOKEN", raising=False)
  283. await self._restore(db_session, ha_enabled="true", ha_token="s3cret", ha_url="http://ha.local")
  284. rows = await self._rows(db_session)
  285. assert "ha_enabled" not in rows
  286. assert rows["ha_url"] == "http://ha.local"
  287. @pytest.mark.asyncio
  288. async def test_a_blank_local_credential_row_is_not_usable(self, db_session):
  289. db_session.add(Settings(key="prometheus_token", value=""))
  290. await db_session.commit()
  291. await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  292. assert "prometheus_enabled" not in await self._rows(db_session)
  293. @pytest.mark.asyncio
  294. @pytest.mark.parametrize("value", ["TRUE", " True ", True])
  295. async def test_true_is_refused_however_it_is_spelled(self, db_session, value):
  296. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  297. assert "prometheus_enabled" not in await self._rows(db_session)
  298. # --- Ruling 3: the tally counts what the preview counted ---------------
  299. @pytest.mark.asyncio
  300. async def test_refusals_are_not_counted_in_the_tally(self, db_session):
  301. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  302. assert (tally.restored, tally.skipped, tally.failed) == (1, 0, 0)
  303. @pytest.mark.asyncio
  304. async def test_tally_total_equals_the_preview_item_count(self, db_session):
  305. """The ruling, encoded: the user is shown a number, and it has to hold.
  306. Off by three before this change — the two name-based refusals and the
  307. companion one were all counted as ``skipped`` despite never being in the
  308. preview's count.
  309. """
  310. db_session.add(Settings(key="theme", value="light"))
  311. await db_session.commit()
  312. values = {
  313. "currency": "EUR", # inserted -> restored
  314. "theme": "dark", # exists, overwrite off -> skipped
  315. "low_stock_threshold": None, # no value -> skipped
  316. "": "junk", # unusable key -> failed
  317. "bambu_cloud_token": "x", # blocked -> refused
  318. "auth_enabled": "false", # protected -> refused
  319. "prometheus_enabled": "true", # companion -> refused
  320. "prometheus_token": "s3cret", # blocked -> refused
  321. }
  322. item_count, _ = await _service()._count_items(
  323. db_session, RestoreCategory.SETTINGS, {SETTINGS_PATH: {"settings": values}}
  324. )
  325. tally = _CategoryTally()
  326. await _service()._restore_settings(db_session, {"settings": values}, overwrite=False, tally=tally)
  327. await db_session.commit()
  328. assert tally.restored + tally.skipped + tally.failed == item_count
  329. assert (tally.restored, tally.skipped, tally.failed) == (1, 2, 1)
  330. @pytest.mark.asyncio
  331. async def test_preview_count_drops_by_one_when_the_local_credential_is_missing(self, db_session):
  332. parsed = {
  333. SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true", "prometheus_token": "s3cret"}}
  334. }
  335. refused_count, refused_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  336. db_session.add(Settings(key="prometheus_token", value="already-set"))
  337. await db_session.commit()
  338. allowed_count, allowed_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  339. assert refused_count == allowed_count - 1
  340. assert refused_detail.code == "settingsCompanionWillSkip"
  341. assert refused_detail.params == {"count": 1, "companion": 1}
  342. # Nothing is being left off now, so the wording drops back to the plain
  343. # credential caveat.
  344. assert allowed_detail.code == "settingsCredentialsWillSkip"
  345. # --- The exposure class: a blank backup credential is the hole ----------
  346. #
  347. # The rule's second condition — "the backup carried a usable credential" —
  348. # is what stops it refusing an anonymous MQTT broker. It does not transfer to
  349. # Prometheus: a backup taken on an instance that enabled Prometheus without a
  350. # token (the field is optional and defaults to "") carries the toggle and no
  351. # usable token, and writing it opens /api/v1/metrics just as wide. That is
  352. # the *more* likely source of the exposure, not the less.
  353. @pytest.mark.asyncio
  354. async def test_prometheus_is_refused_when_the_backup_has_no_token_key_at_all(self, db_session):
  355. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true")
  356. rows = await self._rows(db_session)
  357. assert rows == {"currency": "EUR"}
  358. assert any("prometheus_enabled" in note and "switched off" in note for note in _messages(tally))
  359. @pytest.mark.asyncio
  360. @pytest.mark.parametrize("token", ["", " "])
  361. async def test_prometheus_is_refused_when_the_backup_token_is_blank(self, db_session, token):
  362. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token=token)
  363. assert "prometheus_enabled" not in await self._rows(db_session)
  364. assert "settingsCompanionSkipped" in _codes(tally)
  365. @pytest.mark.asyncio
  366. async def test_the_preview_says_so_with_no_credential_key_to_skip(self, db_session):
  367. """The wording has to survive ``blocked`` being empty.
  368. The shared caveat counts credential-like keys *and* switches; on this
  369. payload there are no credential-like keys, so "0 credential-like key(s)
  370. will be skipped" would be noise.
  371. """
  372. parsed = {SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true"}}}
  373. count, detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  374. assert count == 1
  375. assert detail.code == "settingsCompanionOnlyWillSkip"
  376. assert detail.params == {"companion": 1}
  377. @pytest.mark.asyncio
  378. async def test_the_availability_class_keeps_the_backup_credential_condition(self, db_session):
  379. """The other half of the same change: only Prometheus loses condition 2.
  380. Absent is treated like blank here — an anonymous broker or bind is a
  381. working config, so refusing it would be a false positive.
  382. """
  383. await self._restore(db_session, mqtt_enabled="true", ldap_enabled="true", virtual_printer_enabled="true")
  384. rows = await self._rows(db_session)
  385. assert rows["mqtt_enabled"] == "true"
  386. assert rows["ldap_enabled"] == "true"
  387. assert rows["virtual_printer_enabled"] == "true"
  388. def test_every_exposure_toggle_is_a_companion_toggle(self):
  389. assert _COMPANION_EXPOSURE_TOGGLES.issubset(_COMPANION_CREDENTIALS)
  390. # --- Controls: over-refusal is the real risk here ----------------------
  391. @pytest.mark.asyncio
  392. async def test_a_usable_local_credential_lets_the_toggle_through(self, db_session):
  393. db_session.add(Settings(key="prometheus_token", value="already-set"))
  394. await db_session.commit()
  395. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  396. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  397. assert not any("switched off" in note for note in _messages(tally))
  398. @pytest.mark.asyncio
  399. async def test_the_exposure_route_still_stands_down_for_a_local_token(self, db_session):
  400. """Skipping condition 2 must not skip the local-state pass with it."""
  401. db_session.add(Settings(key="prometheus_token", value="already-set"))
  402. await db_session.commit()
  403. tally = await self._restore(db_session, prometheus_enabled="true")
  404. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  405. assert not any("switched off" in note for note in _messages(tally))
  406. @pytest.mark.asyncio
  407. async def test_the_exposure_route_still_stands_down_when_already_on(self, db_session):
  408. """The exposure pre-dates this restore either way — see ruling 3."""
  409. db_session.add(Settings(key="prometheus_enabled", value="true"))
  410. await db_session.commit()
  411. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true")
  412. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  413. assert not any("switched off" in note for note in _messages(tally))
  414. @pytest.mark.asyncio
  415. async def test_an_anonymous_broker_is_not_a_false_positive(self, db_session):
  416. """mqtt_relay passes an empty password straight through — a real config."""
  417. tally = await self._restore(db_session, mqtt_enabled="true", mqtt_broker="10.0.0.5")
  418. assert (await self._rows(db_session))["mqtt_enabled"] == "true"
  419. assert not any("switched off" in note for note in _messages(tally))
  420. @pytest.mark.asyncio
  421. async def test_an_anonymous_ldap_bind_is_not_a_false_positive(self, db_session):
  422. """Same for a backup that carries the key with a blank value."""
  423. tally = await self._restore(db_session, ldap_enabled="true", ldap_bind_password=" ")
  424. assert (await self._rows(db_session))["ldap_enabled"] == "true"
  425. assert not any("switched off" in note for note in _messages(tally))
  426. @pytest.mark.asyncio
  427. async def test_turning_a_toggle_off_is_always_written(self, db_session):
  428. await self._restore(db_session, prometheus_enabled="false", prometheus_token="s3cret")
  429. assert (await self._rows(db_session))["prometheus_enabled"] == "false"
  430. @pytest.mark.asyncio
  431. @pytest.mark.parametrize("value", ["1", "on", "yes"])
  432. async def test_spellings_no_reader_treats_as_on_are_written(self, db_session, value):
  433. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  434. assert (await self._rows(db_session))["prometheus_enabled"] == value
  435. @pytest.mark.asyncio
  436. async def test_ha_token_in_the_environment_counts_as_usable(self, db_session, monkeypatch):
  437. monkeypatch.setenv("HA_TOKEN", "from-env")
  438. await self._restore(db_session, ha_enabled="true", ha_token="s3cret")
  439. assert (await self._rows(db_session))["ha_enabled"] == "true"
  440. @pytest.mark.asyncio
  441. async def test_a_toggle_already_on_locally_is_written(self, db_session):
  442. """The exposure pre-dates the restore, so "left switched off" would be a lie."""
  443. db_session.add(Settings(key="prometheus_enabled", value="true"))
  444. await db_session.commit()
  445. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true", prometheus_token="s3cret")
  446. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  447. assert not any("switched off" in note for note in _messages(tally))
  448. # --- The map itself ----------------------------------------------------
  449. def test_every_companion_credential_is_blocked_and_no_toggle_is(self):
  450. """Guards the rule against a future edit to _SECRET_KEY_HINTS.
  451. If a credential stopped being blocked, its toggle would travel with it
  452. and the refusal would be pointless; if a toggle started being blocked,
  453. the pair would never be reached at all.
  454. """
  455. for toggle, credential in _COMPANION_CREDENTIALS.items():
  456. assert _is_blocked_setting_key(credential) is True, credential
  457. assert _is_blocked_setting_key(toggle) is False, toggle
  458. assert _is_protected_setting_key(toggle) is False, toggle
  459. def test_every_environment_override_names_a_companion_credential(self):
  460. assert set(_COMPANION_CREDENTIAL_ENV) <= set(_COMPANION_CREDENTIALS.values())
  461. @pytest.mark.asyncio
  462. async def test_plan_leaves_unusable_key_names_in_no_bucket(self, db_session):
  463. """They are the restore's ``failed``, not a refusal."""
  464. plan = await _service()._plan_settings(db_session, {"": "x", 7: "y", "currency": "EUR"})
  465. assert plan == _SettingsPlan()
  466. class TestSpoolTagOverwrite:
  467. """Overwrite must not write the backup's *other* tag key onto a matched spool.
  468. ``tag_uid`` and ``tray_uuid`` are both in the overwrite ``setattr`` loop, and
  469. neither column has a unique constraint, so writing one onto a spool matched
  470. by the other silently creates a duplicate tag rather than erroring. After
  471. that ``_find_spool``'s ``.first()`` is non-deterministic and an AMS tag
  472. lookup resolves to an arbitrary one of the two. The same loop can also clear
  473. a tag the user has scanned since the backup was taken.
  474. """
  475. def _entry(self, **overrides):
  476. entry = {
  477. "id": 41,
  478. "material": "PLA",
  479. "brand": "Bambu Lab",
  480. "created_at": "2026-01-05 12:00:00",
  481. "tag_uid": "TAG-A",
  482. "tray_uuid": None,
  483. }
  484. entry.update(overrides)
  485. return entry
  486. async def _restore(self, db, entry, tally=None):
  487. tally = tally or _CategoryTally()
  488. await _service()._restore_spools(db, {"spools": [entry]}, None, True, tally, {})
  489. await db.commit()
  490. return tally
  491. @pytest.mark.asyncio
  492. async def test_an_empty_incoming_tag_does_not_clear_a_scanned_one(self, db_session):
  493. """The backup predates the scan, so the local tag is the newer fact."""
  494. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-LIVE"))
  495. await db_session.commit()
  496. tally = await self._restore(db_session, self._entry(tray_uuid=None))
  497. row = (await db_session.execute(select(Spool))).scalar_one()
  498. assert row.tray_uuid == "TRAY-LIVE"
  499. assert any(note["code"] == "spoolTagKept" for note in tally.notes)
  500. @pytest.mark.asyncio
  501. async def test_a_tag_another_spool_already_holds_is_not_written(self, db_session):
  502. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A"))
  503. db_session.add(Spool(material="PETG", brand="Other", tray_uuid="TRAY-B"))
  504. await db_session.commit()
  505. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-B"))
  506. holders = (await db_session.execute(select(Spool).where(Spool.tray_uuid == "TRAY-B"))).scalars().all()
  507. assert len(holders) == 1, "a duplicate tray_uuid makes AMS lookups non-deterministic"
  508. assert holders[0].material == "PETG"
  509. assert any(note["code"] == "spoolTagKept" for note in tally.notes)
  510. @pytest.mark.asyncio
  511. async def test_the_note_counts_every_column_it_kept(self, db_session):
  512. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-LIVE"))
  513. db_session.add(Spool(material="PETG", brand="Other", tag_uid="TAG-CLASH"))
  514. await db_session.commit()
  515. # Matched on tray_uuid, so the guard judges tag_uid: it clashes.
  516. tally = await self._restore(db_session, self._entry(tag_uid="TAG-CLASH", tray_uuid="TRAY-LIVE"))
  517. row = (await db_session.execute(select(Spool).where(Spool.tray_uuid == "TRAY-LIVE"))).scalar_one()
  518. assert row.tag_uid == "TAG-A"
  519. note = next(n for n in tally.notes if n["code"] == "spoolTagKept")
  520. assert note["params"] == {"count": 1}
  521. # --- Controls ----------------------------------------------------------
  522. @pytest.mark.asyncio
  523. async def test_a_free_tag_is_still_written(self, db_session):
  524. """The point of overwrite: a spool that gained a tray_uuid gets it."""
  525. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A"))
  526. await db_session.commit()
  527. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-NEW"))
  528. row = (await db_session.execute(select(Spool))).scalar_one()
  529. assert row.tray_uuid == "TRAY-NEW"
  530. assert not any(note["code"] == "spoolTagKept" for note in tally.notes)
  531. @pytest.mark.asyncio
  532. async def test_an_unchanged_tag_is_not_reported_as_kept(self, db_session):
  533. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-A"))
  534. await db_session.commit()
  535. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-A"))
  536. assert not any(note["code"] == "spoolTagKept" for note in tally.notes)
  537. @pytest.mark.asyncio
  538. async def test_a_new_spool_keeps_both_tags_from_the_backup(self, db_session):
  539. """The guard is an overwrite-only concern; an insert is unaffected."""
  540. await self._restore(db_session, self._entry(tag_uid="TAG-NEW", tray_uuid="TRAY-NEW"))
  541. row = (await db_session.execute(select(Spool))).scalar_one()
  542. assert (row.tag_uid, row.tray_uuid) == ("TAG-NEW", "TRAY-NEW")
  543. @pytest.mark.asyncio
  544. async def test_find_spool_reports_which_key_matched(self, db_session):
  545. db_session.add(Spool(material="PLA", tag_uid="TAG-A"))
  546. db_session.add(Spool(material="PETG", tray_uuid="TRAY-B"))
  547. await db_session.commit()
  548. service = _service()
  549. assert (await service._find_spool(db_session, {"tag_uid": "TAG-A"}))[1] == "tag_uid"
  550. assert (await service._find_spool(db_session, {"tray_uuid": "TRAY-B"}))[1] == "tray_uuid"
  551. assert await service._find_spool(db_session, {"tag_uid": "NOPE"}) == (None, None)
  552. class TestRestoreSpools:
  553. def _spool_entry(self, **overrides):
  554. entry = {
  555. "id": 41,
  556. "material": "PLA",
  557. "subtype": "Basic",
  558. "color_name": "Jade White",
  559. "brand": "Bambu Lab",
  560. "tag_uid": "AABBCCDD",
  561. "created_at": "2026-01-05 12:00:00",
  562. "weight_used": 120.5,
  563. }
  564. entry.update(overrides)
  565. return entry
  566. @pytest.mark.asyncio
  567. async def test_inserts_without_reusing_backup_id(self, db_session):
  568. """The backup's spool.id belongs to an unrelated row today."""
  569. db_session.add(Spool(material="PETG")) # occupies id 1
  570. await db_session.commit()
  571. tally = _CategoryTally()
  572. payload = {"spools": [self._spool_entry(id=1)]}
  573. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  574. await db_session.commit()
  575. spools = (await db_session.execute(select(Spool))).scalars().all()
  576. assert len(spools) == 2
  577. restored = next(s for s in spools if s.tag_uid == "AABBCCDD")
  578. assert restored.id != 1
  579. assert restored.material == "PLA"
  580. @pytest.mark.asyncio
  581. async def test_matches_existing_spool_by_tag_uid(self, db_session):
  582. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  583. await db_session.commit()
  584. tally = _CategoryTally()
  585. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, False, tally, {})
  586. await db_session.commit()
  587. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  588. assert tally.skipped == 1
  589. @pytest.mark.asyncio
  590. async def test_matches_existing_spool_by_tray_uuid(self, db_session):
  591. db_session.add(Spool(material="PLA", tray_uuid="1234" * 8))
  592. await db_session.commit()
  593. tally = _CategoryTally()
  594. entry = self._spool_entry(tag_uid=None, tray_uuid="1234" * 8)
  595. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  596. await db_session.commit()
  597. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  598. assert tally.skipped == 1
  599. @pytest.mark.asyncio
  600. async def test_matches_tagless_spool_by_descriptive_composite(self, db_session):
  601. """Manually added spools have no tag, so fall back to created_at + description."""
  602. db_session.add(
  603. Spool(
  604. material="PLA",
  605. subtype="Basic",
  606. color_name="Jade White",
  607. brand="Bambu Lab",
  608. created_at=datetime(2026, 1, 5, 12, 0, 0),
  609. )
  610. )
  611. await db_session.commit()
  612. tally = _CategoryTally()
  613. entry = self._spool_entry(tag_uid=None)
  614. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  615. await db_session.commit()
  616. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  617. assert tally.skipped == 1
  618. @pytest.mark.asyncio
  619. async def test_overwrite_updates_matched_spool(self, db_session):
  620. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old", weight_used=0))
  621. await db_session.commit()
  622. tally = _CategoryTally()
  623. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, True, tally, {})
  624. await db_session.commit()
  625. row = (await db_session.execute(select(Spool))).scalar_one()
  626. assert row.color_name == "Jade White"
  627. assert row.weight_used == 120.5
  628. assert tally.restored == 1
  629. @pytest.mark.asyncio
  630. async def test_insert_preserves_created_at_so_repeat_restore_is_idempotent(self, db_session):
  631. """Second restore of the same backup must match, not duplicate."""
  632. service = _service()
  633. payload = {"spools": [self._spool_entry(tag_uid=None)]}
  634. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  635. await db_session.commit()
  636. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  637. await db_session.commit()
  638. spools = (await db_session.execute(select(Spool))).scalars().all()
  639. assert len(spools) == 1
  640. assert spools[0].created_at == datetime(2026, 1, 5, 12, 0, 0)
  641. @pytest.mark.asyncio
  642. async def test_usage_history_spool_id_is_remapped(self, db_session):
  643. """Usage rows must point at the new local spool id, not the backup's."""
  644. tally = _CategoryTally()
  645. inventory = {"spools": [self._spool_entry(id=41)]}
  646. usage = {
  647. "usage_history": [
  648. {
  649. "id": 900,
  650. "spool_id": 41,
  651. "printer_id": None,
  652. "print_name": "benchy.3mf",
  653. "archive_id": None,
  654. "weight_used": 12.0,
  655. "percent_used": 5,
  656. "status": "completed",
  657. "created_at": "2026-02-01 09:00:00",
  658. }
  659. ]
  660. }
  661. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  662. await db_session.commit()
  663. spool = (await db_session.execute(select(Spool))).scalar_one()
  664. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  665. assert row.spool_id == spool.id
  666. assert row.print_name == "benchy.3mf"
  667. @pytest.mark.asyncio
  668. async def test_usage_history_archive_id_is_remapped(self, db_session):
  669. tally = _CategoryTally()
  670. inventory = {"spools": [self._spool_entry(id=41)]}
  671. usage = {
  672. "usage_history": [
  673. {
  674. "spool_id": 41,
  675. "archive_id": 77,
  676. "weight_used": 1.0,
  677. "created_at": "2026-02-01 09:00:00",
  678. }
  679. ]
  680. }
  681. archive = PrintArchive(filename="a.3mf", file_path="", file_size=1)
  682. db_session.add(archive)
  683. await db_session.flush()
  684. await _service()._restore_spools(db_session, inventory, usage, False, tally, {77: archive.id})
  685. await db_session.commit()
  686. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  687. assert row.archive_id == archive.id
  688. @pytest.mark.asyncio
  689. async def test_usage_row_with_unresolvable_spool_is_skipped_and_explained(self, db_session):
  690. tally = _CategoryTally()
  691. usage = {"usage_history": [{"spool_id": 999, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}]}
  692. await _service()._restore_spools(db_session, {"spools": []}, usage, False, tally, {})
  693. await db_session.commit()
  694. assert (await db_session.execute(select(SpoolUsageHistory))).scalars().first() is None
  695. assert tally.skipped == 1
  696. assert any("their spool is not in this backup's spool list" in note for note in _messages(tally))
  697. # No remedy is offered, because none exists: overwrite does not change
  698. # which spools land in the map (a skipped spool is mapped anyway), and
  699. # usage history is always restored alongside the spools category.
  700. assert not any("overwrite" in note.lower() for note in _messages(tally))
  701. @pytest.mark.asyncio
  702. async def test_usage_resolves_against_a_spool_skipped_because_overwrite_is_off(self, db_session):
  703. """A skipped spool is still mapped, so its usage rows are not "unresolved".
  704. This is why the note above offers no remedy: turning overwrite on would
  705. not rescue anything, and saying so misdescribed which records are lost.
  706. """
  707. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  708. await db_session.commit()
  709. tally = _CategoryTally()
  710. inventory = {"spools": [self._spool_entry(id=41)]}
  711. usage = {
  712. "usage_history": [
  713. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  714. ]
  715. }
  716. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  717. await db_session.commit()
  718. spool = (await db_session.execute(select(Spool))).scalar_one()
  719. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  720. assert row.spool_id == spool.id
  721. assert not any("spool list" in note for note in _messages(tally))
  722. @pytest.mark.asyncio
  723. async def test_usage_history_is_not_duplicated_on_repeat_restore(self, db_session):
  724. service = _service()
  725. inventory = {"spools": [self._spool_entry(id=41)]}
  726. usage = {
  727. "usage_history": [
  728. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  729. ]
  730. }
  731. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  732. await db_session.commit()
  733. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  734. await db_session.commit()
  735. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  736. assert len(rows) == 1
  737. @pytest.mark.asyncio
  738. async def test_dropped_archive_link_is_explained(self, db_session):
  739. """Spools without archives nulls every usage -> archive link, silently."""
  740. tally = _CategoryTally()
  741. inventory = {"spools": [self._spool_entry(id=41)]}
  742. usage = {
  743. "usage_history": [
  744. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"},
  745. {"spool_id": 41, "archive_id": 8, "weight_used": 2.0, "created_at": "2026-02-01 10:00:00"},
  746. {"spool_id": 41, "weight_used": 3.0, "created_at": "2026-02-01 11:00:00"},
  747. ]
  748. }
  749. # Empty archive_id_map: the archives category wasn't selected, so its
  750. # payload was never fetched and there is nothing to match against.
  751. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  752. await db_session.commit()
  753. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  754. assert len(rows) == 3
  755. assert all(row.archive_id is None for row in rows)
  756. # Only the two that had a link to lose are counted.
  757. assert any("2 usage record(s) restored without their print-history link" in n for n in _messages(tally))
  758. assert any("select Print archives alongside" in n for n in _messages(tally))
  759. @pytest.mark.asyncio
  760. async def test_no_note_when_every_archive_link_resolves(self, db_session):
  761. tally = _CategoryTally()
  762. inventory = {"spools": [self._spool_entry(id=41)]}
  763. usage = {
  764. "usage_history": [
  765. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  766. ]
  767. }
  768. archive = PrintArchive(filename="linked.3mf", file_path="", file_size=1)
  769. db_session.add(archive)
  770. await db_session.flush()
  771. await _service()._restore_spools(db_session, inventory, usage, False, tally, {7: archive.id})
  772. await db_session.commit()
  773. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  774. assert row.archive_id == archive.id
  775. assert not any("print-history link" in note for note in _messages(tally))
  776. @pytest.mark.asyncio
  777. async def test_dangling_printer_id_is_cleared(self, db_session):
  778. tally = _CategoryTally()
  779. inventory = {"spools": [self._spool_entry(id=41)]}
  780. usage = {
  781. "usage_history": [
  782. {"spool_id": 41, "printer_id": 4242, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  783. ]
  784. }
  785. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  786. await db_session.commit()
  787. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  788. assert row.printer_id is None
  789. class TestServerDefaultCreatedAtDedupe:
  790. """Dedupe against rows whose ``created_at`` came from the server default.
  791. Every test above seeds its "existing" row through the restore itself, which
  792. binds ``created_at`` explicitly — so both sides end up in SQLAlchemy's
  793. microsecond format and a SQL ``==`` matches. Rows the *application* created
  794. do not: SQLite fills ``server_default=func.now()`` from
  795. ``CURRENT_TIMESTAMP``, which has second precision, and the two strings
  796. never compare equal. That is the ordinary case — a user's own spools and
  797. their print history — and it duplicated the lot on every restore.
  798. """
  799. @staticmethod
  800. async def _native_spool(db_session, **kwargs):
  801. """A spool created the way the app creates one: no explicit created_at."""
  802. spool = Spool(material="PLA", brand="Bambu Lab", subtype="Basic", color_name="Jade White", **kwargs)
  803. db_session.add(spool)
  804. await db_session.commit()
  805. await db_session.refresh(spool)
  806. return spool
  807. def _entry_for(self, spool, **overrides):
  808. """The backup entry the collector writes for ``spool``."""
  809. entry = {
  810. "id": 41,
  811. "material": spool.material,
  812. "brand": spool.brand,
  813. "subtype": spool.subtype,
  814. "color_name": spool.color_name,
  815. "created_at": str(spool.created_at),
  816. }
  817. entry.update(overrides)
  818. return entry
  819. @pytest.mark.asyncio
  820. async def test_find_spool_matches_on_the_composite_fallback(self, db_session):
  821. spool = await self._native_spool(db_session)
  822. found, matched_on = await _service()._find_spool(db_session, self._entry_for(spool))
  823. assert found is not None and found.id == spool.id
  824. assert matched_on is None # the composite, not a tag column
  825. @pytest.mark.asyncio
  826. async def test_a_tagless_spool_is_not_duplicated(self, db_session):
  827. spool = await self._native_spool(db_session)
  828. payload = {"spools": [self._entry_for(spool)]}
  829. tally = _CategoryTally()
  830. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  831. await db_session.commit()
  832. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  833. assert tally.skipped == 1
  834. @pytest.mark.asyncio
  835. async def test_overwrite_updates_the_original_instead_of_inserting(self, db_session):
  836. spool = await self._native_spool(db_session)
  837. payload = {"spools": [self._entry_for(spool, weight_used=250.0)]}
  838. await _service()._restore_spools(db_session, payload, None, True, _CategoryTally(), {})
  839. await db_session.commit()
  840. row = (await db_session.execute(select(Spool))).scalar_one()
  841. assert row.id == spool.id
  842. assert row.weight_used == 250.0
  843. @pytest.mark.asyncio
  844. async def test_a_second_spool_added_later_stays_distinct(self, db_session):
  845. """The composite is only unique because of created_at, so the Python
  846. comparison has to stay exact — not a same-day tolerance."""
  847. spool = await self._native_spool(db_session)
  848. twin = Spool(material=spool.material, brand=spool.brand, subtype=spool.subtype, color_name=spool.color_name)
  849. twin.created_at = spool.created_at + timedelta(hours=1)
  850. db_session.add(twin)
  851. await db_session.commit()
  852. found, _ = await _service()._find_spool(db_session, self._entry_for(spool))
  853. assert found.id == spool.id
  854. @pytest.mark.asyncio
  855. async def test_existing_usage_history_is_not_re_inserted(self, db_session):
  856. spool = await self._native_spool(db_session, tag_uid="AABBCCDD")
  857. usage_row = SpoolUsageHistory(spool_id=spool.id, print_name="b.3mf", weight_used=5.0)
  858. db_session.add(usage_row)
  859. await db_session.commit()
  860. await db_session.refresh(usage_row)
  861. tally = _CategoryTally()
  862. inventory = {"spools": [self._entry_for(spool, tag_uid="AABBCCDD")]}
  863. usage = {
  864. "usage_history": [
  865. {
  866. "spool_id": 41,
  867. "print_name": "b.3mf",
  868. "weight_used": 5.0,
  869. "created_at": str(usage_row.created_at),
  870. }
  871. ]
  872. }
  873. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  874. await db_session.commit()
  875. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  876. assert len(rows) == 1
  877. assert tally.skipped == 2 # the spool and its one usage row
  878. @pytest.mark.asyncio
  879. async def test_a_genuinely_new_usage_row_still_lands(self, db_session):
  880. """Dedupe by timestamp must not swallow a repeat of the same print."""
  881. spool = await self._native_spool(db_session, tag_uid="AABBCCDD")
  882. usage_row = SpoolUsageHistory(spool_id=spool.id, print_name="b.3mf", weight_used=5.0)
  883. db_session.add(usage_row)
  884. await db_session.commit()
  885. await db_session.refresh(usage_row)
  886. inventory = {"spools": [self._entry_for(spool, tag_uid="AABBCCDD")]}
  887. usage = {
  888. "usage_history": [
  889. {
  890. "spool_id": 41,
  891. "print_name": "b.3mf",
  892. "weight_used": 5.0,
  893. "created_at": str(usage_row.created_at + timedelta(days=1)),
  894. }
  895. ]
  896. }
  897. await _service()._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  898. await db_session.commit()
  899. assert len((await db_session.execute(select(SpoolUsageHistory))).scalars().all()) == 2
  900. class TestRestoreArchives:
  901. def _archive_entry(self, **overrides):
  902. entry = {
  903. "id": 77,
  904. "filename": "benchy.3mf",
  905. "file_size": 2048,
  906. "content_hash": "abc123",
  907. "print_name": "Benchy",
  908. "status": "completed",
  909. "started_at": "2026-03-01 10:00:00",
  910. "completed_at": "2026-03-01 11:00:00",
  911. "created_at": "2026-03-01 10:00:00",
  912. "quantity": 1,
  913. "is_favorite": False,
  914. }
  915. entry.update(overrides)
  916. return entry
  917. @pytest.mark.asyncio
  918. async def test_inserts_metadata_only_row_with_empty_file_path(self, db_session):
  919. """print_archives.file_path is NOT NULL but is not in the backup."""
  920. tally = _CategoryTally()
  921. id_map: dict[int, int] = {}
  922. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, id_map)
  923. await db_session.commit()
  924. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  925. assert row.file_path == ""
  926. assert row.filename == "benchy.3mf"
  927. assert row.id != 77
  928. assert id_map == {77: row.id}
  929. assert any("metadata only" in note for note in _messages(tally))
  930. @pytest.mark.asyncio
  931. async def test_matches_existing_archive_by_hash_and_start(self, db_session):
  932. db_session.add(
  933. PrintArchive(
  934. filename="benchy.3mf",
  935. file_path="/data/benchy.3mf",
  936. file_size=2048,
  937. content_hash="abc123",
  938. started_at=datetime(2026, 3, 1, 10, 0, 0),
  939. )
  940. )
  941. await db_session.commit()
  942. tally = _CategoryTally()
  943. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  944. await db_session.commit()
  945. rows = (await db_session.execute(select(PrintArchive))).scalars().all()
  946. assert len(rows) == 1
  947. assert rows[0].file_path == "/data/benchy.3mf"
  948. assert tally.skipped == 1
  949. @pytest.mark.asyncio
  950. async def test_falls_back_to_filename_and_start_without_hash(self, db_session):
  951. db_session.add(
  952. PrintArchive(
  953. filename="benchy.3mf",
  954. file_path="/data/benchy.3mf",
  955. file_size=2048,
  956. started_at=datetime(2026, 3, 1, 10, 0, 0),
  957. )
  958. )
  959. await db_session.commit()
  960. tally = _CategoryTally()
  961. entry = self._archive_entry(content_hash=None)
  962. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  963. await db_session.commit()
  964. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  965. assert tally.skipped == 1
  966. @pytest.mark.asyncio
  967. async def test_matches_archive_with_no_started_at_by_hash(self, db_session):
  968. """started_at is NULL for re-sliced archives, so it cannot be required.
  969. Gating both match branches on it meant these rows never matched: every
  970. restore re-inserted them and overwrite mode could never update them.
  971. """
  972. db_session.add(
  973. PrintArchive(
  974. filename="benchy.3mf",
  975. file_path="/data/benchy.3mf",
  976. file_size=2048,
  977. content_hash="abc123",
  978. started_at=None,
  979. )
  980. )
  981. await db_session.commit()
  982. tally = _CategoryTally()
  983. entry = self._archive_entry(started_at=None)
  984. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  985. await db_session.commit()
  986. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  987. assert tally.skipped == 1
  988. @pytest.mark.asyncio
  989. async def test_started_at_still_discriminates_when_present(self, db_session):
  990. """A NULL-tolerant match must not collapse rows that do differ."""
  991. db_session.add(
  992. PrintArchive(
  993. filename="benchy.3mf",
  994. file_path="/data/benchy.3mf",
  995. file_size=2048,
  996. content_hash="abc123",
  997. started_at=datetime(2026, 3, 1, 10, 0, 0),
  998. )
  999. )
  1000. await db_session.commit()
  1001. tally = _CategoryTally()
  1002. # Same file, no start time recorded — a different row, not that one.
  1003. entry = self._archive_entry(started_at=None)
  1004. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1005. await db_session.commit()
  1006. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 2
  1007. assert tally.restored == 1
  1008. @pytest.mark.asyncio
  1009. async def test_soft_deleted_archive_is_not_restored_as_visible(self, db_session):
  1010. """A backup keeps soft-deleted rows, so the flag has to survive.
  1011. Their row is retained on purpose (stats keep counting the filament and
  1012. energy), so without carrying deleted_at a restore turns an archive the
  1013. user deleted back into a visible one.
  1014. """
  1015. tally = _CategoryTally()
  1016. entry = self._archive_entry(deleted_at="2026-03-02 08:00:00")
  1017. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1018. await db_session.commit()
  1019. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1020. assert row.deleted_at == datetime(2026, 3, 2, 8, 0, 0)
  1021. assert tally.restored == 1
  1022. @pytest.mark.asyncio
  1023. async def test_locally_deleted_archive_stays_deleted_without_overwrite(self, db_session):
  1024. db_session.add(
  1025. PrintArchive(
  1026. filename="benchy.3mf",
  1027. file_path="",
  1028. file_size=2048,
  1029. content_hash="abc123",
  1030. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1031. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  1032. )
  1033. )
  1034. await db_session.commit()
  1035. tally = _CategoryTally()
  1036. # The backup predates the deletion, so its copy is live.
  1037. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  1038. await db_session.commit()
  1039. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1040. assert row.deleted_at == datetime(2026, 3, 5, 9, 0, 0)
  1041. assert tally.skipped == 1
  1042. @pytest.mark.asyncio
  1043. async def test_overwrite_undeletes_a_locally_deleted_archive_and_says_so(self, db_session):
  1044. """The entry has to *say* the archive was live — absent no longer means null.
  1045. A commit taken before the collector wrote ``deleted_at`` carries no
  1046. opinion about it, and overwrite now leaves the column alone in that
  1047. case; see ``TestRestoredArchiveOwnership``.
  1048. """
  1049. db_session.add(
  1050. PrintArchive(
  1051. filename="benchy.3mf",
  1052. file_path="",
  1053. file_size=2048,
  1054. content_hash="abc123",
  1055. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1056. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  1057. )
  1058. )
  1059. await db_session.commit()
  1060. tally = _CategoryTally()
  1061. await _service()._restore_archives(
  1062. db_session, {"archives": [self._archive_entry(deleted_at=None)]}, True, tally, {}
  1063. )
  1064. await db_session.commit()
  1065. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1066. assert row.deleted_at is None
  1067. assert tally.restored == 1
  1068. assert any("visible again" in note for note in _messages(tally))
  1069. @pytest.mark.asyncio
  1070. async def test_overwrite_updates_metadata_but_keeps_local_file_path(self, db_session):
  1071. db_session.add(
  1072. PrintArchive(
  1073. filename="benchy.3mf",
  1074. file_path="/data/benchy.3mf",
  1075. file_size=2048,
  1076. content_hash="abc123",
  1077. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1078. notes="old",
  1079. )
  1080. )
  1081. await db_session.commit()
  1082. tally = _CategoryTally()
  1083. entry = self._archive_entry(notes="restored note")
  1084. await _service()._restore_archives(db_session, {"archives": [entry]}, True, tally, {})
  1085. await db_session.commit()
  1086. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1087. assert row.notes == "restored note"
  1088. # The 3MF on disk must not be orphaned by a metadata restore.
  1089. assert row.file_path == "/data/benchy.3mf"
  1090. assert tally.restored == 1
  1091. @pytest.mark.asyncio
  1092. async def test_dangling_printer_and_project_links_are_cleared(self, db_session):
  1093. tally = _CategoryTally()
  1094. entry = self._archive_entry(printer_id=4242, project_id=4343)
  1095. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1096. await db_session.commit()
  1097. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1098. assert row.printer_id is None
  1099. assert row.project_id is None
  1100. assert any("no longer exist" in note for note in _messages(tally))
  1101. @pytest.mark.asyncio
  1102. async def test_valid_printer_link_is_preserved(self, db_session, printer_factory):
  1103. printer = await printer_factory()
  1104. tally = _CategoryTally()
  1105. entry = self._archive_entry(printer_id=printer.id)
  1106. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1107. await db_session.commit()
  1108. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1109. assert row.printer_id == printer.id
  1110. @pytest.mark.asyncio
  1111. async def test_non_dict_entry_counts_as_failed(self, db_session):
  1112. tally = _CategoryTally()
  1113. await _service()._restore_archives(db_session, {"archives": ["nonsense"]}, False, tally, {})
  1114. assert tally.failed == 1
  1115. class TestRestoreKprofiles:
  1116. @staticmethod
  1117. def _live(
  1118. slot_id,
  1119. filament_id="GFA00",
  1120. name="Bambu PLA",
  1121. setting_id="PFUS123",
  1122. extruder_id=0,
  1123. nozzle_id="HS00-0.4",
  1124. ):
  1125. """One profile as the printer currently reports it.
  1126. ``extruder_id`` and ``nozzle_id`` mirror ``KProfile`` (bambu_mqtt.py),
  1127. which has carried both all along; single-nozzle printers report
  1128. extruder 0. Both are non-default fields there, so a live profile always
  1129. has them — the double must too, or it licenses code that would break on
  1130. the real object.
  1131. """
  1132. return SimpleNamespace(
  1133. slot_id=slot_id,
  1134. filament_id=filament_id,
  1135. name=name,
  1136. setting_id=setting_id,
  1137. extruder_id=extruder_id,
  1138. nozzle_id=nozzle_id,
  1139. )
  1140. def _client(self, live=None, sent="7", ack=(True, "")):
  1141. """A connected printer client.
  1142. ``set_kprofiles_batch`` returns the sequence_id it published under, not
  1143. a success flag (#2718), and the verdict arrives separately from
  1144. ``await_cali_ack`` as ``(ok, detail)``.
  1145. """
  1146. client = MagicMock()
  1147. client.state.connected = True
  1148. client.set_kprofiles_batch = MagicMock(return_value=sent)
  1149. client.await_cali_ack = AsyncMock(return_value=ack)
  1150. client.get_kprofiles = AsyncMock(return_value=list(live or []))
  1151. return client
  1152. def _payload(self, serial="00M09A123456789", nozzle="0.4"):
  1153. return {
  1154. f"kprofiles/{serial}/{nozzle}.json": {
  1155. "version": "1.0",
  1156. "printer_serial": serial,
  1157. "nozzle_diameter": nozzle,
  1158. "profiles": [
  1159. {
  1160. "slot_id": 0,
  1161. "name": "Bambu PLA",
  1162. "k_value": "0.020000",
  1163. "filament_id": "GFA00",
  1164. "nozzle_id": "HS00-0.4",
  1165. "extruder_id": 0,
  1166. "setting_id": "PFUS123",
  1167. }
  1168. ],
  1169. }
  1170. }
  1171. @pytest.mark.asyncio
  1172. async def test_sends_batch_to_connected_printer(self, db_session, printer_factory):
  1173. printer = await printer_factory(serial_number="00M09A123456789")
  1174. client = self._client()
  1175. tally = _CategoryTally()
  1176. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1177. manager.get_client = MagicMock(return_value=client)
  1178. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1179. client.set_kprofiles_batch.assert_called_once()
  1180. profiles, nozzle = client.set_kprofiles_batch.call_args.args
  1181. assert nozzle == "0.4"
  1182. assert profiles[0]["name"] == "Bambu PLA"
  1183. assert profiles[0]["filament_id"] == "GFA00"
  1184. assert tally.restored == 1
  1185. assert manager.get_client.call_args.args == (printer.id,)
  1186. @pytest.mark.asyncio
  1187. async def test_always_warns_to_verify_on_the_printer(self, db_session, printer_factory):
  1188. await printer_factory(serial_number="00M09A123456789")
  1189. client = self._client()
  1190. tally = _CategoryTally()
  1191. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1192. manager.get_client = MagicMock(return_value=client)
  1193. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1194. # A refusal is now read and counted failed, so the caveat is narrowed to
  1195. # what is genuinely left uncertain: a printer that never answers.
  1196. assert any("verify the profiles on the printer" in note for note in _messages(tally))
  1197. assert any("does not answer still counts as restored" in note for note in _messages(tally))
  1198. assert not any("without acknowledgement" in note for note in _messages(tally))
  1199. assert any("always overwrite" in note for note in _messages(tally))
  1200. # --- cali_idx is resolved live, never taken from the backup -------------
  1201. #
  1202. # Regression cover for the silent no-op found testing on an X1E: the backup
  1203. # stored cali_idx 8151, a Bambuddy edit re-keyed the profile to 4606, and
  1204. # the restore aimed extrusion_cali_set at 8151. The printer dropped it and
  1205. # the tally still said "1 restored".
  1206. @pytest.mark.asyncio
  1207. async def test_uses_the_live_cali_idx_not_the_backed_up_slot(self, db_session, printer_factory):
  1208. await printer_factory(serial_number="00M09A123456789")
  1209. payload = self._payload()
  1210. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]["slot_id"] = 8151
  1211. client = self._client(live=[self._live(slot_id=4606)])
  1212. tally = _CategoryTally()
  1213. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1214. manager.get_client = MagicMock(return_value=client)
  1215. await _service()._restore_kprofiles(db_session, payload, tally)
  1216. client.get_kprofiles.assert_awaited_once_with(nozzle_diameter="0.4")
  1217. profiles, _ = client.set_kprofiles_batch.call_args.args
  1218. assert profiles[0]["cali_idx"] == 4606, "must address the slot that exists now"
  1219. assert profiles[0]["cali_idx"] != 8151, "must not reuse the backup's cali_idx"
  1220. assert tally.restored == 1
  1221. @pytest.mark.asyncio
  1222. async def test_matches_on_name_when_setting_id_was_regenerated(self, db_session, printer_factory):
  1223. # A delete-then-add edit mints a fresh setting_id, so the name carries
  1224. # the match instead.
  1225. await printer_factory(serial_number="00M09A123456789")
  1226. client = self._client(live=[self._live(slot_id=4606, setting_id="PF9999999999")])
  1227. tally = _CategoryTally()
  1228. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1229. manager.get_client = MagicMock(return_value=client)
  1230. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1231. profiles, _ = client.set_kprofiles_batch.call_args.args
  1232. assert profiles[0]["cali_idx"] == 4606
  1233. # The live setting_id wins: it is what the printer associates with the slot.
  1234. assert profiles[0]["setting_id"] == "PF9999999999"
  1235. @pytest.mark.asyncio
  1236. async def test_unmatched_profile_is_added_rather_than_aimed_at_a_dead_slot(self, db_session, printer_factory):
  1237. await printer_factory(serial_number="00M09A123456789")
  1238. client = self._client(live=[]) # printer has nothing for this nozzle
  1239. tally = _CategoryTally()
  1240. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1241. manager.get_client = MagicMock(return_value=client)
  1242. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1243. profiles, _ = client.set_kprofiles_batch.call_args.args
  1244. assert profiles[0]["cali_idx"] == -1, "-1 tells the printer to add a new profile"
  1245. assert profiles[0]["setting_id"] == "PFUS123", "falls back to the backed-up preset"
  1246. assert any("added as new profiles" in note for note in _messages(tally))
  1247. @pytest.mark.asyncio
  1248. async def test_different_filament_is_not_treated_as_a_match(self, db_session, printer_factory):
  1249. # Same slot, different filament — matching on slot alone would clobber
  1250. # an unrelated profile.
  1251. await printer_factory(serial_number="00M09A123456789")
  1252. client = self._client(live=[self._live(slot_id=4606, filament_id="GFB99", name="Bambu PLA")])
  1253. tally = _CategoryTally()
  1254. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1255. manager.get_client = MagicMock(return_value=client)
  1256. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1257. profiles, _ = client.set_kprofiles_batch.call_args.args
  1258. assert profiles[0]["cali_idx"] == -1
  1259. @pytest.mark.asyncio
  1260. async def test_unreadable_live_index_degrades_to_adding(self, db_session, printer_factory):
  1261. # A failed read must not abort the restore.
  1262. await printer_factory(serial_number="00M09A123456789")
  1263. client = self._client()
  1264. client.get_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt timeout"))
  1265. tally = _CategoryTally()
  1266. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1267. manager.get_client = MagicMock(return_value=client)
  1268. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1269. profiles, _ = client.set_kprofiles_batch.call_args.args
  1270. assert profiles[0]["cali_idx"] == -1
  1271. assert tally.restored == 1
  1272. @pytest.mark.asyncio
  1273. async def test_sole_profile_for_a_filament_matches_without_setting_id_or_name(self, db_session, printer_factory):
  1274. await printer_factory(serial_number="00M09A123456789")
  1275. payload = self._payload()
  1276. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  1277. entry["setting_id"] = None
  1278. entry["name"] = ""
  1279. client = self._client(live=[self._live(slot_id=4606, setting_id="PFOTHER", name="Renamed")])
  1280. tally = _CategoryTally()
  1281. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1282. manager.get_client = MagicMock(return_value=client)
  1283. await _service()._restore_kprofiles(db_session, payload, tally)
  1284. profiles, _ = client.set_kprofiles_batch.call_args.args
  1285. assert profiles[0]["cali_idx"] == 4606
  1286. @pytest.mark.asyncio
  1287. async def test_ambiguous_filament_without_discriminator_is_added_not_guessed(self, db_session, printer_factory):
  1288. await printer_factory(serial_number="00M09A123456789")
  1289. payload = self._payload()
  1290. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  1291. entry["setting_id"] = None
  1292. entry["name"] = ""
  1293. client = self._client(live=[self._live(slot_id=1, setting_id="A"), self._live(slot_id=2, setting_id="B")])
  1294. tally = _CategoryTally()
  1295. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1296. manager.get_client = MagicMock(return_value=client)
  1297. await _service()._restore_kprofiles(db_session, payload, tally)
  1298. profiles, _ = client.set_kprofiles_batch.call_args.args
  1299. assert profiles[0]["cali_idx"] == -1, "two candidates and nothing to tell them apart"
  1300. @pytest.mark.asyncio
  1301. async def test_two_entries_cannot_claim_the_same_live_slot(self, db_session, printer_factory):
  1302. """One live profile cannot stand in for two backed-up ones (#2656).
  1303. Both entries fell through to the single-candidate arm, both took
  1304. cali_idx 4606, both went into the batch — so the second overwrote the
  1305. first on the printer while the tally counted two restored. Reachable
  1306. whenever the user has deleted one of a pair since the backup, because
  1307. the delete-then-add re-key is what strips the setting_id match.
  1308. """
  1309. await printer_factory(serial_number="00M09A123456789")
  1310. payload = self._payload()
  1311. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1312. entries[0].update(setting_id="PFGONE1", name="PLA Basic")
  1313. entries.append({**entries[0], "setting_id": "PFGONE2", "name": "PLA Matte"})
  1314. client = self._client(live=[self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA")])
  1315. tally = _CategoryTally()
  1316. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1317. manager.get_client = MagicMock(return_value=client)
  1318. await _service()._restore_kprofiles(db_session, payload, tally)
  1319. profiles, _ = client.set_kprofiles_batch.call_args.args
  1320. assert [p["cali_idx"] for p in profiles] == [4606, -1], "the displaced entry has to be added, not aliased"
  1321. assert sum(1 for p in profiles if p["cali_idx"] == 4606) == 1
  1322. assert any("added as new profiles" in note for note in _messages(tally))
  1323. @pytest.mark.asyncio
  1324. async def test_the_displaced_entry_does_not_inherit_the_claimed_setting_id(self, db_session, printer_factory):
  1325. """An add-as-new keeps its own preset, or it lands on top of the match anyway.
  1326. cali_idx -1 is only safe if the rest of the payload doesn't point at the
  1327. profile the first entry just claimed — the generated-setting_id fallback
  1328. reads setting_id when cali_idx is -1.
  1329. """
  1330. await printer_factory(serial_number="00M09A123456789")
  1331. payload = self._payload()
  1332. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1333. entries[0].update(setting_id="PFGONE1", name="PLA Basic")
  1334. entries.append({**entries[0], "setting_id": "PFGONE2", "name": "PLA Matte"})
  1335. client = self._client(live=[self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA")])
  1336. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1337. manager.get_client = MagicMock(return_value=client)
  1338. await _service()._restore_kprofiles(db_session, payload, _CategoryTally())
  1339. profiles, _ = client.set_kprofiles_batch.call_args.args
  1340. assert profiles[0]["setting_id"] == "PFUS123", "the match prefers the live preset"
  1341. assert profiles[1]["setting_id"] == "PFGONE2", "the displaced entry keeps its own"
  1342. @pytest.mark.asyncio
  1343. async def test_two_entries_matching_two_live_profiles_keep_their_own_slots(self, db_session, printer_factory):
  1344. """Control: the guard must not displace a legitimate second match."""
  1345. await printer_factory(serial_number="00M09A123456789")
  1346. payload = self._payload()
  1347. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1348. entries.append({**entries[0], "setting_id": "PFUS456", "name": "Bambu PETG"})
  1349. client = self._client(
  1350. live=[
  1351. self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA"),
  1352. self._live(slot_id=4607, setting_id="PFUS456", name="Bambu PETG"),
  1353. ]
  1354. )
  1355. tally = _CategoryTally()
  1356. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1357. manager.get_client = MagicMock(return_value=client)
  1358. await _service()._restore_kprofiles(db_session, payload, tally)
  1359. profiles, _ = client.set_kprofiles_batch.call_args.args
  1360. assert [p["cali_idx"] for p in profiles] == [4606, 4607]
  1361. assert not any("added as new profiles" in note for note in _messages(tally))
  1362. @pytest.mark.asyncio
  1363. async def test_a_claimed_slot_does_not_make_an_ambiguous_pair_matchable(self, db_session, printer_factory):
  1364. """Two live profiles for one filament stay ambiguous after one is taken.
  1365. The single-candidate fallback is judged against every candidate, not the
  1366. unclaimed ones — otherwise claiming the first would leave exactly one
  1367. "available" and turn a guess the code deliberately refuses into a match.
  1368. """
  1369. await printer_factory(serial_number="00M09A123456789")
  1370. payload = self._payload()
  1371. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1372. entries[0].update(setting_id="PFUS123", name="Bambu PLA")
  1373. entries.append({**entries[0], "setting_id": None, "name": ""})
  1374. client = self._client(
  1375. live=[
  1376. self._live(slot_id=1, setting_id="PFUS123", name="Bambu PLA"),
  1377. self._live(slot_id=2, setting_id="PFOTHER", name="Renamed"),
  1378. ]
  1379. )
  1380. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1381. manager.get_client = MagicMock(return_value=client)
  1382. await _service()._restore_kprofiles(db_session, payload, _CategoryTally())
  1383. profiles, _ = client.set_kprofiles_batch.call_args.args
  1384. assert [p["cali_idx"] for p in profiles] == [1, -1]
  1385. # --- the match is scoped to the extruder it was calibrated on -----------
  1386. #
  1387. # get_kprofiles reads per nozzle *diameter*, so on a dual-nozzle printer
  1388. # both extruders come back in one list. Scoping candidates on filament_id
  1389. # alone let one extruder's calibration be written over the other's.
  1390. @pytest.mark.asyncio
  1391. async def test_each_extruders_profile_lands_on_its_own_extruder(self, db_session, printer_factory):
  1392. """The same preset calibrated on both extruders of an H2D.
  1393. Both live profiles share a filament_id *and* a setting_id, so the
  1394. setting_id arm matched whichever the printer happened to list first —
  1395. and with an entry per extruder the two swapped slots, each overwriting
  1396. the other's calibration while the tally counted both restored.
  1397. """
  1398. await printer_factory(serial_number="00M09A123456789")
  1399. payload = self._payload()
  1400. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1401. entries.append({**entries[0], "extruder_id": 1, "nozzle_id": "HS00-0.4-R"})
  1402. client = self._client(
  1403. live=[
  1404. # Right extruder first, which is what made the bug bite.
  1405. self._live(slot_id=1001, extruder_id=1),
  1406. self._live(slot_id=1000, extruder_id=0),
  1407. ]
  1408. )
  1409. tally = _CategoryTally()
  1410. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1411. manager.get_client = MagicMock(return_value=client)
  1412. await _service()._restore_kprofiles(db_session, payload, tally)
  1413. profiles, _ = client.set_kprofiles_batch.call_args.args
  1414. assert [(p["extruder_id"], p["cali_idx"]) for p in profiles] == [(0, 1000), (1, 1001)]
  1415. assert tally.restored == 2
  1416. assert not any("added as new profiles" in note for note in _messages(tally))
  1417. @pytest.mark.asyncio
  1418. async def test_the_other_extruders_profile_is_not_a_candidate(self, db_session, printer_factory):
  1419. """One backed-up entry, and the only live profile is the other extruder's.
  1420. Adding as new is the right answer: extruder 0's calibration is not a
  1421. stand-in for extruder 1's, however well the filament and preset line up.
  1422. """
  1423. await printer_factory(serial_number="00M09A123456789")
  1424. client = self._client(live=[self._live(slot_id=1001, extruder_id=1)])
  1425. tally = _CategoryTally()
  1426. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1427. manager.get_client = MagicMock(return_value=client)
  1428. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1429. profiles, _ = client.set_kprofiles_batch.call_args.args
  1430. assert profiles[0]["cali_idx"] == -1
  1431. assert any("added as new profiles" in note for note in _messages(tally))
  1432. @pytest.mark.asyncio
  1433. async def test_an_entry_without_an_extruder_id_still_matches(self, db_session, printer_factory):
  1434. """Control: a pre-#2656 backup carries no extruder_id.
  1435. A missing key must leave the match exactly as it was, not turn every
  1436. entry into an add.
  1437. """
  1438. await printer_factory(serial_number="00M09A123456789")
  1439. payload = self._payload()
  1440. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0].pop("extruder_id")
  1441. client = self._client(live=[self._live(slot_id=4606)])
  1442. tally = _CategoryTally()
  1443. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1444. manager.get_client = MagicMock(return_value=client)
  1445. await _service()._restore_kprofiles(db_session, payload, tally)
  1446. profiles, _ = client.set_kprofiles_batch.call_args.args
  1447. assert profiles[0]["cali_idx"] == 4606
  1448. assert tally.restored == 1
  1449. @pytest.mark.asyncio
  1450. async def test_a_live_index_that_reports_no_extruder_still_matches(self, db_session, printer_factory):
  1451. """Control: the same, for a printer whose profiles carry no extruder_id."""
  1452. await printer_factory(serial_number="00M09A123456789")
  1453. live = SimpleNamespace(slot_id=4606, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123")
  1454. client = self._client(live=[live])
  1455. tally = _CategoryTally()
  1456. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1457. manager.get_client = MagicMock(return_value=client)
  1458. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1459. profiles, _ = client.set_kprofiles_batch.call_args.args
  1460. assert profiles[0]["cali_idx"] == 4606
  1461. assert tally.restored == 1
  1462. @pytest.mark.asyncio
  1463. async def test_a_backup_without_a_nozzle_id_omits_the_key(self, db_session, printer_factory):
  1464. """``set_kprofiles_batch`` defaults it, and only an absent key lets it.
  1465. The default is ``p.get("nozzle_id", f"HS00-{diameter}")``, which a key
  1466. present-and-None defeats — the batch would publish a null nozzle_id to
  1467. the printer. Printers that omit the field (#1748) are the reason the
  1468. default exists, so it has to be reachable.
  1469. """
  1470. await printer_factory(serial_number="00M09A123456789")
  1471. payload = self._payload()
  1472. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0].pop("nozzle_id")
  1473. # No live match either, so neither source can supply one.
  1474. client = self._client(live=[])
  1475. tally = _CategoryTally()
  1476. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1477. manager.get_client = MagicMock(return_value=client)
  1478. await _service()._restore_kprofiles(db_session, payload, tally)
  1479. profiles, _ = client.set_kprofiles_batch.call_args.args
  1480. assert "nozzle_id" not in profiles[0]
  1481. @pytest.mark.asyncio
  1482. async def test_the_backups_nozzle_id_is_used_when_nothing_is_live(self, db_session, printer_factory):
  1483. await printer_factory(serial_number="00M09A123456789")
  1484. client = self._client(live=[])
  1485. tally = _CategoryTally()
  1486. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1487. manager.get_client = MagicMock(return_value=client)
  1488. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1489. profiles, _ = client.set_kprofiles_batch.call_args.args
  1490. assert profiles[0]["nozzle_id"] == "HS00-0.4"
  1491. @pytest.mark.asyncio
  1492. async def test_the_live_nozzle_id_beats_the_backups(self, db_session, printer_factory):
  1493. """The nozzle may have been swapped since the backup; we write to the
  1494. one that is fitted now, exactly as with setting_id."""
  1495. await printer_factory(serial_number="00M09A123456789")
  1496. client = self._client(live=[self._live(slot_id=4606, nozzle_id="SS00-0.4")])
  1497. tally = _CategoryTally()
  1498. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1499. manager.get_client = MagicMock(return_value=client)
  1500. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1501. profiles, _ = client.set_kprofiles_batch.call_args.args
  1502. assert profiles[0]["nozzle_id"] == "SS00-0.4"
  1503. @pytest.mark.asyncio
  1504. async def test_a_live_profile_without_a_nozzle_id_falls_back_to_the_backup(self, db_session, printer_factory):
  1505. """Same defensive read as extruder_id: not every live profile carries
  1506. every field."""
  1507. await printer_factory(serial_number="00M09A123456789")
  1508. live = SimpleNamespace(slot_id=4606, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123")
  1509. client = self._client(live=[live])
  1510. tally = _CategoryTally()
  1511. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1512. manager.get_client = MagicMock(return_value=client)
  1513. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1514. profiles, _ = client.set_kprofiles_batch.call_args.args
  1515. assert profiles[0]["nozzle_id"] == "HS00-0.4"
  1516. @pytest.mark.asyncio
  1517. async def test_unknown_serial_is_skipped_with_reason(self, db_session):
  1518. tally = _CategoryTally()
  1519. with patch("backend.app.services.github_restore.printer_manager"):
  1520. await _service()._restore_kprofiles(db_session, self._payload(serial="NOSUCH"), tally)
  1521. assert tally.restored == 0
  1522. assert tally.skipped == 1
  1523. assert any("No printer with serial NOSUCH" in note for note in _messages(tally))
  1524. @pytest.mark.asyncio
  1525. async def test_offline_printer_is_skipped_not_failed(self, db_session, printer_factory):
  1526. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  1527. client = MagicMock()
  1528. client.state.connected = False
  1529. tally = _CategoryTally()
  1530. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1531. manager.get_client = MagicMock(return_value=client)
  1532. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1533. assert tally.skipped == 1
  1534. assert tally.failed == 0
  1535. assert any("not connected" in note for note in _messages(tally))
  1536. @pytest.mark.asyncio
  1537. async def test_no_client_at_all_is_skipped(self, db_session, printer_factory):
  1538. await printer_factory(serial_number="00M09A123456789")
  1539. tally = _CategoryTally()
  1540. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1541. manager.get_client = MagicMock(return_value=None)
  1542. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1543. assert tally.skipped == 1
  1544. @pytest.mark.asyncio
  1545. async def test_publish_failure_counts_as_failed(self, db_session, printer_factory):
  1546. # None is what set_kprofiles_batch returns when it could not publish —
  1547. # a disconnected client. There is no ack to wait for in that case.
  1548. await printer_factory(serial_number="00M09A123456789")
  1549. client = self._client(sent=None)
  1550. tally = _CategoryTally()
  1551. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1552. manager.get_client = MagicMock(return_value=client)
  1553. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1554. assert tally.failed == 1
  1555. assert tally.restored == 0
  1556. assert "kprofilesSendFailed" in _codes(tally)
  1557. assert "kprofilesRefused" not in _codes(tally), "nothing was sent, so the printer refused nothing"
  1558. client.await_cali_ack.assert_not_awaited()
  1559. @pytest.mark.asyncio
  1560. async def test_publish_exception_is_contained(self, db_session, printer_factory):
  1561. await printer_factory(serial_number="00M09A123456789")
  1562. client = MagicMock()
  1563. client.state.connected = True
  1564. client.set_kprofiles_batch = MagicMock(side_effect=RuntimeError("mqtt down"))
  1565. tally = _CategoryTally()
  1566. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1567. manager.get_client = MagicMock(return_value=client)
  1568. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1569. assert tally.failed == 1
  1570. # --- the printer's verdict decides the tally, not the publish ------------
  1571. #
  1572. # #2718 changed set_kprofiles_batch from returning a bool to returning the
  1573. # sequence_id it published under. A sequence_id string is truthy, so a
  1574. # restore that branches on the return value alone reports every refused
  1575. # write as saved — the defect that fix closed in every other caller.
  1576. @pytest.mark.asyncio
  1577. async def test_awaits_the_ack_for_the_sequence_id_it_was_given(self, db_session, printer_factory):
  1578. await printer_factory(serial_number="00M09A123456789")
  1579. client = self._client(sent="4211")
  1580. tally = _CategoryTally()
  1581. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1582. manager.get_client = MagicMock(return_value=client)
  1583. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1584. client.await_cali_ack.assert_awaited_once_with("4211")
  1585. assert tally.restored == 1
  1586. @pytest.mark.asyncio
  1587. async def test_a_refused_batch_counts_failed_not_restored(self, db_session, printer_factory):
  1588. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  1589. client = self._client(ack=(False, "invalid tray_id"))
  1590. tally = _CategoryTally()
  1591. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1592. manager.get_client = MagicMock(return_value=client)
  1593. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1594. assert tally.restored == 0
  1595. assert tally.failed == 1
  1596. assert "kprofilesRefused" in _codes(tally)
  1597. assert "kprofilesSendFailed" not in _codes(tally), "it was sent — the printer answered no"
  1598. note = next(n for n in tally.notes if n["code"] == "kprofilesRefused")
  1599. assert note["params"]["reason"] == "invalid tray_id", "the printer's own reason has to survive"
  1600. assert "Shelf Printer" in note["message"] and "invalid tray_id" in note["message"]
  1601. @pytest.mark.asyncio
  1602. async def test_a_silent_printer_still_counts_restored(self, db_session, printer_factory):
  1603. # maziggy's rule, and await_cali_ack's own contract: no answer is not
  1604. # evidence of refusal. Firmware that predates the ack never answers.
  1605. await printer_factory(serial_number="00M09A123456789")
  1606. client = self._client(ack=(True, "no acknowledgement from printer"))
  1607. tally = _CategoryTally()
  1608. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1609. manager.get_client = MagicMock(return_value=client)
  1610. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1611. assert tally.restored == 1
  1612. assert tally.failed == 0
  1613. assert "kprofilesRefused" not in _codes(tally)
  1614. @pytest.mark.asyncio
  1615. async def test_an_unreadable_ack_does_not_fail_the_batch(self, db_session, printer_factory):
  1616. # Same situation one layer up: the write most likely landed, so this
  1617. # degrades the way a timeout does rather than inventing a failure.
  1618. await printer_factory(serial_number="00M09A123456789")
  1619. client = self._client()
  1620. client.await_cali_ack = AsyncMock(side_effect=RuntimeError("mqtt down"))
  1621. tally = _CategoryTally()
  1622. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1623. manager.get_client = MagicMock(return_value=client)
  1624. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1625. assert tally.restored == 1
  1626. assert tally.failed == 0
  1627. @pytest.mark.asyncio
  1628. async def test_one_refused_nozzle_does_not_condemn_the_other(self, db_session, printer_factory):
  1629. await printer_factory(serial_number="00M09A123456789")
  1630. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1631. client = self._client()
  1632. client.await_cali_ack = AsyncMock(side_effect=[(False, "busy"), (True, "")])
  1633. tally = _CategoryTally()
  1634. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1635. manager.get_client = MagicMock(return_value=client)
  1636. await _service()._restore_kprofiles(db_session, payload, tally)
  1637. assert tally.restored == 1
  1638. assert tally.failed == 1
  1639. @pytest.mark.asyncio
  1640. async def test_each_nozzle_is_sent_separately(self, db_session, printer_factory):
  1641. await printer_factory(serial_number="00M09A123456789")
  1642. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1643. client = self._client()
  1644. tally = _CategoryTally()
  1645. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1646. manager.get_client = MagicMock(return_value=client)
  1647. await _service()._restore_kprofiles(db_session, payload, tally)
  1648. assert client.set_kprofiles_batch.call_count == 2
  1649. assert {c.args[1] for c in client.set_kprofiles_batch.call_args_list} == {"0.4", "0.8"}
  1650. assert tally.restored == 2
  1651. @pytest.mark.asyncio
  1652. async def test_empty_payload_is_noted(self, db_session):
  1653. tally = _CategoryTally()
  1654. await _service()._restore_kprofiles(db_session, {}, tally)
  1655. assert _codes(tally) == ["noData"]
  1656. class TestSoftDeletedArchiveRoundTrip:
  1657. """The two halves of the soft-delete fix only work together.
  1658. The collector keeps soft-deleted rows on purpose (their stats still count),
  1659. so if it doesn't write ``deleted_at`` there is nothing for the restore to
  1660. carry across and a deleted archive comes back visible. Covered end to end
  1661. because each half looks harmless on its own.
  1662. """
  1663. @pytest.mark.asyncio
  1664. async def test_deleted_at_survives_collect_then_restore(self, db_session):
  1665. from backend.app.services.github_backup import github_backup_service
  1666. deleted_at = datetime(2026, 3, 5, 9, 0, 0)
  1667. db_session.add(
  1668. PrintArchive(
  1669. filename="trashed.3mf",
  1670. file_path="",
  1671. file_size=1024,
  1672. content_hash="hash-trashed",
  1673. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1674. deleted_at=deleted_at,
  1675. )
  1676. )
  1677. await db_session.commit()
  1678. files: dict = {}
  1679. await github_backup_service._collect_archives(db_session, files)
  1680. payload = files[ARCHIVES_PATH]
  1681. assert payload["archives"][0]["deleted_at"] == str(deleted_at)
  1682. # Restore that payload into an instance where the row is gone entirely.
  1683. await db_session.execute(PrintArchive.__table__.delete())
  1684. await db_session.commit()
  1685. tally = _CategoryTally()
  1686. await _service()._restore_archives(db_session, payload, False, tally, {})
  1687. await db_session.commit()
  1688. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1689. assert row.deleted_at == deleted_at, "a deleted archive must not come back visible"
  1690. class TestRestoredArchiveOwnership:
  1691. """A restored archive without an owner is invisible to the person who owns it.
  1692. ``created_by_id`` is not attribution, it is the column the access check runs
  1693. on: ``_ensure_archive_visible`` fails closed on NULL (404 for any caller
  1694. without ``archives:read_all``) and the list paths filter
  1695. ``created_by_id == user.id``. So on a multi-user instance the tally reported
  1696. archives restored while their owner could neither list nor open them.
  1697. """
  1698. def _entry(self, **overrides):
  1699. entry = {
  1700. "id": 77,
  1701. "filename": "benchy.3mf",
  1702. "file_size": 2048,
  1703. "content_hash": "abc123",
  1704. "started_at": "2026-03-01 10:00:00",
  1705. "created_at": "2026-03-01 10:00:00",
  1706. }
  1707. entry.update(overrides)
  1708. return entry
  1709. async def _user(self, db, username="alice"):
  1710. user = User(username=username, role="operator")
  1711. db.add(user)
  1712. await db.flush()
  1713. return user
  1714. @pytest.mark.asyncio
  1715. async def test_owner_is_carried_across(self, db_session):
  1716. user = await self._user(db_session)
  1717. tally = _CategoryTally()
  1718. await _service()._restore_archives(
  1719. db_session, {"archives": [self._entry(created_by_id=user.id)]}, False, tally, {}
  1720. )
  1721. await db_session.commit()
  1722. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1723. assert row.created_by_id == user.id
  1724. assert not any("owner cleared" in note for note in _messages(tally))
  1725. @pytest.mark.asyncio
  1726. async def test_an_unknown_owner_is_cleared_with_a_note_not_failed(self, db_session):
  1727. """The archive is still worth having; an admin can reassign it."""
  1728. tally = _CategoryTally()
  1729. await _service()._restore_archives(
  1730. db_session, {"archives": [self._entry(created_by_id=4242)]}, False, tally, {}
  1731. )
  1732. await db_session.commit()
  1733. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1734. assert row.created_by_id is None
  1735. assert tally.restored == 1 and tally.failed == 0
  1736. assert any("owner cleared" in note and "archives:read_all" in note for note in _messages(tally))
  1737. @pytest.mark.asyncio
  1738. async def test_the_owner_note_is_emitted_once_for_many_rows(self, db_session):
  1739. tally = _CategoryTally()
  1740. archives = [
  1741. self._entry(id=1, content_hash="h1", filename="a.3mf", created_by_id=4242),
  1742. self._entry(id=2, content_hash="h2", filename="b.3mf", created_by_id=4243),
  1743. ]
  1744. await _service()._restore_archives(db_session, {"archives": archives}, False, tally, {})
  1745. await db_session.commit()
  1746. assert sum(1 for note in _messages(tally) if "owner cleared" in note) == 1
  1747. @pytest.mark.asyncio
  1748. async def test_a_backup_without_the_key_still_restores_and_says_so(self, db_session):
  1749. """Backups taken before the collector recorded it just can't know the owner.
  1750. The archive is worth restoring anyway, but it lands ownerless — which is
  1751. a 404 for everyone without ``archives:read_all``. Reporting N restored
  1752. while the user who asked for them sees none is the failure mode the note
  1753. exists to prevent.
  1754. """
  1755. tally = _CategoryTally()
  1756. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, False, tally, {})
  1757. await db_session.commit()
  1758. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1759. assert row.created_by_id is None
  1760. assert tally.restored == 1
  1761. assert not any("owner cleared" in note for note in _messages(tally))
  1762. assert any("without an owner" in note and "archives:read_all" in note for note in _messages(tally))
  1763. @pytest.mark.asyncio
  1764. async def test_an_explicitly_ownerless_archive_is_reported_too(self, db_session):
  1765. """Same consequence, so the same note: the source row had no owner either."""
  1766. tally = _CategoryTally()
  1767. await _service()._restore_archives(
  1768. db_session, {"archives": [self._entry(created_by_id=None)]}, False, tally, {}
  1769. )
  1770. await db_session.commit()
  1771. assert any("without an owner" in note for note in _messages(tally))
  1772. @pytest.mark.asyncio
  1773. async def test_a_stale_owner_is_not_reported_twice(self, db_session):
  1774. """One row, one cause, one note — the cleared-owner branch already spoke."""
  1775. tally = _CategoryTally()
  1776. await _service()._restore_archives(
  1777. db_session, {"archives": [self._entry(created_by_id=4242)]}, False, tally, {}
  1778. )
  1779. await db_session.commit()
  1780. assert any("owner cleared" in note for note in _messages(tally))
  1781. assert not any("without an owner" in note for note in _messages(tally))
  1782. @pytest.mark.asyncio
  1783. async def test_a_known_owner_is_not_reported(self, db_session):
  1784. user = await self._user(db_session)
  1785. tally = _CategoryTally()
  1786. await _service()._restore_archives(
  1787. db_session, {"archives": [self._entry(created_by_id=user.id)]}, False, tally, {}
  1788. )
  1789. await db_session.commit()
  1790. assert not any("without an owner" in note for note in _messages(tally))
  1791. @pytest.mark.asyncio
  1792. async def test_the_unknown_owner_note_is_not_emitted_on_overwrite(self, db_session):
  1793. """Overwrite keeps the local owner, so there is nothing to warn about."""
  1794. bob = await self._user(db_session, "bob")
  1795. db_session.add(
  1796. PrintArchive(
  1797. filename="benchy.3mf",
  1798. file_path="/data/benchy.3mf",
  1799. file_size=2048,
  1800. content_hash="abc123",
  1801. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1802. created_by_id=bob.id,
  1803. )
  1804. )
  1805. await db_session.commit()
  1806. tally = _CategoryTally()
  1807. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1808. await db_session.commit()
  1809. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1810. assert row.created_by_id == bob.id
  1811. assert not any("without an owner" in note for note in _messages(tally))
  1812. @pytest.mark.asyncio
  1813. async def test_overwrite_makes_the_local_owner_match_the_backup(self, db_session):
  1814. alice = await self._user(db_session, "alice")
  1815. bob = await self._user(db_session, "bob")
  1816. db_session.add(
  1817. PrintArchive(
  1818. filename="benchy.3mf",
  1819. file_path="/data/benchy.3mf",
  1820. file_size=2048,
  1821. content_hash="abc123",
  1822. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1823. created_by_id=bob.id,
  1824. )
  1825. )
  1826. await db_session.commit()
  1827. await _service()._restore_archives(
  1828. db_session, {"archives": [self._entry(created_by_id=alice.id)]}, True, _CategoryTally(), {}
  1829. )
  1830. await db_session.commit()
  1831. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1832. assert row.created_by_id == alice.id
  1833. @pytest.mark.asyncio
  1834. async def test_overwrite_leaves_the_owner_alone_when_the_backup_predates_the_key(self, db_session):
  1835. """A pre-#2656 commit must not blank the owner of a row that was fine.
  1836. The entry carries no ``created_by_id`` at all, so there is nothing to
  1837. write. Treating that as an explicit null inflicted the exact bug the
  1838. column was added to fix — a 404 for the owner — on rows the restore had
  1839. no business touching, silently, while still counting them restored.
  1840. """
  1841. bob = await self._user(db_session, "bob")
  1842. db_session.add(
  1843. PrintArchive(
  1844. filename="benchy.3mf",
  1845. file_path="/data/benchy.3mf",
  1846. file_size=2048,
  1847. content_hash="abc123",
  1848. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1849. created_by_id=bob.id,
  1850. )
  1851. )
  1852. await db_session.commit()
  1853. tally = _CategoryTally()
  1854. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1855. await db_session.commit()
  1856. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1857. assert row.created_by_id == bob.id, "an old backup does not know the owner, so it must not clear one"
  1858. assert tally.restored == 1
  1859. @pytest.mark.asyncio
  1860. async def test_overwrite_leaves_deleted_at_alone_when_the_backup_predates_the_key(self, db_session):
  1861. """The mirror case: an old commit must not un-delete, and must not claim to.
  1862. ``archivesUndeleted`` reads the same absent value, so the un-delete was
  1863. not merely wrong but unannounced.
  1864. """
  1865. db_session.add(
  1866. PrintArchive(
  1867. filename="benchy.3mf",
  1868. file_path="/data/benchy.3mf",
  1869. file_size=2048,
  1870. content_hash="abc123",
  1871. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1872. deleted_at=datetime(2026, 3, 4, 8, 0, 0),
  1873. )
  1874. )
  1875. await db_session.commit()
  1876. tally = _CategoryTally()
  1877. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1878. await db_session.commit()
  1879. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1880. assert row.deleted_at == datetime(2026, 3, 4, 8, 0, 0), "an old backup must not resurrect a deleted archive"
  1881. assert not any("visible again" in note for note in _messages(tally))
  1882. @pytest.mark.asyncio
  1883. async def test_overwrite_still_clears_an_owner_the_backup_explicitly_nulls(self, db_session):
  1884. """Control: absent is ignored, but an explicit null is still honoured.
  1885. A current-format backup of an unowned archive has to be able to say so,
  1886. or overwrite stops meaning "make the local row match the backup".
  1887. """
  1888. bob = await self._user(db_session, "bob")
  1889. db_session.add(
  1890. PrintArchive(
  1891. filename="benchy.3mf",
  1892. file_path="/data/benchy.3mf",
  1893. file_size=2048,
  1894. content_hash="abc123",
  1895. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1896. created_by_id=bob.id,
  1897. )
  1898. )
  1899. await db_session.commit()
  1900. await _service()._restore_archives(
  1901. db_session, {"archives": [self._entry(created_by_id=None)]}, True, _CategoryTally(), {}
  1902. )
  1903. await db_session.commit()
  1904. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1905. assert row.created_by_id is None
  1906. @pytest.mark.asyncio
  1907. async def test_overwrite_still_undeletes_when_the_backup_explicitly_nulls(self, db_session):
  1908. """Control for the deleted_at half, with the note that goes with it."""
  1909. db_session.add(
  1910. PrintArchive(
  1911. filename="benchy.3mf",
  1912. file_path="/data/benchy.3mf",
  1913. file_size=2048,
  1914. content_hash="abc123",
  1915. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1916. deleted_at=datetime(2026, 3, 4, 8, 0, 0),
  1917. )
  1918. )
  1919. await db_session.commit()
  1920. tally = _CategoryTally()
  1921. await _service()._restore_archives(db_session, {"archives": [self._entry(deleted_at=None)]}, True, tally, {})
  1922. await db_session.commit()
  1923. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1924. assert row.deleted_at is None
  1925. assert any("visible again" in note for note in _messages(tally))
  1926. @pytest.mark.asyncio
  1927. async def test_owner_survives_collect_then_restore(self, db_session):
  1928. """Both halves, because each looks harmless alone.
  1929. The collector never wrote the key, so there was nothing for the restore
  1930. to carry across even once it wanted to.
  1931. """
  1932. from backend.app.services.github_backup import github_backup_service
  1933. user = await self._user(db_session)
  1934. db_session.add(
  1935. PrintArchive(
  1936. filename="owned.3mf",
  1937. file_path="",
  1938. file_size=1024,
  1939. content_hash="hash-owned",
  1940. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1941. created_by_id=user.id,
  1942. )
  1943. )
  1944. await db_session.commit()
  1945. files: dict = {}
  1946. await github_backup_service._collect_archives(db_session, files)
  1947. payload = files[ARCHIVES_PATH]
  1948. assert payload["archives"][0]["created_by_id"] == user.id
  1949. await db_session.execute(PrintArchive.__table__.delete())
  1950. await db_session.commit()
  1951. await _service()._restore_archives(db_session, payload, False, _CategoryTally(), {})
  1952. await db_session.commit()
  1953. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1954. assert row.created_by_id == user.id, "a restored archive its owner cannot see is not restored"
  1955. class TestArchiveOwnerNaturalKey:
  1956. """``created_by_username`` decides the owner; the id is only the fallback.
  1957. Restoring onto a rebuilt instance is this feature's main use case, and the
  1958. users table renumbers there. A raw ``created_by_id`` cannot tell a correct
  1959. match from a live id that now belongs to somebody else, so the id path hands
  1960. one person's print history to another under ``ARCHIVES_READ_OWN`` — silently,
  1961. because ``archivesOwnerCleared`` only fires for an id that is *absent*.
  1962. ``username`` is unique on ``users``, so resolving on it turns that silent
  1963. misattribution into an ownerless row with a note.
  1964. """
  1965. def _entry(self, **overrides):
  1966. entry = {
  1967. "id": 77,
  1968. "filename": "benchy.3mf",
  1969. "file_size": 2048,
  1970. "content_hash": "abc123",
  1971. "started_at": "2026-03-01 10:00:00",
  1972. "created_at": "2026-03-01 10:00:00",
  1973. }
  1974. entry.update(overrides)
  1975. return entry
  1976. async def _user(self, db, username):
  1977. user = User(username=username, role="operator")
  1978. db.add(user)
  1979. await db.flush()
  1980. return user
  1981. @pytest.mark.asyncio
  1982. async def test_the_name_resolves_across_a_renumbered_users_table(self, db_session):
  1983. """The whole point: same person, different id, restore still finds them."""
  1984. alice = await self._user(db_session, "alice")
  1985. tally = _CategoryTally()
  1986. await _service()._restore_archives(
  1987. db_session,
  1988. {"archives": [self._entry(created_by_id=alice.id + 500, created_by_username="alice")]},
  1989. False,
  1990. tally,
  1991. {},
  1992. )
  1993. await db_session.commit()
  1994. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1995. assert row.created_by_id == alice.id
  1996. assert not any("owner cleared" in note for note in _messages(tally))
  1997. @pytest.mark.asyncio
  1998. async def test_the_name_beats_a_live_id_belonging_to_someone_else(self, db_session):
  1999. """The misattribution case, and the one the id path cannot even detect.
  2000. Both ids exist locally, so the id path would write bob's — a valid row,
  2001. no note, alice's print history readable by bob.
  2002. """
  2003. alice = await self._user(db_session, "alice")
  2004. bob = await self._user(db_session, "bob")
  2005. await _service()._restore_archives(
  2006. db_session,
  2007. {"archives": [self._entry(created_by_id=bob.id, created_by_username="alice")]},
  2008. False,
  2009. _CategoryTally(),
  2010. {},
  2011. )
  2012. await db_session.commit()
  2013. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  2014. assert row.created_by_id == alice.id, "the name is the natural key; the id is from another instance"
  2015. @pytest.mark.asyncio
  2016. async def test_a_renamed_owner_lands_ownerless_with_a_note(self, db_session):
  2017. """No local match, so nothing to resolve — and the id is not a fallback here.
  2018. Falling back to it is exactly the guess the name exists to prevent, so
  2019. the row is cleared and said out loud instead.
  2020. """
  2021. bob = await self._user(db_session, "bob")
  2022. tally = _CategoryTally()
  2023. await _service()._restore_archives(
  2024. db_session,
  2025. {"archives": [self._entry(created_by_id=bob.id, created_by_username="alice")]},
  2026. False,
  2027. tally,
  2028. {},
  2029. )
  2030. await db_session.commit()
  2031. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  2032. assert row.created_by_id is None
  2033. assert tally.restored == 1 and tally.failed == 0
  2034. assert any("does not have" in note and "archives:read_all" in note for note in _messages(tally))
  2035. @pytest.mark.asyncio
  2036. async def test_the_unmatched_note_is_emitted_once_for_many_rows(self, db_session):
  2037. tally = _CategoryTally()
  2038. archives = [
  2039. self._entry(id=1, content_hash="h1", filename="a.3mf", created_by_username="alice"),
  2040. self._entry(id=2, content_hash="h2", filename="b.3mf", created_by_username="carol"),
  2041. ]
  2042. await _service()._restore_archives(db_session, {"archives": archives}, False, tally, {})
  2043. await db_session.commit()
  2044. assert sum(1 for note in _messages(tally) if "does not have" in note) == 1
  2045. @pytest.mark.asyncio
  2046. async def test_an_unmatched_name_does_not_also_claim_no_owner_was_recorded(self, db_session):
  2047. """One row, one cause, one note — as with the stale-id branch."""
  2048. tally = _CategoryTally()
  2049. await _service()._restore_archives(
  2050. db_session, {"archives": [self._entry(created_by_username="alice")]}, False, tally, {}
  2051. )
  2052. await db_session.commit()
  2053. assert any("does not have" in note for note in _messages(tally))
  2054. assert not any("without an owner" in note for note in _messages(tally))
  2055. @pytest.mark.asyncio
  2056. async def test_a_pre_username_backup_still_resolves_on_the_id(self, db_session):
  2057. """The fallback has to keep working — every backup taken before this change."""
  2058. alice = await self._user(db_session, "alice")
  2059. await _service()._restore_archives(
  2060. db_session, {"archives": [self._entry(created_by_id=alice.id)]}, False, _CategoryTally(), {}
  2061. )
  2062. await db_session.commit()
  2063. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  2064. assert row.created_by_id == alice.id
  2065. @pytest.mark.asyncio
  2066. async def test_an_explicitly_ownerless_archive_reads_as_no_owner_not_as_unmatched(self, db_session):
  2067. """A current-format backup of an unowned archive writes both keys null."""
  2068. tally = _CategoryTally()
  2069. await _service()._restore_archives(
  2070. db_session,
  2071. {"archives": [self._entry(created_by_id=None, created_by_username=None)]},
  2072. False,
  2073. tally,
  2074. {},
  2075. )
  2076. await db_session.commit()
  2077. assert any("without an owner" in note for note in _messages(tally))
  2078. assert not any("does not have" in note for note in _messages(tally))
  2079. @pytest.mark.asyncio
  2080. async def test_overwrite_leaves_the_owner_alone_when_neither_key_is_present(self, db_session):
  2081. """The absent-is-not-null rule still holds now that there are two keys."""
  2082. bob = await self._user(db_session, "bob")
  2083. db_session.add(
  2084. PrintArchive(
  2085. filename="benchy.3mf",
  2086. file_path="/data/benchy.3mf",
  2087. file_size=2048,
  2088. content_hash="abc123",
  2089. started_at=datetime(2026, 3, 1, 10, 0, 0),
  2090. created_by_id=bob.id,
  2091. )
  2092. )
  2093. await db_session.commit()
  2094. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, _CategoryTally(), {})
  2095. await db_session.commit()
  2096. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  2097. assert row.created_by_id == bob.id
  2098. @pytest.mark.asyncio
  2099. async def test_the_name_survives_collect_then_restore(self, db_session):
  2100. """Both halves, because the collector writing nothing looks harmless alone."""
  2101. from backend.app.services.github_backup import github_backup_service
  2102. alice = await self._user(db_session, "alice")
  2103. db_session.add(
  2104. PrintArchive(
  2105. filename="owned.3mf",
  2106. file_path="",
  2107. file_size=1024,
  2108. content_hash="hash-owned",
  2109. started_at=datetime(2026, 3, 1, 10, 0, 0),
  2110. created_by_id=alice.id,
  2111. )
  2112. )
  2113. await db_session.commit()
  2114. files: dict = {}
  2115. await github_backup_service._collect_archives(db_session, files)
  2116. payload = files[ARCHIVES_PATH]
  2117. assert payload["archives"][0]["created_by_username"] == "alice"
  2118. # Rebuilt instance: same person, and nothing else holds their old id.
  2119. await db_session.execute(PrintArchive.__table__.delete())
  2120. await db_session.execute(User.__table__.delete())
  2121. await db_session.commit()
  2122. rebuilt = await self._user(db_session, "alice")
  2123. await db_session.commit()
  2124. await _service()._restore_archives(db_session, payload, False, _CategoryTally(), {})
  2125. await db_session.commit()
  2126. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  2127. assert row.created_by_id == rebuilt.id
  2128. @pytest.mark.asyncio
  2129. async def test_the_collector_names_no_owner_for_an_unowned_archive(self, db_session):
  2130. """Null rather than absent, so a restore can tell "none" from "not recorded"."""
  2131. from backend.app.services.github_backup import github_backup_service
  2132. db_session.add(
  2133. PrintArchive(
  2134. filename="unowned.3mf",
  2135. file_path="",
  2136. file_size=1024,
  2137. content_hash="hash-unowned",
  2138. started_at=datetime(2026, 3, 1, 10, 0, 0),
  2139. )
  2140. )
  2141. await db_session.commit()
  2142. files: dict = {}
  2143. await github_backup_service._collect_archives(db_session, files)
  2144. entry = files[ARCHIVES_PATH]["archives"][0]
  2145. assert entry["created_by_username"] is None
  2146. assert "created_by_username" in entry
  2147. class TestCategoryPathMapping:
  2148. def setup_method(self):
  2149. self.service = _service()
  2150. self.available = [
  2151. "backup_metadata.json",
  2152. SETTINGS_PATH,
  2153. SPOOLS_PATH,
  2154. SPOOL_USAGE_PATH,
  2155. ARCHIVES_PATH,
  2156. "kprofiles/SERIAL1/0.4.json",
  2157. "kprofiles/SERIAL1/0.8.json",
  2158. "cloud_profiles/filament.json",
  2159. ]
  2160. def test_spools_includes_usage_history(self):
  2161. paths = self.service._category_paths(RestoreCategory.SPOOLS, self.available)
  2162. assert paths == [SPOOLS_PATH, SPOOL_USAGE_PATH]
  2163. def test_kprofiles_globs_all_serials_and_nozzles(self):
  2164. paths = self.service._category_paths(RestoreCategory.KPROFILES, self.available)
  2165. assert paths == ["kprofiles/SERIAL1/0.4.json", "kprofiles/SERIAL1/0.8.json"]
  2166. def test_absent_paths_are_omitted(self):
  2167. paths = self.service._category_paths(RestoreCategory.SETTINGS, ["backup_metadata.json"])
  2168. assert paths == []
  2169. def test_cloud_profiles_are_not_a_restore_category(self):
  2170. assert "cloud_profiles" not in {c.value for c in RestoreCategory}
  2171. class TestMutex:
  2172. @pytest.mark.asyncio
  2173. async def test_restore_refuses_while_a_backup_is_running(self):
  2174. service = _service()
  2175. with patch("backend.app.services.github_backup.github_backup_service") as backup:
  2176. backup.is_running = True
  2177. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  2178. assert result["success"] is False
  2179. assert "backup is currently running" in result["message"]
  2180. @pytest.mark.asyncio
  2181. async def test_restore_refuses_while_another_restore_is_running(self):
  2182. service = _service()
  2183. service._running_restore = True
  2184. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  2185. assert result["success"] is False
  2186. assert "restore is already running" in result["message"]
  2187. @pytest.mark.asyncio
  2188. async def test_backup_refuses_while_a_restore_is_running(self):
  2189. from backend.app.services.github_backup import GitHubBackupService
  2190. backup_service = GitHubBackupService()
  2191. with patch("backend.app.services.github_restore.github_restore_service") as restore:
  2192. restore.is_running = True
  2193. result = await backup_service.run_backup(1, trigger="manual")
  2194. assert result["success"] is False
  2195. assert "restore is currently running" in result["message"]
  2196. class TestMqttRelayReconfigure:
  2197. """Restoring mqtt_* rows has to reach the live relay, not just the table."""
  2198. @pytest.mark.asyncio
  2199. async def test_reconfigures_from_the_committed_rows(self, db_session):
  2200. db_session.add(Settings(key="mqtt_enabled", value="true"))
  2201. db_session.add(Settings(key="mqtt_broker", value="restored.local"))
  2202. db_session.add(Settings(key="mqtt_port", value="8883"))
  2203. db_session.add(Settings(key="mqtt_use_tls", value="true"))
  2204. # Never restorable (credential blocklist), so it comes from the row that
  2205. # was already there.
  2206. db_session.add(Settings(key="mqtt_password", value="kept"))
  2207. await db_session.commit()
  2208. tally = _CategoryTally()
  2209. relay = MagicMock()
  2210. relay.configure = AsyncMock(return_value=True)
  2211. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2212. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_broker"}, tally)
  2213. relay.configure.assert_awaited_once()
  2214. sent = relay.configure.await_args.args[0]
  2215. assert sent["mqtt_enabled"] is True
  2216. assert sent["mqtt_broker"] == "restored.local"
  2217. assert sent["mqtt_port"] == 8883
  2218. assert sent["mqtt_use_tls"] is True
  2219. assert sent["mqtt_password"] == "kept"
  2220. assert sent["mqtt_topic_prefix"] == "bambuddy"
  2221. assert tally.notes == []
  2222. @pytest.mark.asyncio
  2223. async def test_no_reconnect_when_no_mqtt_key_was_written(self, db_session):
  2224. """configure() tears the connection down, so don't call it for a theme change."""
  2225. tally = _CategoryTally()
  2226. relay = MagicMock()
  2227. relay.configure = AsyncMock()
  2228. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2229. await _service()._reconfigure_mqtt_relay(db_session, {"currency", "theme"}, tally)
  2230. relay.configure.assert_not_awaited()
  2231. @pytest.mark.asyncio
  2232. async def test_broker_failure_is_noted_not_fatal(self, db_session):
  2233. tally = _CategoryTally()
  2234. relay = MagicMock()
  2235. relay.configure = AsyncMock(side_effect=OSError("no route to broker"))
  2236. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2237. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_enabled"}, tally)
  2238. assert any("restart Bambuddy" in note for note in _messages(tally))
  2239. @pytest.mark.asyncio
  2240. async def test_restore_settings_reports_the_keys_it_wrote(self, db_session):
  2241. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  2242. await db_session.commit()
  2243. written: set[str] = set()
  2244. payload = {
  2245. "settings": {
  2246. "mqtt_broker": "new.local",
  2247. "currency": "EUR",
  2248. "mqtt_password": "leaked",
  2249. "auth_enabled": "false",
  2250. }
  2251. }
  2252. await _service()._restore_settings(
  2253. db_session, payload, overwrite=True, tally=_CategoryTally(), keys_written=written
  2254. )
  2255. # Skipped keys are not "written", or a blocked mqtt_password would
  2256. # trigger a pointless reconnect.
  2257. assert written == {"mqtt_broker", "currency"}
  2258. @pytest.mark.asyncio
  2259. async def test_keys_skipped_for_overwrite_off_are_not_reported(self, db_session):
  2260. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  2261. await db_session.commit()
  2262. written: set[str] = set()
  2263. await _service()._restore_settings(
  2264. db_session,
  2265. {"settings": {"mqtt_broker": "new.local"}},
  2266. overwrite=False,
  2267. tally=_CategoryTally(),
  2268. keys_written=written,
  2269. )
  2270. assert written == set()
  2271. @pytest.mark.asyncio
  2272. async def test_a_refused_mqtt_enabled_is_not_reported_as_written(self, db_session):
  2273. """So the relay reconfigures from the *local* mqtt_enabled, not the backup's.
  2274. The companion rule refuses ``mqtt_enabled`` when the backup's password
  2275. cannot come across and there is none stored locally. It must not then
  2276. appear in ``keys_written``, or _reconfigure_mqtt_relay would be asked to
  2277. bring up a broker connection the restore deliberately declined to enable.
  2278. """
  2279. written: set[str] = set()
  2280. await _service()._restore_settings(
  2281. db_session,
  2282. {"settings": {"mqtt_enabled": "true", "mqtt_password": "refused", "mqtt_broker": "new.local"}},
  2283. overwrite=True,
  2284. tally=_CategoryTally(),
  2285. keys_written=written,
  2286. )
  2287. assert written == {"mqtt_broker"}
  2288. class TestApplyOrdering:
  2289. """_apply must not hold SQLite's write transaction across the MQTT phase."""
  2290. def _recording_service(self, calls: list[str]):
  2291. service = _service()
  2292. # Sync side effects on purpose: an AsyncMock returns a coroutine its
  2293. # side_effect hands back rather than awaiting it, so an async recorder
  2294. # would never run.
  2295. service._restore_archives = AsyncMock(side_effect=lambda *a, **k: calls.append("archives"))
  2296. service._restore_spools = AsyncMock(side_effect=lambda *a, **k: calls.append("spools"))
  2297. service._restore_settings = AsyncMock(side_effect=lambda *a, **k: calls.append("settings"))
  2298. service._restore_kprofiles = AsyncMock(side_effect=lambda *a, **k: calls.append("kprofiles"))
  2299. return service
  2300. @pytest.mark.asyncio
  2301. async def test_commits_database_categories_before_talking_to_printers(self):
  2302. """get_kprofiles is 3 x 5 s per printer/nozzle; busy_timeout is 15 s."""
  2303. calls: list[str] = []
  2304. service = self._recording_service(calls)
  2305. db = MagicMock()
  2306. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  2307. await service._apply(
  2308. db,
  2309. {},
  2310. [RestoreCategory.ARCHIVES, RestoreCategory.SPOOLS, RestoreCategory.KPROFILES],
  2311. False,
  2312. )
  2313. assert calls == ["archives", "spools", "commit", "kprofiles"]
  2314. @pytest.mark.asyncio
  2315. async def test_does_not_split_the_transaction_without_kprofiles(self):
  2316. """A database-only restore stays one transaction, committed by run_restore."""
  2317. calls: list[str] = []
  2318. service = self._recording_service(calls)
  2319. db = MagicMock()
  2320. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  2321. await service._apply(db, {}, [RestoreCategory.ARCHIVES, RestoreCategory.SETTINGS], False)
  2322. assert calls == ["archives", "settings"]
  2323. assert db.commit.await_count == 0
  2324. class TestKprofilePhaseFailure:
  2325. """The K-profile phase runs after _apply has committed everything else.
  2326. So an exception there used to reach run_restore's handler, which reports
  2327. ``success: False`` with an empty ``results`` — over archive, spool and
  2328. settings rows that are durable on disk. The honest-reporting theme of this
  2329. feature inverted on exactly the path where it matters, and the post-commit
  2330. MQTT reconfigure (downstream of the raise, inside the same try) was skipped,
  2331. leaving the relay pointed at the pre-restore broker.
  2332. """
  2333. _SETTINGS = {"version": "1.0", "settings": {"mqtt_broker": "restored.local", "currency": "EUR"}}
  2334. def _payload(self, profiles=None):
  2335. return {
  2336. SETTINGS_PATH: dict(self._SETTINGS),
  2337. "kprofiles/00M09A123456789/0.4.json": {
  2338. "profiles": [{"filament_id": "GFA00", "name": "Bambu PLA"}] if profiles is None else profiles
  2339. },
  2340. }
  2341. def _session_patch(self, db_session):
  2342. cm = AsyncMock()
  2343. cm.__aenter__ = AsyncMock(return_value=db_session)
  2344. cm.__aexit__ = AsyncMock(return_value=None)
  2345. return patch("backend.app.services.github_restore.async_session", return_value=cm)
  2346. async def _configured_service(self, db_session, payload):
  2347. from backend.app.models.github_backup import GitHubBackupConfig
  2348. config = GitHubBackupConfig(repository_url="https://github.com/o/r", access_token="tok", provider="github")
  2349. db_session.add(config)
  2350. await db_session.commit()
  2351. service = _service()
  2352. service._resolve_ref = AsyncMock(return_value=("a" * 40, "", None))
  2353. service._read_categories = AsyncMock(return_value=(payload, ""))
  2354. return service, config.id
  2355. @pytest.mark.asyncio
  2356. async def test_the_committed_categories_are_still_reported(self, db_session):
  2357. service = _service()
  2358. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  2359. results = await service._apply(
  2360. db_session,
  2361. self._payload(),
  2362. [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES],
  2363. False,
  2364. )
  2365. assert results[RestoreCategory.SETTINGS.value].restored == 2
  2366. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  2367. assert rows == {"mqtt_broker": "restored.local", "currency": "EUR"}, "committed before the phase that failed"
  2368. @pytest.mark.asyncio
  2369. async def test_the_failure_is_counted_and_explained(self, db_session):
  2370. service = _service()
  2371. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  2372. results = await service._apply(
  2373. db_session,
  2374. self._payload(profiles=[{"filament_id": "GFA00"}, {"filament_id": "GFB99"}]),
  2375. [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES],
  2376. False,
  2377. )
  2378. tally = results[RestoreCategory.KPROFILES.value]
  2379. assert tally.failed == 2, "every profile the payload carried is unaccounted for"
  2380. assert tally.restored == 0
  2381. assert _codes(tally) == ["kprofilesStepFailed"]
  2382. assert tally.notes[0]["params"]["reason"] == "mqtt exploded"
  2383. @pytest.mark.asyncio
  2384. async def test_the_relay_is_reconfigured_even_though_the_phase_failed(self, db_session):
  2385. """The reconfigure sits downstream of the raise in run_restore's try."""
  2386. service, config_id = await self._configured_service(db_session, self._payload())
  2387. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  2388. relay = MagicMock()
  2389. relay.configure = AsyncMock(return_value=True)
  2390. with self._session_patch(db_session), patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2391. result = await service.run_restore(
  2392. config_id, "a" * 40, [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES]
  2393. )
  2394. assert result["success"] is True
  2395. assert result["results"][RestoreCategory.SETTINGS.value]["restored"] == 2
  2396. assert result["results"][RestoreCategory.KPROFILES.value]["failed"] == 1
  2397. relay.configure.assert_awaited_once()
  2398. assert relay.configure.await_args.args[0]["mqtt_broker"] == "restored.local"
  2399. @pytest.mark.asyncio
  2400. async def test_a_failure_before_the_commit_still_reports_nothing_restored(self, db_session):
  2401. """Control: rolling back and saying so is right when nothing landed."""
  2402. service, config_id = await self._configured_service(db_session, self._payload())
  2403. service._restore_settings = AsyncMock(side_effect=RuntimeError("read failed"))
  2404. relay = MagicMock()
  2405. relay.configure = AsyncMock(return_value=True)
  2406. with self._session_patch(db_session), patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2407. result = await service.run_restore(
  2408. config_id, "a" * 40, [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES]
  2409. )
  2410. assert result["success"] is False
  2411. assert result["results"] == {}
  2412. assert (await db_session.execute(select(Settings))).scalars().first() is None
  2413. relay.configure.assert_not_awaited()
  2414. @pytest.mark.asyncio
  2415. async def test_a_malformed_profiles_value_is_a_skipped_category_not_a_raise(self, db_session, printer_factory):
  2416. """Belt-and-braces: the pre-loop count ran ahead of the per-call guards.
  2417. ``sum(len(c.get("profiles") or []) ...)`` raises TypeError on a
  2418. hand-edited or truncated backup whose ``profiles`` is not a list — and it
  2419. raises after the database categories are already on disk.
  2420. """
  2421. await printer_factory(serial_number="00M09A123456789")
  2422. client = MagicMock()
  2423. client.state.connected = True
  2424. client.set_kprofiles_batch = MagicMock(return_value="7")
  2425. client.get_kprofiles = AsyncMock(return_value=[])
  2426. tally = _CategoryTally()
  2427. with patch("backend.app.services.github_restore.printer_manager") as manager:
  2428. manager.get_client = MagicMock(return_value=client)
  2429. await _service()._restore_kprofiles(db_session, self._payload(profiles=5), tally)
  2430. client.set_kprofiles_batch.assert_not_called()
  2431. assert (tally.restored, tally.failed) == (0, 0)
  2432. assert "kprofilesStepFailed" not in _codes(tally)
  2433. class TestResolveRef:
  2434. @pytest.mark.asyncio
  2435. async def test_concrete_sha_passes_through_without_an_api_call(self):
  2436. service = _service()
  2437. service.list_commits = AsyncMock()
  2438. config = MagicMock(branch="main")
  2439. resolved, error, commit = await service._resolve_ref(config, "abc1234")
  2440. assert resolved == "abc1234"
  2441. assert error == ""
  2442. # Nothing was fetched, so there is no entry to describe it with.
  2443. assert commit is None
  2444. service.list_commits.assert_not_awaited()
  2445. @pytest.mark.asyncio
  2446. async def test_head_resolves_to_the_tip_sha(self):
  2447. service = _service()
  2448. service.list_commits = AsyncMock(
  2449. return_value={"success": True, "commits": [{"sha": "tipsha1"}, {"sha": "older"}]}
  2450. )
  2451. config = MagicMock(branch="main")
  2452. resolved, error, commit = await service._resolve_ref(config, "HEAD")
  2453. assert resolved == "tipsha1"
  2454. assert error == ""
  2455. # Handed back so preview does not list commits a second time just to
  2456. # describe the one it already fetched.
  2457. assert commit == {"sha": "tipsha1"}
  2458. @pytest.mark.asyncio
  2459. async def test_empty_history_is_an_error(self):
  2460. service = _service()
  2461. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  2462. config = MagicMock(branch="main")
  2463. resolved, error, commit = await service._resolve_ref(config, "HEAD")
  2464. assert resolved is None
  2465. assert "no commits" in error
  2466. assert commit is None
  2467. class TestDescribeCommit:
  2468. """A preview that says `commit: null` gives the user no idea what they picked."""
  2469. def _config(self):
  2470. return MagicMock(branch="main", provider="github", repository_url="https://github.com/o/r", access_token="t")
  2471. def _entry(self, sha: str):
  2472. return {"sha": sha, "message": "Bambuddy backup", "author": "Bambuddy", "date": "2026-07-01T10:00:00Z"}
  2473. @pytest.mark.asyncio
  2474. async def test_an_abbreviated_ref_matches_a_full_sha_in_the_window(self):
  2475. """REF_PATTERN accepts 7 characters; providers return 40.
  2476. The old exact `==` therefore never matched an abbreviated ref, even when
  2477. the commit was right there in the top 20.
  2478. """
  2479. service = _service()
  2480. full = "abc1234" + "0" * 33
  2481. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry(full)]})
  2482. found = await service._describe_commit(self._config(), "abc1234")
  2483. assert found is not None
  2484. assert found["sha"] == full
  2485. @pytest.mark.asyncio
  2486. async def test_a_full_sha_matches_an_abbreviated_entry(self):
  2487. service = _service()
  2488. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry("abc1234")]})
  2489. found = await service._describe_commit(self._config(), "abc1234" + "0" * 33)
  2490. assert found is not None
  2491. @pytest.mark.asyncio
  2492. async def test_a_commit_outside_the_window_is_fetched_directly(self):
  2493. service = _service()
  2494. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry("f" * 40)]})
  2495. backend = MagicMock()
  2496. backend.get_commit = AsyncMock(return_value={"success": True, "commit": self._entry("old" + "0" * 37)})
  2497. with patch("backend.app.services.github_restore.get_provider_backend", return_value=backend):
  2498. found = await service._describe_commit(self._config(), "old" + "0" * 37)
  2499. assert found["sha"] == "old" + "0" * 37
  2500. backend.get_commit.assert_awaited_once()
  2501. @pytest.mark.asyncio
  2502. async def test_a_direct_lookup_failure_is_not_fatal(self):
  2503. """It is a subject line: render the preview without it."""
  2504. service = _service()
  2505. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  2506. backend = MagicMock()
  2507. backend.get_commit = AsyncMock(return_value={"success": False, "message": "boom", "commit": None})
  2508. with patch("backend.app.services.github_restore.get_provider_backend", return_value=backend):
  2509. assert await service._describe_commit(self._config(), "a" * 40) is None
  2510. @pytest.mark.asyncio
  2511. async def test_the_window_scan_is_not_run_twice(self):
  2512. """_resolve_ref already listed commits for HEAD; preview reuses that."""
  2513. service = _service()
  2514. tip = self._entry("t" * 40)
  2515. service.list_commits = AsyncMock(return_value={"success": True, "commits": [tip]})
  2516. resolved, _, commit = await service._resolve_ref(self._config(), "HEAD")
  2517. assert resolved == "t" * 40
  2518. assert commit == tip
  2519. assert service.list_commits.await_count == 1