settings.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. import io
  2. import json
  3. import logging
  4. import os
  5. import zipfile
  6. from datetime import datetime
  7. from pathlib import Path
  8. from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
  9. from fastapi.responses import FileResponse, JSONResponse
  10. from pydantic import BaseModel, Field
  11. from sqlalchemy import func, select
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from backend.app.core.auth import (
  14. RequestPrinterScope,
  15. RequireAdminIfAuthEnabled,
  16. RequirePermissionIfAuthEnabled,
  17. ScopedCaller,
  18. caller_is_api_key,
  19. is_auth_enabled,
  20. require_auth_if_enabled,
  21. require_energy_cost_update,
  22. )
  23. from backend.app.core.config import APP_VERSION, settings as app_settings
  24. from backend.app.core.database import get_db
  25. from backend.app.core.permissions import Permission
  26. from backend.app.core.printer_scope import PrinterScope
  27. from backend.app.models.settings import Settings
  28. from backend.app.models.user import User
  29. from backend.app.schemas.settings import ADMIN_ONLY_SETTING_KEYS, AppSettings, AppSettingsUpdate
  30. from backend.app.services import camera_light
  31. from backend.app.services.secret_fields import SETTINGS_SECRETS, SecretConfigError, mask_fields, merge_partial
  32. logger = logging.getLogger(__name__)
  33. router = APIRouter(prefix="/settings", tags=["settings"])
  34. DEFAULT_SETTINGS = AppSettings()
  35. # Sensitive credential fields blanked for API-key callers. Everyone else sees
  36. # them as the placeholder (write-only secrets, see services/secret_fields).
  37. _SENSITIVE_FIELDS_FOR_API_KEY = tuple(SETTINGS_SECRETS)
  38. async def get_setting(db: AsyncSession, key: str) -> str | None:
  39. """Get a single setting value by key."""
  40. result = await db.execute(select(Settings).where(Settings.key == key))
  41. setting = result.scalar_one_or_none()
  42. return setting.value if setting else None
  43. # Accepted spellings for a boolean settings value. Settings live in a VARCHAR
  44. # column and every reader compares them as strings, so these are normalised to
  45. # "true"/"false" on the way in. The sets are deliberately generous: these
  46. # endpoints are part of the documented REST surface, reached by scripts and by
  47. # Home Assistant rest_command, where "True", "1" and "on" are all natural.
  48. _TRUTHY_SETTING_VALUES = frozenset({"true", "1", "yes", "on"})
  49. _FALSY_SETTING_VALUES = frozenset({"false", "0", "no", "off"})
  50. def setting_is_true(value: object) -> bool:
  51. """Return True if a *stored* settings value means "on".
  52. Deliberately narrower than the spellings ``normalize_bool_setting`` accepts:
  53. it matches only what every other reader in the codebase treats as on
  54. (``value.lower() == "true"``). Submitted values are canonicalised on write,
  55. so a stored value is always "true"/"false"/""; accepting "1" or "on" here
  56. would make this function disagree with the rest of the app about any legacy
  57. row containing them.
  58. A bool is tolerated for the case of a row written before values were
  59. normalised, where SQLite coerced a raw bool into the VARCHAR column.
  60. """
  61. if isinstance(value, bool):
  62. return value
  63. if value is None:
  64. return False
  65. return str(value).strip().lower() == "true"
  66. def normalize_bool_setting(key: str, value: object) -> str:
  67. """Coerce a boolean-ish settings value to the canonical "true"/"false".
  68. Raises HTTPException(400) for values with no sensible interpretation, so an
  69. API client gets a message naming the field instead of a 500.
  70. A JSON boolean is the natural thing for an API client to send, and before
  71. this normalisation it caused two distinct failures on
  72. ``PUT /settings/spoolman``: ``bool.lower()`` raised AttributeError, and the
  73. raw bool was written into a VARCHAR column, which SQLite silently coerces
  74. to 1/0 while asyncpg rejects outright. Both surfaced as an opaque 500.
  75. """
  76. if isinstance(value, bool): # must precede the int branch — bool is an int
  77. return "true" if value else "false"
  78. if isinstance(value, int):
  79. if value in (0, 1):
  80. return "true" if value else "false"
  81. raise HTTPException(400, f"{key} must be a boolean; got the number {value}")
  82. if isinstance(value, str):
  83. candidate = value.strip().lower()
  84. if not candidate:
  85. # Empty is stored verbatim rather than normalised to "false".
  86. # get_spoolman_settings reads these with ``or "<default>"``, so an
  87. # empty stored value means "use the default" — and two of them
  88. # (spoolman_report_partial_usage, auto_add_unknown_rfid) default to
  89. # ON. Rewriting "" to "false" would silently switch them off for any
  90. # client that submits a blank value.
  91. return ""
  92. if candidate in _TRUTHY_SETTING_VALUES:
  93. return "true"
  94. if candidate in _FALSY_SETTING_VALUES:
  95. return "false"
  96. raise HTTPException(400, f"{key} must be a boolean; got {value!r}")
  97. raise HTTPException(400, f"{key} must be a boolean; got {type(value).__name__}")
  98. def normalize_str_setting(key: str, value: object) -> str:
  99. """Return a string settings value, rejecting types that would store garbage.
  100. ``str()`` on a dict or list would persist its repr, so those are refused
  101. rather than silently written. Numbers are accepted and stringified: a port
  102. or a bare host submitted unquoted is a plausible client mistake, not a
  103. reason to fail the request.
  104. """
  105. if isinstance(value, str):
  106. return value
  107. if value is None:
  108. return ""
  109. if isinstance(value, bool | int | float):
  110. return str(value)
  111. raise HTTPException(400, f"{key} must be a string; got {type(value).__name__}")
  112. async def get_external_base_url(db: AsyncSession) -> str:
  113. """Base URL for links Bambuddy hands to the outside world (no trailing slash).
  114. ``external_url`` is optional and has no default, so anything that must be
  115. absolute — a login link in an e-mail, the one-tap outcome verdict links
  116. (#1898), whose Telegram/ntfy buttons are dropped for a relative URL — falls
  117. back to APP_URL and finally to the dev origin.
  118. """
  119. import os
  120. external_url = await get_setting(db, "external_url")
  121. if external_url:
  122. return external_url.rstrip("/")
  123. return os.environ.get("APP_URL", "http://localhost:5173").rstrip("/")
  124. async def get_external_login_url(db: AsyncSession) -> str:
  125. """Get the external URL for the login page.
  126. Uses external_url from settings if available, otherwise falls back to APP_URL env var.
  127. Args:
  128. db: Database session
  129. Returns:
  130. Full URL to the login page
  131. """
  132. return await get_external_base_url(db) + "/login"
  133. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  134. """Set a single setting value."""
  135. from backend.app.core.db_dialect import upsert_setting
  136. await upsert_setting(db, Settings, key, value)
  137. # Settings stored as booleans / numbers. Storage is a VARCHAR column, so
  138. # _build_settings_response() parses these back, and update_settings() refuses
  139. # an explicit null for them: a null is stored as the literal "None", which
  140. # reads back as False for a boolean and is not a number at all.
  141. _BOOL_SETTING_KEYS = frozenset(
  142. {
  143. "auto_archive",
  144. "save_thumbnails",
  145. "capture_finish_photo",
  146. "finish_photo_restore_plate",
  147. "spoolman_enabled",
  148. "spoolman_disable_weight_sync",
  149. "spoolman_report_partial_usage",
  150. "auto_add_unknown_rfid",
  151. "disable_filament_warnings",
  152. "prefer_lowest_filament",
  153. "check_updates",
  154. "check_printer_firmware",
  155. "include_beta_updates",
  156. "announcements_enabled",
  157. "announcements_all_users",
  158. "virtual_printer_enabled",
  159. "ftp_retry_enabled",
  160. "mqtt_enabled",
  161. "mqtt_use_tls",
  162. "ha_enabled",
  163. "per_printer_mapping_expanded",
  164. "prometheus_enabled",
  165. "user_notifications_enabled",
  166. "queue_drying_enabled",
  167. "queue_drying_block",
  168. "ambient_drying_enabled",
  169. "print_drying_enabled",
  170. "require_plate_clear",
  171. "queue_shortest_first",
  172. # default_bed_levelling / default_flow_cali / default_nozzle_offset_cali
  173. # are tri-state strings (off/on/auto) — parsed via the raw-string else
  174. # branch; the TriState validator coerces legacy "true"/"false" rows.
  175. "default_vibration_cali",
  176. "default_layer_inspect",
  177. "default_timelapse",
  178. "default_confirm_outcome",
  179. "confirm_outcome_external_prints",
  180. "confirm_default_good_on_plate_clear",
  181. "billing_enabled",
  182. "printer_kill_switch_enabled",
  183. "ldap_enabled",
  184. "ldap_auto_provision",
  185. "local_login_enabled",
  186. "preheat_enabled",
  187. "queue_keep_bed_warm",
  188. }
  189. )
  190. _FLOAT_SETTING_KEYS = frozenset(
  191. {
  192. "default_filament_cost",
  193. "energy_cost_per_kwh",
  194. "camera_light_delay",
  195. "ams_temp_good",
  196. "ams_temp_fair",
  197. "library_disk_warning_gb",
  198. "low_stock_threshold",
  199. }
  200. )
  201. # String settings limited to a fixed set of values, which a stored "None"
  202. # would break when the settings response is built.
  203. _ENUM_SETTING_KEYS = frozenset({"energy_price_source"})
  204. _INT_SETTING_KEYS = frozenset(
  205. {
  206. "ams_humidity_good",
  207. "ams_humidity_fair",
  208. "ams_history_retention_days",
  209. "printer_sensor_history_retention_days",
  210. "ftp_retry_count",
  211. "ftp_retry_delay",
  212. "ftp_timeout",
  213. "mqtt_port",
  214. "stagger_group_size",
  215. "stagger_interval_minutes",
  216. "forecast_global_lead_time_days",
  217. "location_sensor_poll_interval",
  218. "finance_budget_reset_day",
  219. "session_max_hours",
  220. "pipeline_max_copies",
  221. "preheat_max_wait_seconds",
  222. "preheat_soak_seconds",
  223. "queue_keep_warm_bed_temp",
  224. "queue_keep_warm_max_minutes",
  225. "queue_max_concurrent_uploads",
  226. "ambient_drying_sustained_minutes",
  227. }
  228. )
  229. async def _build_settings_response(db: AsyncSession, is_api_key: bool = False, mask: bool = True) -> AppSettings:
  230. """Build the full settings response.
  231. Secrets are blank for API-key callers and the placeholder for everyone else;
  232. ``mask=False`` is for server-side use only (comparing with an update).
  233. """
  234. settings_dict = DEFAULT_SETTINGS.model_dump()
  235. result = await db.execute(select(Settings))
  236. for setting in result.scalars().all():
  237. if setting.key not in settings_dict:
  238. continue
  239. if setting.key in _BOOL_SETTING_KEYS:
  240. settings_dict[setting.key] = setting.value.lower() == "true"
  241. elif setting.key in _FLOAT_SETTING_KEYS or setting.key in _INT_SETTING_KEYS:
  242. # A value that does not parse (the literal "None" from an old
  243. # null save, or a hand-edited row) keeps the default instead of
  244. # taking the whole settings response down with it.
  245. parse = int if setting.key in _INT_SETTING_KEYS else float
  246. try:
  247. settings_dict[setting.key] = parse(setting.value)
  248. except (TypeError, ValueError):
  249. logger.warning("Setting %s has an unparseable value; using the default", setting.key)
  250. elif setting.key in [
  251. # Nullable floats. Settings storage stringifies None to the literal
  252. # "None", which must read back as null here -- not as the default
  253. # the _FLOAT_SETTING_KEYS branch above falls back to (#2905).
  254. "ams_temp_alarm",
  255. ]:
  256. try:
  257. settings_dict[setting.key] = float(setting.value)
  258. except (TypeError, ValueError):
  259. settings_dict[setting.key] = None
  260. elif setting.key == "default_printer_id":
  261. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  262. elif setting.key == "open_in_slicer":
  263. # None means "inherit from preferred_slicer" (#1329). The PUT path
  264. # serializes None as the literal string "None"; strip it back so
  265. # the frontend sees a true null and falls back as intended.
  266. settings_dict[setting.key] = setting.value if setting.value and setting.value != "None" else None
  267. else:
  268. settings_dict[setting.key] = setting.value
  269. ha_settings = await get_homeassistant_settings(db)
  270. settings_dict.update(ha_settings)
  271. # ldap_bind_password is never returned to any caller (mask=False is
  272. # server-side only)
  273. if mask or is_api_key:
  274. settings_dict["ldap_bind_password"] = ""
  275. if is_api_key:
  276. for field in _SENSITIVE_FIELDS_FOR_API_KEY:
  277. if field in settings_dict:
  278. settings_dict[field] = ""
  279. elif mask:
  280. settings_dict = mask_fields(settings_dict, SETTINGS_SECRETS)
  281. return AppSettings(**settings_dict)
  282. @router.get("", response_model=AppSettings)
  283. @router.get("/", response_model=AppSettings)
  284. async def get_settings(
  285. db: AsyncSession = Depends(get_db),
  286. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  287. _is_api_key: bool = Depends(caller_is_api_key),
  288. ):
  289. """Get all application settings."""
  290. return await _build_settings_response(db, is_api_key=_is_api_key)
  291. def _as_stored_setting(value: object) -> str:
  292. """The text the settings writer below stores for ``value``."""
  293. if isinstance(value, bool):
  294. return "true" if value else "false"
  295. if value is None:
  296. return "None"
  297. return str(value)
  298. def _same_setting_value(new: object, old: object) -> bool:
  299. """Whether saving ``new`` stores exactly what ``old`` is stored as."""
  300. return _as_stored_setting(new) == _as_stored_setting(old)
  301. @router.put("/", response_model=AppSettings)
  302. async def update_settings(
  303. settings_update: AppSettingsUpdate,
  304. db: AsyncSession = Depends(get_db),
  305. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  306. ):
  307. """Update application settings."""
  308. update_data = settings_update.model_dump(exclude_unset=True)
  309. # Write-only secrets: the placeholder keeps the stored value, and a kept
  310. # secret does not follow a changed destination.
  311. stored = (await _build_settings_response(db, mask=False)).model_dump()
  312. secrets = dict(SETTINGS_SECRETS)
  313. if stored.get("ha_token_from_env"):
  314. # The deployment's own token, not a stored secret to enter again: the
  315. # URL may change (the placeholder sent back still writes nothing).
  316. secrets["ha_token"] = ()
  317. try:
  318. update_data = merge_partial(stored, update_data, secrets)
  319. except SecretConfigError as exc:
  320. raise HTTPException(status_code=400, detail=str(exc)) from None
  321. # An explicit null for a boolean or numeric setting has no meaning -- these
  322. # are not clearable -- and would be stored as the literal "None".
  323. null_keys = sorted(
  324. key
  325. for key, value in update_data.items()
  326. if value is None and key in (_BOOL_SETTING_KEYS | _FLOAT_SETTING_KEYS | _INT_SETTING_KEYS | _ENUM_SETTING_KEYS)
  327. )
  328. if null_keys:
  329. raise HTTPException(status_code=422, detail=f"These settings cannot be null: {', '.join(null_keys)}")
  330. # Settings that decide who can sign in are admin-only, like the user routes.
  331. # Only a real change counts: the settings page sends every field on each
  332. # save, so an unchanged value from a non-admin must pass.
  333. if current_user is not None and not current_user.is_admin:
  334. changed = sorted(
  335. key
  336. for key in update_data
  337. if key in ADMIN_ONLY_SETTING_KEYS and not _same_setting_value(update_data[key], stored.get(key))
  338. )
  339. if changed:
  340. raise HTTPException(
  341. status_code=403,
  342. detail=f"Only an administrator can change these settings: {', '.join(changed)}",
  343. )
  344. # Like an API key's or a provider's printers: a page still open from before
  345. # a printer delete would save the deleted id, which SQLite gives to the next
  346. # printer created (the validator has already checked it is a list of ints).
  347. # Only ids not stored yet are checked: the page sends the whole list, and an
  348. # id already there must not block every save.
  349. if update_data.get("obico_enabled_printers"):
  350. from backend.app.core.printer_scope import ensure_printers_exist
  351. try:
  352. stored = json.loads(await get_setting(db, "obico_enabled_printers") or "[]")
  353. except ValueError:
  354. stored = []
  355. stored = set(stored) if isinstance(stored, list) else set()
  356. added = [i for i in json.loads(update_data["obico_enabled_printers"]) if i not in stored]
  357. await ensure_printers_exist(db, added)
  358. # Safety refusals on disabling local login (#1589). Two failure modes
  359. # would otherwise lock everyone out of the install:
  360. # 1. No enabled OIDC provider exists — nobody could authenticate.
  361. # 2. The caller has no UserOIDCLink — they would lock themselves out
  362. # even if other admins are linked.
  363. # Either case returns HTTP 400 instead of silently saving. The
  364. # ``BAMBUDDY_LOCAL_LOGIN=true`` env-var bypass on /auth/login is a
  365. # separate recovery path; the refusals here protect the *default*
  366. # configuration where the env var is absent.
  367. if update_data.get("local_login_enabled") is False:
  368. from backend.app.models.oidc_provider import OIDCProvider, UserOIDCLink
  369. enabled_count = await db.scalar(select(func.count(OIDCProvider.id)).where(OIDCProvider.is_enabled.is_(True)))
  370. if not enabled_count:
  371. raise HTTPException(
  372. status_code=400,
  373. detail="Cannot disable local login: no OIDC provider is enabled.",
  374. )
  375. if current_user is not None:
  376. caller_links = await db.scalar(
  377. select(func.count(UserOIDCLink.id)).where(UserOIDCLink.user_id == current_user.id)
  378. )
  379. if not caller_links:
  380. raise HTTPException(
  381. status_code=400,
  382. detail="Cannot disable local login: your account has no OIDC link, so you would lock yourself out.",
  383. )
  384. # Check if any MQTT settings are being updated
  385. mqtt_keys = {
  386. "mqtt_enabled",
  387. "mqtt_broker",
  388. "mqtt_port",
  389. "mqtt_username",
  390. "mqtt_password",
  391. "mqtt_topic_prefix",
  392. "mqtt_use_tls",
  393. }
  394. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  395. # The page saves every field it shows on each change, so compare against
  396. # what is stored: only a real change of price source is worth a read.
  397. price_source_changed = False
  398. for key in ("energy_price_source", "energy_price_ha_entity"):
  399. if key in update_data and str(update_data[key]) != (await get_setting(db, key) or ""):
  400. price_source_changed = True
  401. for key, value in update_data.items():
  402. # Convert value to string for storage
  403. await set_setting(db, key, _as_stored_setting(value))
  404. await db.commit()
  405. # Expire all objects to ensure fresh reads after commit
  406. db.expire_all()
  407. if {"camera_light_mode", "camera_light_delay"} & set(update_data.keys()):
  408. camera_light.invalidate_settings()
  409. if price_source_changed:
  410. # Read a newly chosen price sensor now, so the saved settings show its
  411. # price instead of the old one until the next hourly read (#1251).
  412. from backend.app.services.energy_price import current_price
  413. try:
  414. await current_price(db, remember=True)
  415. await db.commit()
  416. except Exception as e:
  417. logger.warning("Could not read the electricity price after saving its source: %s", e)
  418. # Reconfigure MQTT relay if any MQTT settings changed
  419. if mqtt_updated:
  420. try:
  421. from backend.app.services.mqtt_relay import mqtt_relay
  422. mqtt_settings = {
  423. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  424. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  425. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  426. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  427. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  428. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  429. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  430. }
  431. await mqtt_relay.configure(mqtt_settings)
  432. except Exception:
  433. pass # Don't fail the settings update if MQTT reconfiguration fails
  434. # Return updated settings, secrets as the placeholder
  435. return await _build_settings_response(db, is_api_key=False)
  436. @router.patch("/", response_model=AppSettings)
  437. @router.patch("", response_model=AppSettings)
  438. async def patch_settings(
  439. settings_update: AppSettingsUpdate,
  440. db: AsyncSession = Depends(get_db),
  441. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  442. ):
  443. """Partially update application settings (same as PUT, for REST compatibility)."""
  444. return await update_settings(settings_update, db, _)
  445. class ElectricityPriceUpdate(BaseModel):
  446. """Payload for ``POST /settings/electricity-price`` (#1356).
  447. Mirrors the field name documented in ``wiki/features/energy.md`` so the
  448. Home Assistant ``rest_command`` example needs only a URL change, not a
  449. payload change. Plain non-negative float; tariffs can go as low as 0.0 in
  450. some markets (e.g. free hours).
  451. """
  452. energy_cost_per_kwh: float = Field(ge=0)
  453. @router.post("/electricity-price", response_model=AppSettings)
  454. async def update_electricity_price(
  455. payload: ElectricityPriceUpdate,
  456. db: AsyncSession = Depends(get_db),
  457. _: ScopedCaller = Depends(require_energy_cost_update()),
  458. _is_api_key: bool = Depends(caller_is_api_key),
  459. ):
  460. """Update the per-kWh electricity cost used by the energy-tracking pipeline.
  461. This is the only settings field writable via API key, gated by the
  462. ``can_update_energy_cost`` toggle on the key. JWT users still need the
  463. standard ``SETTINGS_UPDATE`` permission. See #1356 for the rationale —
  464. the general ``PATCH /settings`` route remains denied for API keys because
  465. it can rewrite SMTP/LDAP/MQTT credentials, which is a much wider surface
  466. than the documented dynamic-tariff use case requires.
  467. """
  468. await set_setting(db, "energy_cost_per_kwh", str(payload.energy_cost_per_kwh))
  469. await db.commit()
  470. db.expire_all()
  471. return await _build_settings_response(db, is_api_key=_is_api_key)
  472. @router.post("/reset", response_model=AppSettings)
  473. async def reset_settings(
  474. db: AsyncSession = Depends(get_db),
  475. _admin: User | None = RequireAdminIfAuthEnabled(),
  476. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  477. ):
  478. """Reset all settings to defaults."""
  479. # Delete all settings
  480. result = await db.execute(select(Settings))
  481. for setting in result.scalars().all():
  482. await db.delete(setting)
  483. await db.commit()
  484. camera_light.invalidate_settings()
  485. return DEFAULT_SETTINGS
  486. @router.get("/default-sidebar-order")
  487. async def get_default_sidebar_order(
  488. db: AsyncSession = Depends(get_db),
  489. ):
  490. """Get the admin-set default sidebar order.
  491. Intentionally unauthenticated: non-admin users need to read this value to apply
  492. the default sidebar order, but may lack SETTINGS_READ permission.
  493. The value is non-sensitive (sidebar item IDs only).
  494. """
  495. value = await get_setting(db, "default_sidebar_order")
  496. return {"default_sidebar_order": value or ""}
  497. # Fields exposed via /ui-preferences without SETTINGS_READ. Each entry MUST be
  498. # non-sensitive (no credentials, no PII, no secret tokens) — granting SETTINGS_READ
  499. # also grants visibility of SMTP/LDAP/MQTT passwords and similar, so the goal of
  500. # this endpoint is exactly to NOT require that permission for UI rendering hints.
  501. # When adding a field here, confirm it doesn't carry anything sensitive.
  502. _UI_PREFERENCE_FIELDS: tuple[str, ...] = (
  503. "require_plate_clear",
  504. "check_printer_firmware",
  505. "camera_view_mode",
  506. "time_format",
  507. "date_format",
  508. "drying_presets",
  509. "ams_humidity_thresholds",
  510. "ams_humidity_good",
  511. "ams_humidity_fair",
  512. "ams_temp_good",
  513. "ams_temp_fair",
  514. # ams_temp_alarm is deliberately NOT here. This endpoint is unauthenticated
  515. # and exists so the UI can colour readings without SETTINGS_READ; the good /
  516. # fair bands are what the printer card colours by. The alarm threshold
  517. # changes no rendering anywhere -- only SettingsPage reads it, and that is
  518. # behind the settings permissions already (#2905).
  519. "bed_cooled_threshold",
  520. # Temperature / fan-speed presets for the printer-card popovers. Numbers
  521. # only; no PII / credentials.
  522. "nozzle_temp_presets",
  523. "bed_temp_presets",
  524. "chamber_temp_presets",
  525. "fan_speed_presets",
  526. )
  527. @router.get("/ui-preferences")
  528. async def get_ui_preferences(db: AsyncSession = Depends(get_db)):
  529. """Get the curated subset of settings that any page needs to render correctly.
  530. Intentionally not gated on SETTINGS_READ — every authenticated user (and
  531. every page that loads for them) needs these fields, but granting SETTINGS_READ
  532. would also grant visibility of secrets (SMTP/LDAP/MQTT credentials, etc.).
  533. Same pattern as /default-sidebar-order (#1293).
  534. Reuses _build_settings_response so the typed values match what /settings
  535. returns for fields with the same name — bool/int/float/str types stay in
  536. sync without a separate type-coercion path.
  537. """
  538. full = await _build_settings_response(db, is_api_key=False)
  539. dumped = full.model_dump()
  540. return {key: dumped[key] for key in _UI_PREFERENCE_FIELDS if key in dumped}
  541. # Install configuration the app shell reads before it can render correctly.
  542. #
  543. # Deliberately a second list rather than more entries in _UI_PREFERENCE_FIELDS.
  544. # That one is served to anyone at all, on the recorded grounds that its contents
  545. # are "public defaults that ship with the app" (test_route_auth_coverage.py), and
  546. # its field set is pinned by a test written to make anyone adding to it stop and
  547. # think. These fields are not defaults -- they are facts about how this
  548. # particular deployment is configured -- so they get their own endpoint at their
  549. # own trust level instead of stretching that charter to fit them.
  550. _UI_FLAG_FIELDS: tuple[str, ...] = (
  551. # The sidebar hides Finance unless billing is on. Layout read this from
  552. # GET /settings, which requires SETTINGS_READ, so for a non-admin the query
  553. # 403'd, the value arrived undefined, `undefined !== true` held, and the
  554. # entry was hidden from exactly the users cost_centers:read_own exists to
  555. # serve. The page itself was reachable by URL the whole time (#3023).
  556. "billing_enabled",
  557. # Same 403, opposite outcome. That gate tests `=== false`, which undefined
  558. # never satisfies, so an administrator who turned user notifications off
  559. # still left the entry showing -- to precisely the non-admins it governs.
  560. "user_notifications_enabled",
  561. # Not gates, but read by the shell and equally undefined for a non-admin:
  562. # the sponsor prompt fell back to EUR whatever the install uses, and the
  563. # update check ran even where it had been switched off.
  564. "currency",
  565. "check_updates",
  566. # Read by the print dialog, queue, file manager, inventory and SpoolBuddy
  567. # pages, which users without SETTINGS_READ open too: the 403 dropped them
  568. # all to their defaults (with billing on, the print dialog hid the cost
  569. # centre picker and the print was then refused for lacking one).
  570. "queue_shortest_first",
  571. "use_slicer_api",
  572. "open_in_slicer",
  573. "preferred_slicer",
  574. "disable_filament_warnings",
  575. "prefer_lowest_filament",
  576. "per_printer_mapping_expanded",
  577. "default_filament_cost",
  578. "default_bed_levelling",
  579. "default_flow_cali",
  580. "default_vibration_cali",
  581. "default_layer_inspect",
  582. "default_timelapse",
  583. "default_nozzle_offset_cali",
  584. "default_confirm_outcome",
  585. "stagger_group_size",
  586. "stagger_interval_minutes",
  587. "library_disk_warning_gb",
  588. "low_stock_threshold",
  589. "location_sensor_poll_interval",
  590. "location_sensor_alert_defaults",
  591. "pipeline_max_copies",
  592. "language",
  593. "dark_style",
  594. "dark_background",
  595. "dark_accent",
  596. "light_style",
  597. "light_background",
  598. "light_accent",
  599. # Which inventory a new spool goes to (unknown-tag prompt), and the
  600. # forecast's default lead time.
  601. "spoolman_enabled",
  602. "forecast_global_lead_time_days",
  603. # Preselected in the print dialog; withheld below from a caller who may
  604. # not use that printer.
  605. "default_printer_id",
  606. )
  607. @router.get("/ui-flags")
  608. async def get_ui_flags(
  609. db: AsyncSession = Depends(get_db),
  610. _: User | None = Depends(require_auth_if_enabled),
  611. printer_scope: PrinterScope = RequestPrinterScope,
  612. ):
  613. """Install configuration the app shell needs, for any signed-in user.
  614. Gated on being authenticated rather than on ``SETTINGS_READ``. The sidebar
  615. has to know whether billing is enabled before it can decide whether to offer
  616. Finance, and ``SETTINGS_READ`` cannot be the price of knowing that -- it also
  617. grants sight of the SMTP, LDAP and MQTT credentials.
  618. ``require_auth_if_enabled`` returns ``None`` when auth is switched off
  619. entirely, which is the case /ui-preferences was left ungated for. That is the
  620. distinction the two endpoints draw: "works when there is no auth" is not the
  621. same statement as "readable by anyone", and conflating them is what put a
  622. settings read in front of a permission that was never meant to require one.
  623. """
  624. full = await _build_settings_response(db, is_api_key=False)
  625. dumped = full.model_dump()
  626. flags = {key: dumped[key] for key in _UI_FLAG_FIELDS if key in dumped}
  627. if flags.get("default_printer_id") is not None and not printer_scope.allows(flags["default_printer_id"]):
  628. flags["default_printer_id"] = None
  629. # Whether G-code snippets are set up, not the snippets themselves.
  630. flags["has_gcode_snippets"] = bool(dumped.get("gcode_snippets"))
  631. return flags
  632. @router.get("/check-ffmpeg")
  633. async def check_ffmpeg(
  634. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  635. ):
  636. """Check if ffmpeg is installed and available.
  637. Gated on ``SETTINGS_READ`` (audit finding I4 — the binary path was
  638. leaking the host filesystem layout to unauthenticated callers).
  639. ``require_permission_if_auth_enabled`` returns ``None`` only when
  640. auth is disabled (in which case there's no privacy boundary to
  641. enforce); otherwise it raises 401/403 before we get here.
  642. """
  643. from backend.app.services.camera import get_ffmpeg_path
  644. ffmpeg_path = get_ffmpeg_path()
  645. return {
  646. "installed": ffmpeg_path is not None,
  647. "path": ffmpeg_path,
  648. }
  649. @router.get("/spoolman")
  650. async def get_spoolman_settings(
  651. db: AsyncSession = Depends(get_db),
  652. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  653. ):
  654. """Get Spoolman integration settings."""
  655. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  656. spoolman_url = await get_setting(db, "spoolman_url") or ""
  657. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  658. spoolman_disable_weight_sync = await get_setting(db, "spoolman_disable_weight_sync") or "false"
  659. spoolman_report_partial_usage = await get_setting(db, "spoolman_report_partial_usage") or "true"
  660. auto_add_unknown_rfid = await get_setting(db, "auto_add_unknown_rfid") or "true"
  661. return {
  662. "spoolman_enabled": spoolman_enabled,
  663. "spoolman_url": spoolman_url,
  664. "spoolman_sync_mode": spoolman_sync_mode,
  665. "spoolman_disable_weight_sync": spoolman_disable_weight_sync,
  666. "spoolman_report_partial_usage": spoolman_report_partial_usage,
  667. "auto_add_unknown_rfid": auto_add_unknown_rfid,
  668. }
  669. @router.put("/spoolman")
  670. async def update_spoolman_settings(
  671. settings: dict,
  672. db: AsyncSession = Depends(get_db),
  673. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  674. ):
  675. """Update Spoolman integration settings.
  676. The body is a free-form dict rather than a schema, so each value is
  677. normalised before it is persisted — see ``normalize_bool_setting`` for why
  678. a JSON boolean used to produce a 500 here.
  679. """
  680. if "spoolman_enabled" in settings:
  681. was_enabled = setting_is_true(await get_setting(db, "spoolman_enabled"))
  682. new_val = normalize_bool_setting("spoolman_enabled", settings["spoolman_enabled"])
  683. now_enabled = new_val == "true"
  684. await set_setting(db, "spoolman_enabled", new_val)
  685. # Nothing is deleted on a mode change (#2812). Each mode keeps its slot
  686. # assignments in its own table, so both can hold rows at once and the
  687. # toggle is reversible: switching to Spoolman to see what it does, then
  688. # switching back, returns you to the assignments you had.
  689. #
  690. # This used to empty the other mode's table on every toggle. The reason
  691. # was real -- checks that read both tables would let a row in the mode
  692. # you are not using answer for the mode you are -- but the cost was that
  693. # inspecting a mode destroyed your configuration, with no confirmation
  694. # and no way back, and the deletion was unfiltered across every printer.
  695. # The readers that could be confused now ask which mode is active
  696. # (``spoolman_owns_assignments``), which is where that decision belongs:
  697. # the mode is a property of the install, not of the rows.
  698. if was_enabled != now_enabled:
  699. logger.info(
  700. "Inventory mode switched to %s; slot assignments in both tables kept",
  701. "Spoolman" if now_enabled else "built-in",
  702. )
  703. if "spoolman_url" in settings:
  704. await set_setting(db, "spoolman_url", normalize_str_setting("spoolman_url", settings["spoolman_url"]))
  705. if "spoolman_sync_mode" in settings:
  706. await set_setting(
  707. db, "spoolman_sync_mode", normalize_str_setting("spoolman_sync_mode", settings["spoolman_sync_mode"])
  708. )
  709. for bool_key in ("spoolman_disable_weight_sync", "spoolman_report_partial_usage", "auto_add_unknown_rfid"):
  710. if bool_key in settings:
  711. await set_setting(db, bool_key, normalize_bool_setting(bool_key, settings[bool_key]))
  712. spoolman_changed = "spoolman_enabled" in settings or "spoolman_url" in settings
  713. await db.commit()
  714. db.expire_all()
  715. if spoolman_changed:
  716. from backend.app.services.location_service import maybe_sync_spoolman_locations
  717. if await maybe_sync_spoolman_locations(db):
  718. await db.commit()
  719. # Return updated settings
  720. return await get_spoolman_settings(db)
  721. async def get_homeassistant_settings(db: AsyncSession) -> dict:
  722. """
  723. Get Home Assistant integration settings.
  724. Environment variables (HA_URL, HA_TOKEN) take precedence over database settings.
  725. """
  726. import os
  727. # Check environment variables first
  728. ha_url_env = os.environ.get("HA_URL")
  729. ha_token_env = os.environ.get("HA_TOKEN")
  730. # Fall back to database values
  731. ha_url = ha_url_env or await get_setting(db, "ha_url") or ""
  732. ha_token = ha_token_env or await get_setting(db, "ha_token") or ""
  733. ha_enabled_db = await get_setting(db, "ha_enabled") or "false"
  734. # Track which settings come from environment
  735. ha_url_from_env = bool(ha_url_env)
  736. ha_token_from_env = bool(ha_token_env)
  737. ha_env_managed = ha_url_from_env and ha_token_from_env
  738. # Auto-enable when both env vars are set, otherwise use database value
  739. if ha_url_env and ha_token_env:
  740. ha_enabled = True
  741. else:
  742. ha_enabled = ha_enabled_db.lower() == "true"
  743. return {
  744. "ha_enabled": ha_enabled,
  745. "ha_url": ha_url,
  746. "ha_token": ha_token,
  747. "ha_url_from_env": ha_url_from_env,
  748. "ha_token_from_env": ha_token_from_env,
  749. "ha_env_managed": ha_env_managed,
  750. }
  751. async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
  752. """Create a complete backup ZIP (database + all data directories).
  753. If output_path is given, the ZIP is written there.
  754. Otherwise a temporary file is created (caller must clean up).
  755. Returns (zip_path, filename).
  756. """
  757. import shutil
  758. import tempfile
  759. from backend.app.core.db_dialect import is_sqlite
  760. base_dir = app_settings.base_dir
  761. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  762. with tempfile.TemporaryDirectory() as temp_dir:
  763. temp_path = Path(temp_dir)
  764. if is_sqlite():
  765. from sqlalchemy import text
  766. from backend.app.core.database import engine
  767. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  768. # Checkpoint WAL to ensure all data is in main db file
  769. async with engine.begin() as conn:
  770. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  771. # Copy database file
  772. shutil.copy2(db_path, temp_path / "bambuddy.db")
  773. else:
  774. # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
  775. # This makes backups restorable on both SQLite and Postgres installs.
  776. import json
  777. import sqlite3
  778. from sqlalchemy import create_engine as create_sync_engine
  779. from backend.app.core.database import Base, engine
  780. backup_db_path = temp_path / "bambuddy.db"
  781. metadata = Base.metadata
  782. # Build the portable SQLite schema with SQLAlchemy's own DDL rather
  783. # than a hand-rolled CREATE TABLE. metadata.create_all() emits the
  784. # exact schema a native SQLite install gets — NOT NULL, DEFAULT
  785. # (server_default=func.now() → CURRENT_TIMESTAMP), foreign keys,
  786. # unique constraints and indexes. The previous name+type-only
  787. # rebuild dropped all of these, so a Postgres→SQLite restore left
  788. # server_default columns (e.g. spoolbuddy_devices.created_at) with
  789. # no DEFAULT — SQLAlchemy omits such columns on INSERT and the DB
  790. # then wrote NULL, which 500'd on the next read (#2526). Using the
  791. # real DDL also keeps the #1333 BLOB guard: LargeBinary still
  792. # renders as BLOB, so OIDC icon bytes survive the round trip.
  793. schema_engine = create_sync_engine(f"sqlite:///{backup_db_path}")
  794. try:
  795. metadata.create_all(schema_engine)
  796. finally:
  797. schema_engine.dispose()
  798. dst = sqlite3.connect(str(backup_db_path))
  799. # Export data from Postgres to SQLite
  800. async with engine.connect() as conn:
  801. for table in metadata.sorted_tables:
  802. result = await conn.execute(table.select())
  803. rows = result.fetchall()
  804. if not rows:
  805. continue
  806. columns = list(result.keys())
  807. placeholders = ", ".join(["?"] * len(columns))
  808. col_list = ", ".join(columns)
  809. insert_sql = f"INSERT INTO {table.name} ({col_list}) VALUES ({placeholders})" # noqa: S608 # nosec B608 — table/column names from ORM metadata, not user input
  810. def _serialize_row(row):
  811. return tuple(json.dumps(v) if isinstance(v, (list, dict)) else v for v in row)
  812. dst.executemany(insert_sql, [_serialize_row(row) for row in rows])
  813. dst.commit()
  814. dst.close()
  815. logger.info("PostgreSQL backup exported to portable SQLite format")
  816. # Copy data directories (if they exist)
  817. dirs_to_backup = [
  818. ("archive", base_dir / "archive"),
  819. ("virtual_printer", base_dir / "virtual_printer"),
  820. ("plate_calibration", app_settings.plate_calibration_dir),
  821. ("icons", base_dir / "icons"),
  822. ("projects", base_dir / "projects"),
  823. ("overlay-branding", base_dir / "overlay-branding"),
  824. ]
  825. for name, src_dir in dirs_to_backup:
  826. if src_dir.exists() and any(src_dir.iterdir()):
  827. try:
  828. shutil.copytree(
  829. src_dir, temp_path / name
  830. ) # SEC-PATH-OK: name iterates the dirs_to_backup tuple of constant strings ("archive", "virtual_printer", ...)
  831. except shutil.Error as e:
  832. logger.warning("Some files in %s could not be copied: %s", name, e)
  833. except PermissionError as e:
  834. logger.warning("Permission denied copying %s: %s", name, e)
  835. # Say which version made this, so a restore that cannot import it can
  836. # name the versions rather than a list of columns. Backups from before
  837. # this existed simply have no manifest, and restore treats the version
  838. # as unknown.
  839. import json as _json
  840. manifest = {
  841. "format": 1,
  842. "app_version": APP_VERSION,
  843. "created_at": datetime.now().isoformat(timespec="seconds"),
  844. "database": "sqlite" if is_sqlite() else "postgresql",
  845. }
  846. (temp_path / "manifest.json").write_text(_json.dumps(manifest, indent=2) + "\n")
  847. # Include the MFA encryption key as a ZIP top-level entry alongside
  848. # bambuddy.db. Without it, encrypted client_secret / TOTP secret rows
  849. # would be unrecoverable after restore on a host without MFA_ENCRYPTION_KEY set.
  850. from backend.app.core.paths import resolve_data_dir
  851. mfa_key_src = resolve_data_dir() / ".mfa_encryption_key"
  852. if mfa_key_src.exists() and mfa_key_src.is_file():
  853. try:
  854. shutil.copy2(mfa_key_src, temp_path / ".mfa_encryption_key")
  855. except OSError as exc:
  856. logger.error(
  857. "Could not include MFA encryption key in backup (%s). "
  858. "The backup ZIP will not contain the key — restore on a "
  859. "keyless host will fail for encrypted secrets.",
  860. exc,
  861. )
  862. raise
  863. # Create ZIP
  864. if output_path is not None:
  865. zip_file = (
  866. output_path / filename
  867. ) # SEC-PATH-OK: filename = f"bambuddy-backup-{datetime.now()...}.zip" generated in create_backup_zip itself
  868. else:
  869. fd, tmp = tempfile.mkstemp(suffix=".zip")
  870. os.close(fd)
  871. zip_file = Path(tmp)
  872. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  873. for file_path in temp_path.rglob("*"):
  874. if file_path.is_file():
  875. arcname = file_path.relative_to(temp_path)
  876. zf.write(file_path, arcname)
  877. return zip_file, filename
  878. @router.get("/backup")
  879. async def create_backup(
  880. db: AsyncSession = Depends(get_db),
  881. _admin: User | None = RequireAdminIfAuthEnabled(),
  882. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  883. ):
  884. """Create a complete backup (database + all files) as a ZIP download."""
  885. from starlette.background import BackgroundTask
  886. try:
  887. zip_file, filename = await create_backup_zip()
  888. return FileResponse(
  889. path=zip_file,
  890. filename=filename,
  891. media_type="application/zip",
  892. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  893. )
  894. except Exception as e:
  895. logger.error("Backup failed: %s", e, exc_info=True)
  896. return JSONResponse(
  897. status_code=500,
  898. content={"success": False, "message": "Backup failed. Check server logs for details."},
  899. )
  900. class BackupSchemaIncompatible(Exception):
  901. """The backup has no value for a column this version requires.
  902. A backup carries the schema of the install that made it. Restoring it into
  903. a different version means the destination can have NOT NULL columns the
  904. backup never heard of -- either because that version is older and still has
  905. a column since removed (``user_wallets.currency``, dropped in #3123), or
  906. because it is newer and has added one. Most such columns have a default and
  907. can simply be filled. The ones that cannot are what this reports, and it has
  908. to be reported BEFORE the restore drops anything: the Postgres import wipes
  909. every table in the first transaction, so a failure halfway leaves the
  910. install with an empty schema and the previous data gone.
  911. """
  912. def _missing_required_columns(pg_table, src_columns: set[str]):
  913. """Split the destination's NOT NULL columns that the backup lacks.
  914. Returns ``(injectable, db_filled, unfillable)``:
  915. * ``injectable`` -- ``{name: value}`` from the model's Python-side default.
  916. These are invisible to the import's raw SQL: SQLAlchemy applies a
  917. ``default=`` on ORM and Core inserts, never on ``text()``, and
  918. ``create_all`` emits no DDL default for one. So a column like
  919. ``currency VARCHAR(3) NOT NULL`` with ``default="EUR"`` arrives with
  920. nothing to put in it unless we put it there.
  921. * ``db_filled`` -- has a server default or is the autoincrement key; the
  922. database fills it when the column is left out of the INSERT.
  923. * ``unfillable`` -- nothing can supply a value. The backup is incompatible.
  924. """
  925. injectable: dict = {}
  926. db_filled: list[str] = []
  927. unfillable: list[str] = []
  928. for col in pg_table.columns:
  929. if col.nullable or col.name in src_columns:
  930. continue
  931. if col.default is not None:
  932. arg = col.default.arg
  933. injectable[col.name] = arg(None) if callable(arg) else arg
  934. elif col.server_default is not None or col.primary_key:
  935. db_filled.append(col.name)
  936. else:
  937. unfillable.append(col.name)
  938. return injectable, db_filled, unfillable
  939. def check_backup_schema_compatible(sqlite_path: Path, backup_version: str | None = None) -> None:
  940. """Raise if this version cannot import that backup. Touches nothing.
  941. Only the cross-engine path needs this. A SQLite install restores by copying
  942. the backup's pages, schema included, and `init_db()` migrates it forward
  943. afterwards; the Postgres import instead recreates the schema from THIS
  944. process's ORM and then inserts the backup's columns into it.
  945. """
  946. import sqlite3
  947. from backend.app.core.database import Base
  948. src = sqlite3.connect(f"file:{sqlite_path}?mode=ro", uri=True)
  949. try:
  950. src_tables = {
  951. row[0]
  952. for row in src.execute(
  953. "SELECT name FROM sqlite_master WHERE type='table' "
  954. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  955. )
  956. }
  957. problems: list[str] = []
  958. # metadata.tables, not sorted_tables: the latter warns about the
  959. # library_files/library_folders/print_archives cycle, and nothing here
  960. # depends on the order.
  961. for name, pg_table in Base.metadata.tables.items():
  962. if name not in src_tables:
  963. continue
  964. # An empty table inserts nothing, so a column it cannot supply
  965. # cannot fail. Refusing a restore over one would be a false alarm.
  966. if src.execute(f'SELECT 1 FROM "{name}" LIMIT 1').fetchone() is None: # noqa: S608 # nosec B608 — name comes from ORM metadata
  967. continue
  968. src_columns = {row[1] for row in src.execute(f'PRAGMA table_info("{name}")')}
  969. _, _, unfillable = _missing_required_columns(pg_table, src_columns)
  970. problems.extend(f"{name}.{col}" for col in unfillable)
  971. finally:
  972. src.close()
  973. if not problems:
  974. return
  975. made_by = f"The backup was made by Bambuddy {backup_version}, " if backup_version else "The backup "
  976. raise BackupSchemaIncompatible(
  977. "This backup cannot be restored by this version of Bambuddy. It carries no value for "
  978. f"{len(problems)} column(s) this version requires and cannot default: {', '.join(sorted(problems))}. "
  979. f"{made_by}and this install runs {APP_VERSION}. Restore it on the version that made it, or "
  980. "upgrade this install to that version. Nothing has been changed."
  981. )
  982. def _read_backup_manifest(temp_path: Path) -> dict:
  983. """The backup's manifest.json, or {} for a backup made before it existed."""
  984. import json
  985. path = temp_path / "manifest.json"
  986. if not path.is_file():
  987. return {}
  988. try:
  989. data = json.loads(path.read_text())
  990. except (OSError, ValueError) as exc:
  991. logger.warning("Ignoring unreadable backup manifest: %s", exc)
  992. return {}
  993. return data if isinstance(data, dict) else {}
  994. def _restored_value_fixes(table_name: str) -> dict[str, tuple[tuple[str, ...], str]]:
  995. """Columns of ``table_name`` whose backed-up value must be one of a set, with its fallback.
  996. Older versions stored any project priority or status; one longer than the
  997. column fails the whole import on PostgreSQL. The fallbacks are the ones
  998. project import and the start-up repair use.
  999. """
  1000. if table_name != "projects":
  1001. return {}
  1002. from backend.app.models.project import PROJECT_PRIORITIES, PROJECT_STATUSES
  1003. return {"priority": (PROJECT_PRIORITIES, "normal"), "status": (PROJECT_STATUSES, "active")}
  1004. async def _import_sqlite_to_postgres(sqlite_path: Path):
  1005. """Import data from a SQLite database file into the current PostgreSQL database.
  1006. Used for cross-database restore (SQLite backup → PostgreSQL).
  1007. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  1008. """
  1009. import sqlite3
  1010. from sqlalchemy import text
  1011. from backend.app.core.database import AUTOINCREMENT_TABLES, Base, _create_engine, highest_referenced_id
  1012. # Before anything is dropped. The route checks this too, earlier and with
  1013. # the backup's version in the message; this call is what makes the guarantee
  1014. # a property of the import itself rather than of one caller.
  1015. check_backup_schema_compatible(sqlite_path)
  1016. # Create a temporary engine for the import (current engine was disposed)
  1017. pg_engine = _create_engine()
  1018. try:
  1019. # Open SQLite file directly (sync — it's a local file read)
  1020. src = sqlite3.connect(str(sqlite_path))
  1021. src.row_factory = sqlite3.Row
  1022. # Get list of tables from SQLite (skip internal/FTS tables)
  1023. cursor = src.execute(
  1024. "SELECT name FROM sqlite_master WHERE type='table' "
  1025. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  1026. )
  1027. src_tables = {row["name"] for row in cursor.fetchall()}
  1028. # Where SQLite's own counters stand: ids freed there are not given out
  1029. # again on PostgreSQL either (a backup from before they were kept has none).
  1030. src_counters: dict[str, int] = {}
  1031. if src.execute("SELECT 1 FROM sqlite_master WHERE name = 'sqlite_sequence'").fetchone():
  1032. src_counters = {row["name"]: row["seq"] for row in src.execute("SELECT name, seq FROM sqlite_sequence")}
  1033. # Get Postgres tables from our ORM models
  1034. metadata = Base.metadata
  1035. pg_tables = set(metadata.tables.keys())
  1036. # Only import tables that exist in both source and destination
  1037. tables_to_import = src_tables & pg_tables
  1038. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  1039. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  1040. # This avoids all FK ordering/orphan issues during import; the
  1041. # constraints go back on at the end, once every row has landed.
  1042. async with pg_engine.begin() as conn:
  1043. # Cap how long DROP TABLE will wait for AccessExclusiveLock so
  1044. # any residual concurrent writer (per-printer MQTT clients
  1045. # writing reactively, an AMS history recorder firing on its
  1046. # hourly cadence) surfaces a fast `lock_timeout` error instead
  1047. # of blocking the restore for 30 s or producing a deadlock.
  1048. # SET LOCAL scopes to this transaction only; outside this
  1049. # restore path the global default (no timeout) applies.
  1050. await conn.execute(text("SET LOCAL lock_timeout = '10s'"))
  1051. # Drop every existing table in the public schema with CASCADE
  1052. # rather than `metadata.drop_all`. Two reasons:
  1053. # 1. The user's live DB may carry orphan tables from removed
  1054. # features (e.g. the legacy `spoolman_slot_assignments`,
  1055. # `spoolman_k_profile`) that hold FK constraints back to
  1056. # ORM tables. `drop_all` doesn't know they exist and emits
  1057. # `DROP TABLE printers` without CASCADE — Postgres refuses
  1058. # and the whole restore aborts (#XXXX).
  1059. # 2. Even within the metadata, `drop_all` is FK-ordered and
  1060. # breaks if a future schema rename leaves old constraints
  1061. # around. CASCADE is the right tool for a destructive
  1062. # restore: the user is intentionally wiping state.
  1063. await conn.execute(
  1064. text(
  1065. "DO $$ DECLARE r RECORD; BEGIN "
  1066. "FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP "
  1067. "EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE'; "
  1068. "END LOOP; END $$;"
  1069. )
  1070. )
  1071. await conn.run_sync(metadata.create_all)
  1072. # Now strip the foreign keys, at the database level.
  1073. #
  1074. # This used to be done by discarding each ForeignKeyConstraint
  1075. # from `table.constraints` before `create_all`. That only
  1076. # suppresses the inline REFERENCES clause inside CREATE TABLE:
  1077. # `Table.foreign_key_constraints` is derived from the *columns'*
  1078. # ForeignKey objects, which the discard never touched. When
  1079. # `create_all` meets a dependency cycle it can't sort -- and
  1080. # library_files / library_folders / print_archives are exactly
  1081. # such a cycle -- it falls back to emitting those tables' keys
  1082. # as separate ALTER TABLE ... ADD FOREIGN KEY statements read
  1083. # straight from that property. Twelve constraints survived,
  1084. # including library_files.folder_id, and because the same cycle
  1085. # also drops the ordering edge from `sorted_tables` the child
  1086. # table was imported before its parent and the restore died on
  1087. # a ForeignKeyViolationError.
  1088. #
  1089. # Dropping them from pg_constraint instead is indifferent to how
  1090. # create_all chose to emit them, so a future model cycle cannot
  1091. # reintroduce this. It also keeps the app's global Base.metadata
  1092. # untouched: the old code only put the constraints back *after*
  1093. # the transaction, so a failure in here left the running process
  1094. # with an FK-less metadata until restart.
  1095. await conn.execute(
  1096. text(
  1097. "DO $$ DECLARE r RECORD; BEGIN "
  1098. "FOR r IN (SELECT conrelid::regclass AS tbl, conname FROM pg_constraint "
  1099. "WHERE contype = 'f' AND connamespace = 'public'::regnamespace) LOOP "
  1100. "EXECUTE 'ALTER TABLE ' || r.tbl || ' DROP CONSTRAINT ' || quote_ident(r.conname); "
  1101. "END LOOP; END $$;"
  1102. )
  1103. )
  1104. # Phase 2: Import data (no FKs to worry about)
  1105. async with pg_engine.begin() as conn:
  1106. # Import each table in dependency order (parents before children)
  1107. for table_name in sorted_tables:
  1108. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  1109. if not rows:
  1110. continue
  1111. # Filter to columns that exist in the Postgres table
  1112. src_columns = rows[0].keys()
  1113. pg_table = metadata.tables.get(table_name)
  1114. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  1115. columns = [c for c in src_columns if c in pg_columns]
  1116. if not columns:
  1117. continue
  1118. # Columns this schema requires that the backup does not have at
  1119. # all. The block below handles a column PRESENT in the backup
  1120. # with a NULL in it; one the backup never had is not in
  1121. # `columns` and so never reached it -- which is how a backup
  1122. # from an install without `user_wallets.currency` died on
  1123. # NotNullViolationError against a version that still had it.
  1124. injected, _db_filled, _unfillable = _missing_required_columns(pg_table, set(src_columns))
  1125. if injected:
  1126. logger.info(
  1127. "Filling %s column(s) absent from the backup in %s: %s",
  1128. len(injected),
  1129. table_name,
  1130. ", ".join(sorted(injected)),
  1131. )
  1132. insert_columns = columns + list(injected)
  1133. col_list = ", ".join(insert_columns)
  1134. param_list = ", ".join(f":{c}" for c in insert_columns)
  1135. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  1136. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  1137. # Identify columns that need type conversion (SQLite stores booleans
  1138. # as int and datetimes as str — asyncpg requires native Python types)
  1139. from datetime import datetime as dt
  1140. bool_columns = set()
  1141. datetime_columns = set()
  1142. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  1143. if pg_table is not None:
  1144. for col in pg_table.columns:
  1145. if col.name not in columns:
  1146. continue
  1147. col_type = str(col.type)
  1148. if col_type == "BOOLEAN":
  1149. bool_columns.add(col.name)
  1150. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  1151. datetime_columns.add(col.name)
  1152. # Track NOT NULL columns with defaults — older backups may have NULL
  1153. # for columns added after the backup was created
  1154. if not col.nullable:
  1155. if col.default is not None:
  1156. default = col.default.arg
  1157. if callable(default):
  1158. default = default(None)
  1159. not_null_defaults[col.name] = default
  1160. elif col.server_default is not None:
  1161. # server_default=func.now() → use current timestamp
  1162. if col.name in datetime_columns:
  1163. not_null_defaults[col.name] = "__now__"
  1164. else:
  1165. # Try to extract literal server default
  1166. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  1167. if sd is not None:
  1168. not_null_defaults[col.name] = sd
  1169. now = dt.now()
  1170. value_fixes = _restored_value_fixes(table_name)
  1171. def _convert_row(
  1172. row,
  1173. cols=columns,
  1174. bools=bool_columns,
  1175. dts=datetime_columns,
  1176. nn_defaults=not_null_defaults,
  1177. _now=now,
  1178. inject=injected,
  1179. fixes=value_fixes,
  1180. ):
  1181. result = dict(inject)
  1182. for c in cols:
  1183. val = row[c]
  1184. if val is None and c in nn_defaults:
  1185. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  1186. if val is not None:
  1187. if c in bools:
  1188. val = bool(val)
  1189. elif c in dts and isinstance(val, str):
  1190. try:
  1191. val = dt.fromisoformat(val)
  1192. except ValueError:
  1193. pass
  1194. result[c] = val
  1195. for c, (allowed, fallback) in fixes.items():
  1196. if c in result and result[c] not in allowed:
  1197. result[c] = fallback
  1198. return result
  1199. batch = [_convert_row(row) for row in rows]
  1200. await conn.execute(insert_sql, batch)
  1201. logger.info("Imported %d rows into %s", len(batch), table_name)
  1202. # Reset sequences to max(id) + 1 for each table with an id column;
  1203. # for AUTOINCREMENT_TABLES past SQLite's counter and every id still
  1204. # referred to, so a deleted row's id is not given to a new one.
  1205. for table_name in sorted_tables:
  1206. try:
  1207. async with conn.begin_nested():
  1208. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  1209. max_id = result.scalar()
  1210. if table_name in AUTOINCREMENT_TABLES:
  1211. max_id = max(
  1212. max_id or 0,
  1213. src_counters.get(table_name) or 0,
  1214. await highest_referenced_id(conn, table_name),
  1215. )
  1216. if max_id:
  1217. seq_name = f"{table_name}_id_seq"
  1218. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  1219. except Exception:
  1220. pass # Table may not have an id column or sequence
  1221. src.close()
  1222. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  1223. # Recreate FK constraints from ORM metadata, which Phase 1 left intact.
  1224. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  1225. from sqlalchemy.schema import AddConstraint
  1226. failed_fks = []
  1227. for table in metadata.sorted_tables:
  1228. for fk in table.foreign_key_constraints:
  1229. try:
  1230. async with pg_engine.begin() as fk_conn:
  1231. await fk_conn.execute(AddConstraint(fk))
  1232. except Exception as e:
  1233. # Name the constraint by what it links, not by `fk.name`:
  1234. # these are unnamed in the ORM, so that field is None and
  1235. # the warning used to read "print_archives.None" for every
  1236. # one of the five keys on that table -- unusable for
  1237. # working out which rows to go and look at.
  1238. cols = ", ".join(c.name for c in fk.columns)
  1239. target = fk.elements[0].target_fullname if fk.elements else "unknown"
  1240. failed_fks.append(f"{table.name}({cols}) -> {target}")
  1241. # Postgres puts the offending key in a DETAIL line; it
  1242. # names the exact orphan value, which is the one thing
  1243. # that turns this into an actionable report.
  1244. detail = next(
  1245. (ln.strip() for ln in str(e).splitlines() if ln.startswith("DETAIL:")),
  1246. str(e).splitlines()[0] if str(e) else e.__class__.__name__,
  1247. )
  1248. logger.info("FK %s(%s) -> %s not restored: %s", table.name, cols, target, detail)
  1249. if failed_fks:
  1250. logger.warning(
  1251. "Could not restore %d FK constraints (orphaned data in the backup): %s. "
  1252. "The data is restored and usable; those columns are simply no longer "
  1253. "enforced. See the INFO lines above for the offending key in each case.",
  1254. len(failed_fks),
  1255. ", ".join(failed_fks),
  1256. )
  1257. finally:
  1258. await pg_engine.dispose()
  1259. @router.post("/restore")
  1260. async def restore_backup(
  1261. file: UploadFile = File(...),
  1262. db: AsyncSession = Depends(get_db),
  1263. _admin: User | None = RequireAdminIfAuthEnabled(),
  1264. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  1265. ):
  1266. """Restore from a complete backup ZIP.
  1267. Replaces the database and all data directories from the backup ZIP.
  1268. Requires a restart after restore.
  1269. """
  1270. import shutil
  1271. import tempfile
  1272. from fastapi import HTTPException
  1273. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  1274. from backend.app.core.db_dialect import is_sqlite
  1275. from backend.app.services.virtual_printer import virtual_printer_manager
  1276. base_dir = app_settings.base_dir
  1277. with tempfile.TemporaryDirectory() as temp_dir:
  1278. temp_path = Path(temp_dir)
  1279. # 1. Read and extract ZIP
  1280. content = await file.read()
  1281. # Check if it's a valid ZIP
  1282. if not file.filename or not file.filename.endswith(".zip"):
  1283. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  1284. try:
  1285. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  1286. for name in zf.namelist():
  1287. # Reject path-traversal payloads: any entry whose resolved
  1288. # path escapes temp_path would allow writing arbitrary files
  1289. # on the host (ZipSlip / CVE-2006-5456).
  1290. dest = (
  1291. temp_path / name
  1292. ).resolve() # SEC-PATH-OK: is_relative_to containment check below before extractall
  1293. # is_relative_to (Python 3.9+) covers both relative
  1294. # path-traversal (../etc/passwd) and absolute-path overrides
  1295. # (/etc/passwd) — str.startswith was vulnerable to
  1296. # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
  1297. # a /tmp/abc prefix check).
  1298. if not dest.is_relative_to(temp_path.resolve()):
  1299. raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
  1300. zf.extractall(temp_path)
  1301. except zipfile.BadZipFile:
  1302. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  1303. # 2. Validate backup
  1304. backup_db = temp_path / "bambuddy.db"
  1305. if not backup_db.exists():
  1306. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  1307. # 2b. Can this version import this backup at all?
  1308. #
  1309. # Deliberately here: everything below has a side effect. The virtual
  1310. # printer stops, background services stop, the MFA key file is
  1311. # overwritten with the backup's -- and then the Postgres import drops
  1312. # every table in its first transaction. A backup rejected at the INSERT
  1313. # took the install's data with it and left the encrypted secrets under a
  1314. # key that no longer matches. Nothing above this line has touched
  1315. # anything.
  1316. import sqlite3
  1317. manifest = _read_backup_manifest(temp_path)
  1318. backup_version = manifest.get("app_version")
  1319. if backup_version:
  1320. logger.info("Backup was created by Bambuddy %s; this install runs %s", backup_version, APP_VERSION)
  1321. if not is_sqlite():
  1322. try:
  1323. check_backup_schema_compatible(backup_db, backup_version)
  1324. except BackupSchemaIncompatible as exc:
  1325. logger.error("Refusing backup: %s", exc)
  1326. raise HTTPException(400, str(exc)) from exc
  1327. except sqlite3.DatabaseError as exc:
  1328. raise HTTPException(400, f"Invalid backup: bambuddy.db is not readable ({exc})") from exc
  1329. try:
  1330. import asyncio
  1331. # 3. Stop virtual printer if running (releases file locks)
  1332. try:
  1333. if virtual_printer_manager.is_enabled:
  1334. logger.info("Stopping virtual printer for restore...")
  1335. await virtual_printer_manager.configure(enabled=False)
  1336. await asyncio.sleep(1)
  1337. except Exception as e:
  1338. logger.warning("Failed to stop virtual printer: %s", e)
  1339. # 3b. Pause timer-based background services BEFORE the DB swap.
  1340. # close_all_connections() below only disposes the engine's pool,
  1341. # not the asyncio tasks that opened sessions from it. The print
  1342. # scheduler (30 s cadence), smart-plug snapshot loop (30 s), and
  1343. # notification digest loop all
  1344. # wake up and call async_session(), which lazily re-creates a
  1345. # pool connection holding RowExclusiveLock on print_queue /
  1346. # smart_plug_energy_snapshots / etc. The DROP TABLE CASCADE
  1347. # pass in the PostgreSQL restore path needs AccessExclusiveLock
  1348. # on every public table, producing an AB/BA deadlock and a
  1349. # full restore rollback. Successful restore already requires a
  1350. # container restart, so we don't restart the services here.
  1351. try:
  1352. from backend.app.services.notification_service import notification_service
  1353. from backend.app.services.print_scheduler import scheduler as print_scheduler
  1354. from backend.app.services.smart_plug_manager import smart_plug_manager
  1355. logger.info("Pausing background services for restore...")
  1356. print_scheduler.stop()
  1357. smart_plug_manager.stop_scheduler()
  1358. notification_service.stop_digest_scheduler()
  1359. # In-flight loop iterations need a moment to commit + release
  1360. # their DB sessions before we dispose() the engine pool.
  1361. await asyncio.sleep(1.0)
  1362. except Exception as e:
  1363. logger.warning("Could not cleanly pause background services: %s", e)
  1364. # 4. Close current database connections
  1365. logger.info("Closing database connections...")
  1366. await close_all_connections()
  1367. # B1: Restore the MFA encryption key file BEFORE the database swap.
  1368. # If the key write fails (OSError, RO disk, full disk, EACCES) we
  1369. # can still abort while the live DB is intact. Doing this AFTER the
  1370. # DB swap would leave the database with rows encrypted under the
  1371. # backup's key but the running install holding only the old key —
  1372. # every encrypted secret becomes unrecoverable.
  1373. from backend.app.core.paths import resolve_data_dir
  1374. mfa_key_src = temp_path / ".mfa_encryption_key"
  1375. if mfa_key_src.exists() and mfa_key_src.is_file():
  1376. dst_key = resolve_data_dir() / ".mfa_encryption_key"
  1377. tmp_key = dst_key.parent / ".mfa_encryption_key.restore-tmp"
  1378. try:
  1379. dst_key.parent.mkdir(parents=True, exist_ok=True)
  1380. # S1: atomic write with restrictive mode from creation.
  1381. # O_TRUNC because a stale tmp may exist from a prior
  1382. # failed restore attempt — we want to overwrite it.
  1383. fd = os.open(str(tmp_key), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
  1384. try:
  1385. os.write(fd, mfa_key_src.read_bytes())
  1386. finally:
  1387. os.close(fd)
  1388. # POSIX rename(2) — atomic when source/dest are on the
  1389. # same filesystem (we're staying inside dst_key.parent).
  1390. os.replace(str(tmp_key), str(dst_key))
  1391. # S9: warn if the FS doesn't enforce 0o600
  1392. actual_mode = dst_key.stat().st_mode & 0o777
  1393. if actual_mode != 0o600:
  1394. logger.warning(
  1395. "Restored MFA key file %s: filesystem did not enforce 0o600 "
  1396. "(actual: 0o%o). Key may be world-readable on Windows / SMB / FUSE.",
  1397. dst_key,
  1398. actual_mode,
  1399. )
  1400. logger.info("Restored .mfa_encryption_key from backup")
  1401. except OSError as e:
  1402. logger.error(
  1403. "Could not write restored MFA key file to %s: %s — "
  1404. "aborting BEFORE database swap (DB unchanged).",
  1405. dst_key,
  1406. e,
  1407. exc_info=True,
  1408. )
  1409. raise HTTPException(
  1410. status_code=500,
  1411. detail=("Restore aborted: MFA key write failed. Database is unchanged. Check server logs."),
  1412. ) from e
  1413. # 5. Replace database
  1414. logger.info("Restoring database from backup...")
  1415. if is_sqlite():
  1416. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  1417. # Use SQLite's online backup API instead of shutil.copy2.
  1418. # The pragma at database.py:19 runs the live DB in WAL mode,
  1419. # which means a naive file copy is unsafe: anything written
  1420. # to the live DB before this call that hasn't been
  1421. # checkpointed yet (seed_default_groups + init_db on first
  1422. # start, plus whatever background heartbeats wrote during
  1423. # the request window) sits in bambuddy.db-wal with valid
  1424. # checksums. The route handler's own `db: Depends(get_db)`
  1425. # session also keeps a connection checked out across
  1426. # engine.dispose(), holding fds to the WAL inode. With
  1427. # `shutil.copy2` SQLite finds the stale WAL on the next
  1428. # open and silently re-applies those page-level writes on
  1429. # top of the restored DB, partially clobbering it with
  1430. # fresh-install state — the user sees a "successful"
  1431. # restore where most rows and settings have reverted to
  1432. # defaults (#1211 / #668). The page-by-page backup API
  1433. # opens both DBs as real SQLite connections, takes the
  1434. # right locks, and routes new pages through the live DB's
  1435. # own WAL — so concurrent open sessions see their own
  1436. # snapshot until they close (transaction isolation) but
  1437. # can't corrupt the restored state.
  1438. import sqlite3
  1439. src_conn = sqlite3.connect(str(backup_db))
  1440. try:
  1441. dst_conn = sqlite3.connect(str(db_path))
  1442. try:
  1443. src_conn.backup(dst_conn)
  1444. finally:
  1445. dst_conn.close()
  1446. finally:
  1447. src_conn.close()
  1448. else:
  1449. # Import SQLite backup into PostgreSQL
  1450. logger.info("Importing SQLite backup into PostgreSQL...")
  1451. await _import_sqlite_to_postgres(backup_db)
  1452. # 6. Replace data directories
  1453. # For Docker compatibility: clear contents then copy (don't delete mount points)
  1454. dirs_to_restore = [
  1455. ("archive", base_dir / "archive"),
  1456. ("virtual_printer", base_dir / "virtual_printer"),
  1457. ("plate_calibration", app_settings.plate_calibration_dir),
  1458. ("icons", base_dir / "icons"),
  1459. ("projects", base_dir / "projects"),
  1460. ("overlay-branding", base_dir / "overlay-branding"),
  1461. ]
  1462. skipped_dirs = []
  1463. for name, dest_dir in dirs_to_restore:
  1464. src_dir = (
  1465. temp_path / name
  1466. ) # SEC-PATH-OK: name iterates the dirs_to_restore tuple of constant strings ("archive", "virtual_printer", ...)
  1467. if src_dir.exists():
  1468. logger.info("Restoring %s directory...", name)
  1469. try:
  1470. # Clear destination contents (not the dir itself - may be Docker mount)
  1471. if dest_dir.exists():
  1472. for item in dest_dir.iterdir():
  1473. try:
  1474. if item.is_dir():
  1475. shutil.rmtree(item)
  1476. else:
  1477. item.unlink()
  1478. except OSError as e:
  1479. logger.warning("Could not delete %s: %s", item, e)
  1480. else:
  1481. dest_dir.mkdir(parents=True, exist_ok=True)
  1482. # Copy contents from backup
  1483. for item in src_dir.iterdir():
  1484. dest_item = dest_dir / item.name
  1485. if item.is_dir():
  1486. shutil.copytree(item, dest_item)
  1487. else:
  1488. shutil.copy2(item, dest_item)
  1489. except OSError as e:
  1490. logger.warning("Could not restore %s directory: %s", name, e)
  1491. skipped_dirs.append(name)
  1492. # 7. Reset the encryption singleton so the migration that runs
  1493. # inside init_db() picks up the restored key file (if a new one
  1494. # was written above). Without this reset, _get_fernet would
  1495. # return the cached Fernet instance built from the previous key.
  1496. import backend.app.core.encryption as _enc_mod
  1497. _enc_mod._fernet_instance = None
  1498. _enc_mod._key_source = None
  1499. _enc_mod._warn_shown = False
  1500. # 8. Reinitialize the database engine and apply schema migrations so that
  1501. # tables added after the backup was created (e.g. ams_labels) exist
  1502. # immediately, without requiring a manual restart.
  1503. await reinitialize_database()
  1504. await init_db()
  1505. # 9. Sign everyone out. The restored users and auth tokens come from
  1506. # another point in time, possibly written by older code, so no
  1507. # session issued before the restore should stay valid.
  1508. from backend.app.core import database as _db_mod
  1509. async with _db_mod.engine.begin() as conn:
  1510. await _db_mod.invalidate_all_sessions(conn)
  1511. # Open dashboards of signed-in users too: they are never signed in
  1512. # again. API-key and anonymous ones are not closed outright (nothing
  1513. # ended theirs), but the restored data decides what they may still see: the anonymous ones
  1514. # go if the backup turns authentication on, and the refresh closes
  1515. # those of a key the backup does not have (or has under another key).
  1516. from backend.app.core.auth import invalidate_auth_enabled_cache
  1517. from backend.app.core.websocket import ws_manager
  1518. # Read from the restored data: this request has just cached the
  1519. # setting it had before.
  1520. invalidate_auth_enabled_cache()
  1521. # Cloud presets were cached per user of the replaced user table.
  1522. from backend.app.api.routes.cloud import forget_all_cloud_presets
  1523. forget_all_cloud_presets()
  1524. async with _db_mod.async_session() as auth_db:
  1525. auth_on = await is_auth_enabled(auth_db)
  1526. if auth_on:
  1527. await ws_manager.close_signed_in()
  1528. await ws_manager.close_anonymous()
  1529. await ws_manager.refresh_printer_scopes()
  1530. logger.info("Restore complete - restart required")
  1531. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  1532. if skipped_dirs:
  1533. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  1534. return {
  1535. "success": True,
  1536. "message": message,
  1537. }
  1538. except HTTPException:
  1539. # Preserve specific HTTP error responses raised inside the restore
  1540. # body (e.g. the key-write OSError → 500). The blanket
  1541. # except Exception below would otherwise swallow them and replace
  1542. # the operator-facing detail with a generic message.
  1543. raise
  1544. except Exception as e:
  1545. logger.error("Restore failed: %s", e, exc_info=True)
  1546. return JSONResponse(
  1547. status_code=500,
  1548. content={"success": False, "message": "Restore failed. Check server logs for details."},
  1549. )
  1550. @router.get("/network-interfaces")
  1551. async def get_network_interfaces(
  1552. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1553. ):
  1554. """Get available network interfaces with all IPs (primary + aliases)."""
  1555. from backend.app.services.network_utils import get_all_interface_ips
  1556. interfaces = get_all_interface_ips()
  1557. return {"interfaces": interfaces}
  1558. @router.get("/virtual-printer/models")
  1559. async def get_virtual_printer_models(
  1560. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1561. ):
  1562. """Get available virtual printer models."""
  1563. from backend.app.services.virtual_printer import (
  1564. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1565. VIRTUAL_PRINTER_MODELS,
  1566. )
  1567. return {
  1568. "models": VIRTUAL_PRINTER_MODELS,
  1569. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1570. }
  1571. def _legacy_vp_status(status: dict, printer_scope: PrinterScope) -> dict:
  1572. """The first virtual printer's status, without what names its target for a limited caller."""
  1573. if printer_scope.is_unrestricted:
  1574. return status
  1575. return {key: value for key, value in status.items() if key not in ("name", "serial", "target_printer_ip", "proxy")}
  1576. @router.get("/virtual-printer")
  1577. async def get_virtual_printer_settings(
  1578. db: AsyncSession = Depends(get_db),
  1579. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1580. printer_scope: PrinterScope = RequestPrinterScope,
  1581. ):
  1582. """Get virtual printer settings and status."""
  1583. from backend.app.services.virtual_printer import (
  1584. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1585. virtual_printer_manager,
  1586. )
  1587. enabled = await get_setting(db, "virtual_printer_enabled")
  1588. access_code = await get_setting(db, "virtual_printer_access_code")
  1589. mode = await get_setting(db, "virtual_printer_mode")
  1590. model = await get_setting(db, "virtual_printer_model")
  1591. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  1592. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  1593. tailscale_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  1594. archive_name_source = await get_setting(db, "virtual_printer_archive_name_source")
  1595. from backend.app.models.virtual_printer import VP_MODE_ARCHIVE, normalize_vp_mode
  1596. return {
  1597. "enabled": enabled == "true" if enabled else False,
  1598. "access_code_set": bool(access_code),
  1599. # Normalize on read so older settings rows (with `immediate` /
  1600. # `print_queue`) come out as `archive` / `queue` for the frontend.
  1601. "mode": normalize_vp_mode(mode) or VP_MODE_ARCHIVE,
  1602. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1603. # A target the caller can't see is not named.
  1604. "target_printer_id": int(target_printer_id)
  1605. if target_printer_id and printer_scope.allows(int(target_printer_id))
  1606. else None,
  1607. "remote_interface_ip": remote_interface_ip or "",
  1608. "tailscale_disabled": tailscale_disabled_raw == "true" if tailscale_disabled_raw else True,
  1609. "archive_name_source": archive_name_source if archive_name_source in ("metadata", "filename") else "metadata",
  1610. "status": _legacy_vp_status(virtual_printer_manager.get_status(), printer_scope),
  1611. }
  1612. @router.put("/virtual-printer")
  1613. async def update_virtual_printer_settings(
  1614. enabled: bool = None,
  1615. access_code: str = None,
  1616. mode: str = None,
  1617. model: str = None,
  1618. target_printer_id: int = None,
  1619. remote_interface_ip: str = None,
  1620. tailscale_disabled: bool = None,
  1621. archive_name_source: str = None,
  1622. db: AsyncSession = Depends(get_db),
  1623. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1624. printer_scope: PrinterScope = RequestPrinterScope,
  1625. ):
  1626. """Update virtual printer settings and restart services if needed.
  1627. For proxy mode with SSDP proxy (dual-homed setup):
  1628. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  1629. - Local interface is auto-detected based on target printer IP
  1630. """
  1631. from sqlalchemy import select
  1632. from backend.app.models.printer import Printer
  1633. from backend.app.services.virtual_printer import (
  1634. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1635. VIRTUAL_PRINTER_MODELS,
  1636. virtual_printer_manager,
  1637. )
  1638. # Get current values
  1639. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  1640. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1641. # Default to `archive` (the canonical name) but tolerate legacy `immediate`
  1642. # in the stored value — normalized later before validation.
  1643. current_mode = await get_setting(db, "virtual_printer_mode") or "archive"
  1644. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  1645. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  1646. current_target_id = int(current_target_id_str) if current_target_id_str else None
  1647. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  1648. current_ts_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  1649. # Default True (opt-in) when the setting has never been saved — matches the model default.
  1650. current_ts_disabled = current_ts_disabled_raw == "true" if current_ts_disabled_raw else True
  1651. # Apply updates
  1652. new_enabled = enabled if enabled is not None else current_enabled
  1653. new_access_code = access_code if access_code is not None else current_access_code
  1654. new_mode = mode if mode is not None else current_mode
  1655. new_model = model if model is not None else current_model
  1656. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  1657. # One bridging to a printer the caller can't use is not theirs to change,
  1658. # and they can't aim it at such a printer.
  1659. from backend.app.models.virtual_printer import VirtualPrinter as FirstVP
  1660. # The first virtual printer is the one these settings reach.
  1661. first_vp = (await db.execute(select(FirstVP).order_by(FirstVP.position, FirstVP.id).limit(1))).scalar_one_or_none()
  1662. if not printer_scope.allows(current_target_id) or (
  1663. first_vp is not None and not printer_scope.allows(first_vp.target_printer_id)
  1664. ):
  1665. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  1666. if target_printer_id is not None and not printer_scope.allows(target_printer_id):
  1667. return JSONResponse(status_code=400, content={"detail": f"Printer with ID {target_printer_id} not found"})
  1668. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  1669. new_ts_disabled = tailscale_disabled if tailscale_disabled is not None else current_ts_disabled
  1670. # Validate mode. Canonical wire values are `archive` / `review` / `queue`
  1671. # / `proxy`; legacy `immediate` and `print_queue` are accepted as aliases
  1672. # and translated before storage so support bundles stop showing the old
  1673. # confusing pair (#1429 mode-label discrepancy).
  1674. from backend.app.models.virtual_printer import VP_MODE_VALUES, normalize_vp_mode
  1675. canonical_mode = normalize_vp_mode(new_mode)
  1676. if canonical_mode not in VP_MODE_VALUES:
  1677. return JSONResponse(
  1678. status_code=400,
  1679. content={
  1680. "detail": f"Mode must be one of: {', '.join(VP_MODE_VALUES)}",
  1681. },
  1682. )
  1683. new_mode = canonical_mode
  1684. # Validate archive_name_source
  1685. if archive_name_source is not None and archive_name_source not in ("metadata", "filename"):
  1686. return JSONResponse(
  1687. status_code=400,
  1688. content={"detail": "archive_name_source must be 'metadata' or 'filename'"},
  1689. )
  1690. # Validate model
  1691. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  1692. return JSONResponse(
  1693. status_code=400,
  1694. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  1695. )
  1696. # Mode-specific validation and printer lookup
  1697. target_printer_ip = ""
  1698. target_printer_serial = ""
  1699. if new_mode == "proxy":
  1700. # Proxy mode requires target printer when enabling
  1701. if new_enabled and not new_target_id:
  1702. # If just switching to proxy mode (not explicitly enabling), auto-disable
  1703. if enabled is None:
  1704. new_enabled = False
  1705. else:
  1706. return JSONResponse(
  1707. status_code=400,
  1708. content={"detail": "Target printer is required for proxy mode"},
  1709. )
  1710. # Look up printer IP and serial if we have a target
  1711. if new_target_id:
  1712. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  1713. printer = result.scalar_one_or_none()
  1714. if not printer:
  1715. return JSONResponse(
  1716. status_code=400,
  1717. content={"detail": f"Printer with ID {new_target_id} not found"},
  1718. )
  1719. target_printer_ip = printer.ip_address
  1720. target_printer_serial = printer.serial_number
  1721. # Access code not required for proxy mode
  1722. else:
  1723. # Non-proxy modes require access code when enabling
  1724. if new_enabled and not new_access_code:
  1725. # If just switching modes (not explicitly enabling), auto-disable
  1726. if enabled is None:
  1727. new_enabled = False
  1728. else:
  1729. return JSONResponse(
  1730. status_code=400,
  1731. content={"detail": "Access code is required when enabling virtual printer"},
  1732. )
  1733. # Validate access code length (Bambu Studio requires exactly 8 characters)
  1734. if access_code is not None and access_code and len(access_code) != 8:
  1735. return JSONResponse(
  1736. status_code=400,
  1737. content={"detail": "Access code must be exactly 8 characters"},
  1738. )
  1739. # Save settings
  1740. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  1741. if access_code is not None:
  1742. await set_setting(db, "virtual_printer_access_code", access_code)
  1743. await set_setting(db, "virtual_printer_mode", new_mode)
  1744. if model is not None:
  1745. await set_setting(db, "virtual_printer_model", model)
  1746. if target_printer_id is not None:
  1747. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  1748. if remote_interface_ip is not None:
  1749. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  1750. if tailscale_disabled is not None:
  1751. await set_setting(db, "virtual_printer_tailscale_disabled", "true" if tailscale_disabled else "false")
  1752. if archive_name_source is not None:
  1753. await set_setting(db, "virtual_printer_archive_name_source", archive_name_source)
  1754. # Propagate tailscale_disabled to the first VirtualPrinter row so sync_from_db() picks it up
  1755. if tailscale_disabled is not None:
  1756. if first_vp is not None:
  1757. first_vp.tailscale_disabled = new_ts_disabled
  1758. await db.commit()
  1759. db.expire_all()
  1760. # Reconfigure virtual printer
  1761. try:
  1762. await virtual_printer_manager.configure(
  1763. enabled=new_enabled,
  1764. access_code=new_access_code,
  1765. mode=new_mode,
  1766. model=new_model,
  1767. target_printer_ip=target_printer_ip,
  1768. target_printer_serial=target_printer_serial,
  1769. remote_interface_ip=new_remote_iface,
  1770. )
  1771. except ValueError as e:
  1772. logger.warning("Virtual printer configuration validation error: %s", e)
  1773. return JSONResponse(
  1774. status_code=400,
  1775. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  1776. )
  1777. except Exception as e:
  1778. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  1779. return JSONResponse(
  1780. status_code=500,
  1781. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  1782. )
  1783. return await get_virtual_printer_settings(db, printer_scope=printer_scope)
  1784. # =============================================================================
  1785. # MQTT Relay Settings
  1786. # =============================================================================
  1787. @router.get("/mqtt/status")
  1788. async def get_mqtt_status(
  1789. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1790. ):
  1791. """Get MQTT relay connection status."""
  1792. from backend.app.services.mqtt_relay import mqtt_relay
  1793. return mqtt_relay.get_status()