settings.py 91 KB

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