settings.py 88 KB

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