settings.py 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  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. )
  547. @router.get("/ui-flags")
  548. async def get_ui_flags(
  549. db: AsyncSession = Depends(get_db),
  550. _: User | None = Depends(require_auth_if_enabled),
  551. ):
  552. """Install configuration the app shell needs, for any signed-in user.
  553. Gated on being authenticated rather than on ``SETTINGS_READ``. The sidebar
  554. has to know whether billing is enabled before it can decide whether to offer
  555. Finance, and ``SETTINGS_READ`` cannot be the price of knowing that -- it also
  556. grants sight of the SMTP, LDAP and MQTT credentials.
  557. ``require_auth_if_enabled`` returns ``None`` when auth is switched off
  558. entirely, which is the case /ui-preferences was left ungated for. That is the
  559. distinction the two endpoints draw: "works when there is no auth" is not the
  560. same statement as "readable by anyone", and conflating them is what put a
  561. settings read in front of a permission that was never meant to require one.
  562. """
  563. full = await _build_settings_response(db, is_api_key=False)
  564. dumped = full.model_dump()
  565. return {key: dumped[key] for key in _UI_FLAG_FIELDS if key in dumped}
  566. @router.get("/check-ffmpeg")
  567. async def check_ffmpeg(
  568. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  569. ):
  570. """Check if ffmpeg is installed and available.
  571. Gated on ``SETTINGS_READ`` (audit finding I4 — the binary path was
  572. leaking the host filesystem layout to unauthenticated callers).
  573. ``require_permission_if_auth_enabled`` returns ``None`` only when
  574. auth is disabled (in which case there's no privacy boundary to
  575. enforce); otherwise it raises 401/403 before we get here.
  576. """
  577. from backend.app.services.camera import get_ffmpeg_path
  578. ffmpeg_path = get_ffmpeg_path()
  579. return {
  580. "installed": ffmpeg_path is not None,
  581. "path": ffmpeg_path,
  582. }
  583. @router.get("/spoolman")
  584. async def get_spoolman_settings(
  585. db: AsyncSession = Depends(get_db),
  586. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  587. ):
  588. """Get Spoolman integration settings."""
  589. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  590. spoolman_url = await get_setting(db, "spoolman_url") or ""
  591. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  592. spoolman_disable_weight_sync = await get_setting(db, "spoolman_disable_weight_sync") or "false"
  593. spoolman_report_partial_usage = await get_setting(db, "spoolman_report_partial_usage") or "true"
  594. auto_add_unknown_rfid = await get_setting(db, "auto_add_unknown_rfid") or "true"
  595. return {
  596. "spoolman_enabled": spoolman_enabled,
  597. "spoolman_url": spoolman_url,
  598. "spoolman_sync_mode": spoolman_sync_mode,
  599. "spoolman_disable_weight_sync": spoolman_disable_weight_sync,
  600. "spoolman_report_partial_usage": spoolman_report_partial_usage,
  601. "auto_add_unknown_rfid": auto_add_unknown_rfid,
  602. }
  603. @router.put("/spoolman")
  604. async def update_spoolman_settings(
  605. settings: dict,
  606. db: AsyncSession = Depends(get_db),
  607. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  608. ):
  609. """Update Spoolman integration settings.
  610. The body is a free-form dict rather than a schema, so each value is
  611. normalised before it is persisted — see ``normalize_bool_setting`` for why
  612. a JSON boolean used to produce a 500 here.
  613. """
  614. if "spoolman_enabled" in settings:
  615. was_enabled = setting_is_true(await get_setting(db, "spoolman_enabled"))
  616. new_val = normalize_bool_setting("spoolman_enabled", settings["spoolman_enabled"])
  617. now_enabled = new_val == "true"
  618. await set_setting(db, "spoolman_enabled", new_val)
  619. # Nothing is deleted on a mode change (#2812). Each mode keeps its slot
  620. # assignments in its own table, so both can hold rows at once and the
  621. # toggle is reversible: switching to Spoolman to see what it does, then
  622. # switching back, returns you to the assignments you had.
  623. #
  624. # This used to empty the other mode's table on every toggle. The reason
  625. # was real -- checks that read both tables would let a row in the mode
  626. # you are not using answer for the mode you are -- but the cost was that
  627. # inspecting a mode destroyed your configuration, with no confirmation
  628. # and no way back, and the deletion was unfiltered across every printer.
  629. # The readers that could be confused now ask which mode is active
  630. # (``spoolman_owns_assignments``), which is where that decision belongs:
  631. # the mode is a property of the install, not of the rows.
  632. if was_enabled != now_enabled:
  633. logger.info(
  634. "Inventory mode switched to %s; slot assignments in both tables kept",
  635. "Spoolman" if now_enabled else "built-in",
  636. )
  637. if "spoolman_url" in settings:
  638. await set_setting(db, "spoolman_url", normalize_str_setting("spoolman_url", settings["spoolman_url"]))
  639. if "spoolman_sync_mode" in settings:
  640. await set_setting(
  641. db, "spoolman_sync_mode", normalize_str_setting("spoolman_sync_mode", settings["spoolman_sync_mode"])
  642. )
  643. for bool_key in ("spoolman_disable_weight_sync", "spoolman_report_partial_usage", "auto_add_unknown_rfid"):
  644. if bool_key in settings:
  645. await set_setting(db, bool_key, normalize_bool_setting(bool_key, settings[bool_key]))
  646. spoolman_changed = "spoolman_enabled" in settings or "spoolman_url" in settings
  647. await db.commit()
  648. db.expire_all()
  649. if spoolman_changed:
  650. from backend.app.services.location_service import maybe_sync_spoolman_locations
  651. if await maybe_sync_spoolman_locations(db):
  652. await db.commit()
  653. # Return updated settings
  654. return await get_spoolman_settings(db)
  655. async def get_homeassistant_settings(db: AsyncSession) -> dict:
  656. """
  657. Get Home Assistant integration settings.
  658. Environment variables (HA_URL, HA_TOKEN) take precedence over database settings.
  659. """
  660. import os
  661. # Check environment variables first
  662. ha_url_env = os.environ.get("HA_URL")
  663. ha_token_env = os.environ.get("HA_TOKEN")
  664. # Fall back to database values
  665. ha_url = ha_url_env or await get_setting(db, "ha_url") or ""
  666. ha_token = ha_token_env or await get_setting(db, "ha_token") or ""
  667. ha_enabled_db = await get_setting(db, "ha_enabled") or "false"
  668. # Track which settings come from environment
  669. ha_url_from_env = bool(ha_url_env)
  670. ha_token_from_env = bool(ha_token_env)
  671. ha_env_managed = ha_url_from_env and ha_token_from_env
  672. # Auto-enable when both env vars are set, otherwise use database value
  673. if ha_url_env and ha_token_env:
  674. ha_enabled = True
  675. else:
  676. ha_enabled = ha_enabled_db.lower() == "true"
  677. return {
  678. "ha_enabled": ha_enabled,
  679. "ha_url": ha_url,
  680. "ha_token": ha_token,
  681. "ha_url_from_env": ha_url_from_env,
  682. "ha_token_from_env": ha_token_from_env,
  683. "ha_env_managed": ha_env_managed,
  684. }
  685. async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
  686. """Create a complete backup ZIP (database + all data directories).
  687. If output_path is given, the ZIP is written there.
  688. Otherwise a temporary file is created (caller must clean up).
  689. Returns (zip_path, filename).
  690. """
  691. import shutil
  692. import tempfile
  693. from backend.app.core.db_dialect import is_sqlite
  694. base_dir = app_settings.base_dir
  695. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  696. with tempfile.TemporaryDirectory() as temp_dir:
  697. temp_path = Path(temp_dir)
  698. if is_sqlite():
  699. from sqlalchemy import text
  700. from backend.app.core.database import engine
  701. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  702. # Checkpoint WAL to ensure all data is in main db file
  703. async with engine.begin() as conn:
  704. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  705. # Copy database file
  706. shutil.copy2(db_path, temp_path / "bambuddy.db")
  707. else:
  708. # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
  709. # This makes backups restorable on both SQLite and Postgres installs.
  710. import json
  711. import sqlite3
  712. from sqlalchemy import create_engine as create_sync_engine
  713. from backend.app.core.database import Base, engine
  714. backup_db_path = temp_path / "bambuddy.db"
  715. metadata = Base.metadata
  716. # Build the portable SQLite schema with SQLAlchemy's own DDL rather
  717. # than a hand-rolled CREATE TABLE. metadata.create_all() emits the
  718. # exact schema a native SQLite install gets — NOT NULL, DEFAULT
  719. # (server_default=func.now() → CURRENT_TIMESTAMP), foreign keys,
  720. # unique constraints and indexes. The previous name+type-only
  721. # rebuild dropped all of these, so a Postgres→SQLite restore left
  722. # server_default columns (e.g. spoolbuddy_devices.created_at) with
  723. # no DEFAULT — SQLAlchemy omits such columns on INSERT and the DB
  724. # then wrote NULL, which 500'd on the next read (#2526). Using the
  725. # real DDL also keeps the #1333 BLOB guard: LargeBinary still
  726. # renders as BLOB, so OIDC icon bytes survive the round trip.
  727. schema_engine = create_sync_engine(f"sqlite:///{backup_db_path}")
  728. try:
  729. metadata.create_all(schema_engine)
  730. finally:
  731. schema_engine.dispose()
  732. dst = sqlite3.connect(str(backup_db_path))
  733. # Export data from Postgres to SQLite
  734. async with engine.connect() as conn:
  735. for table in metadata.sorted_tables:
  736. result = await conn.execute(table.select())
  737. rows = result.fetchall()
  738. if not rows:
  739. continue
  740. columns = list(result.keys())
  741. placeholders = ", ".join(["?"] * len(columns))
  742. col_list = ", ".join(columns)
  743. insert_sql = f"INSERT INTO {table.name} ({col_list}) VALUES ({placeholders})" # noqa: S608 # nosec B608 — table/column names from ORM metadata, not user input
  744. def _serialize_row(row):
  745. return tuple(json.dumps(v) if isinstance(v, (list, dict)) else v for v in row)
  746. dst.executemany(insert_sql, [_serialize_row(row) for row in rows])
  747. dst.commit()
  748. dst.close()
  749. logger.info("PostgreSQL backup exported to portable SQLite format")
  750. # Copy data directories (if they exist)
  751. dirs_to_backup = [
  752. ("archive", base_dir / "archive"),
  753. ("virtual_printer", base_dir / "virtual_printer"),
  754. ("plate_calibration", app_settings.plate_calibration_dir),
  755. ("icons", base_dir / "icons"),
  756. ("projects", base_dir / "projects"),
  757. ("overlay-branding", base_dir / "overlay-branding"),
  758. ]
  759. for name, src_dir in dirs_to_backup:
  760. if src_dir.exists() and any(src_dir.iterdir()):
  761. try:
  762. shutil.copytree(
  763. src_dir, temp_path / name
  764. ) # SEC-PATH-OK: name iterates the dirs_to_backup tuple of constant strings ("archive", "virtual_printer", ...)
  765. except shutil.Error as e:
  766. logger.warning("Some files in %s could not be copied: %s", name, e)
  767. except PermissionError as e:
  768. logger.warning("Permission denied copying %s: %s", name, e)
  769. # Say which version made this, so a restore that cannot import it can
  770. # name the versions rather than a list of columns. Backups from before
  771. # this existed simply have no manifest, and restore treats the version
  772. # as unknown.
  773. import json as _json
  774. manifest = {
  775. "format": 1,
  776. "app_version": APP_VERSION,
  777. "created_at": datetime.now().isoformat(timespec="seconds"),
  778. "database": "sqlite" if is_sqlite() else "postgresql",
  779. }
  780. (temp_path / "manifest.json").write_text(_json.dumps(manifest, indent=2) + "\n")
  781. # Include the MFA encryption key as a ZIP top-level entry alongside
  782. # bambuddy.db. Without it, encrypted client_secret / TOTP secret rows
  783. # would be unrecoverable after restore on a host without MFA_ENCRYPTION_KEY set.
  784. from backend.app.core.paths import resolve_data_dir
  785. mfa_key_src = resolve_data_dir() / ".mfa_encryption_key"
  786. if mfa_key_src.exists() and mfa_key_src.is_file():
  787. try:
  788. shutil.copy2(mfa_key_src, temp_path / ".mfa_encryption_key")
  789. except OSError as exc:
  790. logger.error(
  791. "Could not include MFA encryption key in backup (%s). "
  792. "The backup ZIP will not contain the key — restore on a "
  793. "keyless host will fail for encrypted secrets.",
  794. exc,
  795. )
  796. raise
  797. # Create ZIP
  798. if output_path is not None:
  799. zip_file = (
  800. output_path / filename
  801. ) # SEC-PATH-OK: filename = f"bambuddy-backup-{datetime.now()...}.zip" generated in create_backup_zip itself
  802. else:
  803. fd, tmp = tempfile.mkstemp(suffix=".zip")
  804. os.close(fd)
  805. zip_file = Path(tmp)
  806. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  807. for file_path in temp_path.rglob("*"):
  808. if file_path.is_file():
  809. arcname = file_path.relative_to(temp_path)
  810. zf.write(file_path, arcname)
  811. return zip_file, filename
  812. @router.get("/backup")
  813. async def create_backup(
  814. db: AsyncSession = Depends(get_db),
  815. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  816. ):
  817. """Create a complete backup (database + all files) as a ZIP download."""
  818. from starlette.background import BackgroundTask
  819. try:
  820. zip_file, filename = await create_backup_zip()
  821. return FileResponse(
  822. path=zip_file,
  823. filename=filename,
  824. media_type="application/zip",
  825. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  826. )
  827. except Exception as e:
  828. logger.error("Backup failed: %s", e, exc_info=True)
  829. return JSONResponse(
  830. status_code=500,
  831. content={"success": False, "message": "Backup failed. Check server logs for details."},
  832. )
  833. class BackupSchemaIncompatible(Exception):
  834. """The backup has no value for a column this version requires.
  835. A backup carries the schema of the install that made it. Restoring it into
  836. a different version means the destination can have NOT NULL columns the
  837. backup never heard of -- either because that version is older and still has
  838. a column since removed (``user_wallets.currency``, dropped in #3123), or
  839. because it is newer and has added one. Most such columns have a default and
  840. can simply be filled. The ones that cannot are what this reports, and it has
  841. to be reported BEFORE the restore drops anything: the Postgres import wipes
  842. every table in the first transaction, so a failure halfway leaves the
  843. install with an empty schema and the previous data gone.
  844. """
  845. def _missing_required_columns(pg_table, src_columns: set[str]):
  846. """Split the destination's NOT NULL columns that the backup lacks.
  847. Returns ``(injectable, db_filled, unfillable)``:
  848. * ``injectable`` -- ``{name: value}`` from the model's Python-side default.
  849. These are invisible to the import's raw SQL: SQLAlchemy applies a
  850. ``default=`` on ORM and Core inserts, never on ``text()``, and
  851. ``create_all`` emits no DDL default for one. So a column like
  852. ``currency VARCHAR(3) NOT NULL`` with ``default="EUR"`` arrives with
  853. nothing to put in it unless we put it there.
  854. * ``db_filled`` -- has a server default or is the autoincrement key; the
  855. database fills it when the column is left out of the INSERT.
  856. * ``unfillable`` -- nothing can supply a value. The backup is incompatible.
  857. """
  858. injectable: dict = {}
  859. db_filled: list[str] = []
  860. unfillable: list[str] = []
  861. for col in pg_table.columns:
  862. if col.nullable or col.name in src_columns:
  863. continue
  864. if col.default is not None:
  865. arg = col.default.arg
  866. injectable[col.name] = arg(None) if callable(arg) else arg
  867. elif col.server_default is not None or col.primary_key:
  868. db_filled.append(col.name)
  869. else:
  870. unfillable.append(col.name)
  871. return injectable, db_filled, unfillable
  872. def check_backup_schema_compatible(sqlite_path: Path, backup_version: str | None = None) -> None:
  873. """Raise if this version cannot import that backup. Touches nothing.
  874. Only the cross-engine path needs this. A SQLite install restores by copying
  875. the backup's pages, schema included, and `init_db()` migrates it forward
  876. afterwards; the Postgres import instead recreates the schema from THIS
  877. process's ORM and then inserts the backup's columns into it.
  878. """
  879. import sqlite3
  880. from backend.app.core.database import Base
  881. src = sqlite3.connect(f"file:{sqlite_path}?mode=ro", uri=True)
  882. try:
  883. src_tables = {
  884. row[0]
  885. for row in src.execute(
  886. "SELECT name FROM sqlite_master WHERE type='table' "
  887. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  888. )
  889. }
  890. problems: list[str] = []
  891. # metadata.tables, not sorted_tables: the latter warns about the
  892. # library_files/library_folders/print_archives cycle, and nothing here
  893. # depends on the order.
  894. for name, pg_table in Base.metadata.tables.items():
  895. if name not in src_tables:
  896. continue
  897. # An empty table inserts nothing, so a column it cannot supply
  898. # cannot fail. Refusing a restore over one would be a false alarm.
  899. if src.execute(f'SELECT 1 FROM "{name}" LIMIT 1').fetchone() is None: # noqa: S608 # nosec B608 — name comes from ORM metadata
  900. continue
  901. src_columns = {row[1] for row in src.execute(f'PRAGMA table_info("{name}")')}
  902. _, _, unfillable = _missing_required_columns(pg_table, src_columns)
  903. problems.extend(f"{name}.{col}" for col in unfillable)
  904. finally:
  905. src.close()
  906. if not problems:
  907. return
  908. made_by = f"The backup was made by Bambuddy {backup_version}, " if backup_version else "The backup "
  909. raise BackupSchemaIncompatible(
  910. "This backup cannot be restored by this version of Bambuddy. It carries no value for "
  911. f"{len(problems)} column(s) this version requires and cannot default: {', '.join(sorted(problems))}. "
  912. f"{made_by}and this install runs {APP_VERSION}. Restore it on the version that made it, or "
  913. "upgrade this install to that version. Nothing has been changed."
  914. )
  915. def _read_backup_manifest(temp_path: Path) -> dict:
  916. """The backup's manifest.json, or {} for a backup made before it existed."""
  917. import json
  918. path = temp_path / "manifest.json"
  919. if not path.is_file():
  920. return {}
  921. try:
  922. data = json.loads(path.read_text())
  923. except (OSError, ValueError) as exc:
  924. logger.warning("Ignoring unreadable backup manifest: %s", exc)
  925. return {}
  926. return data if isinstance(data, dict) else {}
  927. def _restored_value_fixes(table_name: str) -> dict[str, tuple[tuple[str, ...], str]]:
  928. """Columns of ``table_name`` whose backed-up value must be one of a set, with its fallback.
  929. Older versions stored any project priority or status; one longer than the
  930. column fails the whole import on PostgreSQL. The fallbacks are the ones
  931. project import and the start-up repair use.
  932. """
  933. if table_name != "projects":
  934. return {}
  935. from backend.app.models.project import PROJECT_PRIORITIES, PROJECT_STATUSES
  936. return {"priority": (PROJECT_PRIORITIES, "normal"), "status": (PROJECT_STATUSES, "active")}
  937. async def _import_sqlite_to_postgres(sqlite_path: Path):
  938. """Import data from a SQLite database file into the current PostgreSQL database.
  939. Used for cross-database restore (SQLite backup → PostgreSQL).
  940. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  941. """
  942. import sqlite3
  943. from sqlalchemy import text
  944. from backend.app.core.database import AUTOINCREMENT_TABLES, Base, _create_engine, highest_referenced_id
  945. # Before anything is dropped. The route checks this too, earlier and with
  946. # the backup's version in the message; this call is what makes the guarantee
  947. # a property of the import itself rather than of one caller.
  948. check_backup_schema_compatible(sqlite_path)
  949. # Create a temporary engine for the import (current engine was disposed)
  950. pg_engine = _create_engine()
  951. try:
  952. # Open SQLite file directly (sync — it's a local file read)
  953. src = sqlite3.connect(str(sqlite_path))
  954. src.row_factory = sqlite3.Row
  955. # Get list of tables from SQLite (skip internal/FTS tables)
  956. cursor = src.execute(
  957. "SELECT name FROM sqlite_master WHERE type='table' "
  958. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  959. )
  960. src_tables = {row["name"] for row in cursor.fetchall()}
  961. # Where SQLite's own counters stand: ids freed there are not given out
  962. # again on PostgreSQL either (a backup from before they were kept has none).
  963. src_counters: dict[str, int] = {}
  964. if src.execute("SELECT 1 FROM sqlite_master WHERE name = 'sqlite_sequence'").fetchone():
  965. src_counters = {row["name"]: row["seq"] for row in src.execute("SELECT name, seq FROM sqlite_sequence")}
  966. # Get Postgres tables from our ORM models
  967. metadata = Base.metadata
  968. pg_tables = set(metadata.tables.keys())
  969. # Only import tables that exist in both source and destination
  970. tables_to_import = src_tables & pg_tables
  971. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  972. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  973. # This avoids all FK ordering/orphan issues during import; the
  974. # constraints go back on at the end, once every row has landed.
  975. async with pg_engine.begin() as conn:
  976. # Cap how long DROP TABLE will wait for AccessExclusiveLock so
  977. # any residual concurrent writer (per-printer MQTT clients
  978. # writing reactively, an AMS history recorder firing on its
  979. # hourly cadence) surfaces a fast `lock_timeout` error instead
  980. # of blocking the restore for 30 s or producing a deadlock.
  981. # SET LOCAL scopes to this transaction only; outside this
  982. # restore path the global default (no timeout) applies.
  983. await conn.execute(text("SET LOCAL lock_timeout = '10s'"))
  984. # Drop every existing table in the public schema with CASCADE
  985. # rather than `metadata.drop_all`. Two reasons:
  986. # 1. The user's live DB may carry orphan tables from removed
  987. # features (e.g. the legacy `spoolman_slot_assignments`,
  988. # `spoolman_k_profile`) that hold FK constraints back to
  989. # ORM tables. `drop_all` doesn't know they exist and emits
  990. # `DROP TABLE printers` without CASCADE — Postgres refuses
  991. # and the whole restore aborts (#XXXX).
  992. # 2. Even within the metadata, `drop_all` is FK-ordered and
  993. # breaks if a future schema rename leaves old constraints
  994. # around. CASCADE is the right tool for a destructive
  995. # restore: the user is intentionally wiping state.
  996. await conn.execute(
  997. text(
  998. "DO $$ DECLARE r RECORD; BEGIN "
  999. "FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP "
  1000. "EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE'; "
  1001. "END LOOP; END $$;"
  1002. )
  1003. )
  1004. await conn.run_sync(metadata.create_all)
  1005. # Now strip the foreign keys, at the database level.
  1006. #
  1007. # This used to be done by discarding each ForeignKeyConstraint
  1008. # from `table.constraints` before `create_all`. That only
  1009. # suppresses the inline REFERENCES clause inside CREATE TABLE:
  1010. # `Table.foreign_key_constraints` is derived from the *columns'*
  1011. # ForeignKey objects, which the discard never touched. When
  1012. # `create_all` meets a dependency cycle it can't sort -- and
  1013. # library_files / library_folders / print_archives are exactly
  1014. # such a cycle -- it falls back to emitting those tables' keys
  1015. # as separate ALTER TABLE ... ADD FOREIGN KEY statements read
  1016. # straight from that property. Twelve constraints survived,
  1017. # including library_files.folder_id, and because the same cycle
  1018. # also drops the ordering edge from `sorted_tables` the child
  1019. # table was imported before its parent and the restore died on
  1020. # a ForeignKeyViolationError.
  1021. #
  1022. # Dropping them from pg_constraint instead is indifferent to how
  1023. # create_all chose to emit them, so a future model cycle cannot
  1024. # reintroduce this. It also keeps the app's global Base.metadata
  1025. # untouched: the old code only put the constraints back *after*
  1026. # the transaction, so a failure in here left the running process
  1027. # with an FK-less metadata until restart.
  1028. await conn.execute(
  1029. text(
  1030. "DO $$ DECLARE r RECORD; BEGIN "
  1031. "FOR r IN (SELECT conrelid::regclass AS tbl, conname FROM pg_constraint "
  1032. "WHERE contype = 'f' AND connamespace = 'public'::regnamespace) LOOP "
  1033. "EXECUTE 'ALTER TABLE ' || r.tbl || ' DROP CONSTRAINT ' || quote_ident(r.conname); "
  1034. "END LOOP; END $$;"
  1035. )
  1036. )
  1037. # Phase 2: Import data (no FKs to worry about)
  1038. async with pg_engine.begin() as conn:
  1039. # Import each table in dependency order (parents before children)
  1040. for table_name in sorted_tables:
  1041. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  1042. if not rows:
  1043. continue
  1044. # Filter to columns that exist in the Postgres table
  1045. src_columns = rows[0].keys()
  1046. pg_table = metadata.tables.get(table_name)
  1047. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  1048. columns = [c for c in src_columns if c in pg_columns]
  1049. if not columns:
  1050. continue
  1051. # Columns this schema requires that the backup does not have at
  1052. # all. The block below handles a column PRESENT in the backup
  1053. # with a NULL in it; one the backup never had is not in
  1054. # `columns` and so never reached it -- which is how a backup
  1055. # from an install without `user_wallets.currency` died on
  1056. # NotNullViolationError against a version that still had it.
  1057. injected, _db_filled, _unfillable = _missing_required_columns(pg_table, set(src_columns))
  1058. if injected:
  1059. logger.info(
  1060. "Filling %s column(s) absent from the backup in %s: %s",
  1061. len(injected),
  1062. table_name,
  1063. ", ".join(sorted(injected)),
  1064. )
  1065. insert_columns = columns + list(injected)
  1066. col_list = ", ".join(insert_columns)
  1067. param_list = ", ".join(f":{c}" for c in insert_columns)
  1068. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  1069. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  1070. # Identify columns that need type conversion (SQLite stores booleans
  1071. # as int and datetimes as str — asyncpg requires native Python types)
  1072. from datetime import datetime as dt
  1073. bool_columns = set()
  1074. datetime_columns = set()
  1075. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  1076. if pg_table is not None:
  1077. for col in pg_table.columns:
  1078. if col.name not in columns:
  1079. continue
  1080. col_type = str(col.type)
  1081. if col_type == "BOOLEAN":
  1082. bool_columns.add(col.name)
  1083. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  1084. datetime_columns.add(col.name)
  1085. # Track NOT NULL columns with defaults — older backups may have NULL
  1086. # for columns added after the backup was created
  1087. if not col.nullable:
  1088. if col.default is not None:
  1089. default = col.default.arg
  1090. if callable(default):
  1091. default = default(None)
  1092. not_null_defaults[col.name] = default
  1093. elif col.server_default is not None:
  1094. # server_default=func.now() → use current timestamp
  1095. if col.name in datetime_columns:
  1096. not_null_defaults[col.name] = "__now__"
  1097. else:
  1098. # Try to extract literal server default
  1099. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  1100. if sd is not None:
  1101. not_null_defaults[col.name] = sd
  1102. now = dt.now()
  1103. value_fixes = _restored_value_fixes(table_name)
  1104. def _convert_row(
  1105. row,
  1106. cols=columns,
  1107. bools=bool_columns,
  1108. dts=datetime_columns,
  1109. nn_defaults=not_null_defaults,
  1110. _now=now,
  1111. inject=injected,
  1112. fixes=value_fixes,
  1113. ):
  1114. result = dict(inject)
  1115. for c in cols:
  1116. val = row[c]
  1117. if val is None and c in nn_defaults:
  1118. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  1119. if val is not None:
  1120. if c in bools:
  1121. val = bool(val)
  1122. elif c in dts and isinstance(val, str):
  1123. try:
  1124. val = dt.fromisoformat(val)
  1125. except ValueError:
  1126. pass
  1127. result[c] = val
  1128. for c, (allowed, fallback) in fixes.items():
  1129. if c in result and result[c] not in allowed:
  1130. result[c] = fallback
  1131. return result
  1132. batch = [_convert_row(row) for row in rows]
  1133. await conn.execute(insert_sql, batch)
  1134. logger.info("Imported %d rows into %s", len(batch), table_name)
  1135. # Reset sequences to max(id) + 1 for each table with an id column;
  1136. # for AUTOINCREMENT_TABLES past SQLite's counter and every id still
  1137. # referred to, so a deleted row's id is not given to a new one.
  1138. for table_name in sorted_tables:
  1139. try:
  1140. async with conn.begin_nested():
  1141. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  1142. max_id = result.scalar()
  1143. if table_name in AUTOINCREMENT_TABLES:
  1144. max_id = max(
  1145. max_id or 0,
  1146. src_counters.get(table_name) or 0,
  1147. await highest_referenced_id(conn, table_name),
  1148. )
  1149. if max_id:
  1150. seq_name = f"{table_name}_id_seq"
  1151. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  1152. except Exception:
  1153. pass # Table may not have an id column or sequence
  1154. src.close()
  1155. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  1156. # Recreate FK constraints from ORM metadata, which Phase 1 left intact.
  1157. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  1158. from sqlalchemy.schema import AddConstraint
  1159. failed_fks = []
  1160. for table in metadata.sorted_tables:
  1161. for fk in table.foreign_key_constraints:
  1162. try:
  1163. async with pg_engine.begin() as fk_conn:
  1164. await fk_conn.execute(AddConstraint(fk))
  1165. except Exception as e:
  1166. # Name the constraint by what it links, not by `fk.name`:
  1167. # these are unnamed in the ORM, so that field is None and
  1168. # the warning used to read "print_archives.None" for every
  1169. # one of the five keys on that table -- unusable for
  1170. # working out which rows to go and look at.
  1171. cols = ", ".join(c.name for c in fk.columns)
  1172. target = fk.elements[0].target_fullname if fk.elements else "unknown"
  1173. failed_fks.append(f"{table.name}({cols}) -> {target}")
  1174. # Postgres puts the offending key in a DETAIL line; it
  1175. # names the exact orphan value, which is the one thing
  1176. # that turns this into an actionable report.
  1177. detail = next(
  1178. (ln.strip() for ln in str(e).splitlines() if ln.startswith("DETAIL:")),
  1179. str(e).splitlines()[0] if str(e) else e.__class__.__name__,
  1180. )
  1181. logger.info("FK %s(%s) -> %s not restored: %s", table.name, cols, target, detail)
  1182. if failed_fks:
  1183. logger.warning(
  1184. "Could not restore %d FK constraints (orphaned data in the backup): %s. "
  1185. "The data is restored and usable; those columns are simply no longer "
  1186. "enforced. See the INFO lines above for the offending key in each case.",
  1187. len(failed_fks),
  1188. ", ".join(failed_fks),
  1189. )
  1190. finally:
  1191. await pg_engine.dispose()
  1192. @router.post("/restore")
  1193. async def restore_backup(
  1194. file: UploadFile = File(...),
  1195. db: AsyncSession = Depends(get_db),
  1196. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  1197. ):
  1198. """Restore from a complete backup ZIP.
  1199. Replaces the database and all data directories from the backup ZIP.
  1200. Requires a restart after restore.
  1201. """
  1202. import shutil
  1203. import tempfile
  1204. from fastapi import HTTPException
  1205. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  1206. from backend.app.core.db_dialect import is_sqlite
  1207. from backend.app.services.virtual_printer import virtual_printer_manager
  1208. base_dir = app_settings.base_dir
  1209. with tempfile.TemporaryDirectory() as temp_dir:
  1210. temp_path = Path(temp_dir)
  1211. # 1. Read and extract ZIP
  1212. content = await file.read()
  1213. # Check if it's a valid ZIP
  1214. if not file.filename or not file.filename.endswith(".zip"):
  1215. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  1216. try:
  1217. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  1218. for name in zf.namelist():
  1219. # Reject path-traversal payloads: any entry whose resolved
  1220. # path escapes temp_path would allow writing arbitrary files
  1221. # on the host (ZipSlip / CVE-2006-5456).
  1222. dest = (
  1223. temp_path / name
  1224. ).resolve() # SEC-PATH-OK: is_relative_to containment check below before extractall
  1225. # is_relative_to (Python 3.9+) covers both relative
  1226. # path-traversal (../etc/passwd) and absolute-path overrides
  1227. # (/etc/passwd) — str.startswith was vulnerable to
  1228. # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
  1229. # a /tmp/abc prefix check).
  1230. if not dest.is_relative_to(temp_path.resolve()):
  1231. raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
  1232. zf.extractall(temp_path)
  1233. except zipfile.BadZipFile:
  1234. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  1235. # 2. Validate backup
  1236. backup_db = temp_path / "bambuddy.db"
  1237. if not backup_db.exists():
  1238. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  1239. # 2b. Can this version import this backup at all?
  1240. #
  1241. # Deliberately here: everything below has a side effect. The virtual
  1242. # printer stops, background services stop, the MFA key file is
  1243. # overwritten with the backup's -- and then the Postgres import drops
  1244. # every table in its first transaction. A backup rejected at the INSERT
  1245. # took the install's data with it and left the encrypted secrets under a
  1246. # key that no longer matches. Nothing above this line has touched
  1247. # anything.
  1248. import sqlite3
  1249. manifest = _read_backup_manifest(temp_path)
  1250. backup_version = manifest.get("app_version")
  1251. if backup_version:
  1252. logger.info("Backup was created by Bambuddy %s; this install runs %s", backup_version, APP_VERSION)
  1253. if not is_sqlite():
  1254. try:
  1255. check_backup_schema_compatible(backup_db, backup_version)
  1256. except BackupSchemaIncompatible as exc:
  1257. logger.error("Refusing backup: %s", exc)
  1258. raise HTTPException(400, str(exc)) from exc
  1259. except sqlite3.DatabaseError as exc:
  1260. raise HTTPException(400, f"Invalid backup: bambuddy.db is not readable ({exc})") from exc
  1261. try:
  1262. import asyncio
  1263. # 3. Stop virtual printer if running (releases file locks)
  1264. try:
  1265. if virtual_printer_manager.is_enabled:
  1266. logger.info("Stopping virtual printer for restore...")
  1267. await virtual_printer_manager.configure(enabled=False)
  1268. await asyncio.sleep(1)
  1269. except Exception as e:
  1270. logger.warning("Failed to stop virtual printer: %s", e)
  1271. # 3b. Pause timer-based background services BEFORE the DB swap.
  1272. # close_all_connections() below only disposes the engine's pool,
  1273. # not the asyncio tasks that opened sessions from it. The print
  1274. # scheduler (30 s cadence), smart-plug snapshot loop (30 s), and
  1275. # notification digest loop all
  1276. # wake up and call async_session(), which lazily re-creates a
  1277. # pool connection holding RowExclusiveLock on print_queue /
  1278. # smart_plug_energy_snapshots / etc. The DROP TABLE CASCADE
  1279. # pass in the PostgreSQL restore path needs AccessExclusiveLock
  1280. # on every public table, producing an AB/BA deadlock and a
  1281. # full restore rollback. Successful restore already requires a
  1282. # container restart, so we don't restart the services here.
  1283. try:
  1284. from backend.app.services.notification_service import notification_service
  1285. from backend.app.services.print_scheduler import scheduler as print_scheduler
  1286. from backend.app.services.smart_plug_manager import smart_plug_manager
  1287. logger.info("Pausing background services for restore...")
  1288. print_scheduler.stop()
  1289. smart_plug_manager.stop_scheduler()
  1290. notification_service.stop_digest_scheduler()
  1291. # In-flight loop iterations need a moment to commit + release
  1292. # their DB sessions before we dispose() the engine pool.
  1293. await asyncio.sleep(1.0)
  1294. except Exception as e:
  1295. logger.warning("Could not cleanly pause background services: %s", e)
  1296. # 4. Close current database connections
  1297. logger.info("Closing database connections...")
  1298. await close_all_connections()
  1299. # B1: Restore the MFA encryption key file BEFORE the database swap.
  1300. # If the key write fails (OSError, RO disk, full disk, EACCES) we
  1301. # can still abort while the live DB is intact. Doing this AFTER the
  1302. # DB swap would leave the database with rows encrypted under the
  1303. # backup's key but the running install holding only the old key —
  1304. # every encrypted secret becomes unrecoverable.
  1305. from backend.app.core.paths import resolve_data_dir
  1306. mfa_key_src = temp_path / ".mfa_encryption_key"
  1307. if mfa_key_src.exists() and mfa_key_src.is_file():
  1308. dst_key = resolve_data_dir() / ".mfa_encryption_key"
  1309. tmp_key = dst_key.parent / ".mfa_encryption_key.restore-tmp"
  1310. try:
  1311. dst_key.parent.mkdir(parents=True, exist_ok=True)
  1312. # S1: atomic write with restrictive mode from creation.
  1313. # O_TRUNC because a stale tmp may exist from a prior
  1314. # failed restore attempt — we want to overwrite it.
  1315. fd = os.open(str(tmp_key), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
  1316. try:
  1317. os.write(fd, mfa_key_src.read_bytes())
  1318. finally:
  1319. os.close(fd)
  1320. # POSIX rename(2) — atomic when source/dest are on the
  1321. # same filesystem (we're staying inside dst_key.parent).
  1322. os.replace(str(tmp_key), str(dst_key))
  1323. # S9: warn if the FS doesn't enforce 0o600
  1324. actual_mode = dst_key.stat().st_mode & 0o777
  1325. if actual_mode != 0o600:
  1326. logger.warning(
  1327. "Restored MFA key file %s: filesystem did not enforce 0o600 "
  1328. "(actual: 0o%o). Key may be world-readable on Windows / SMB / FUSE.",
  1329. dst_key,
  1330. actual_mode,
  1331. )
  1332. logger.info("Restored .mfa_encryption_key from backup")
  1333. except OSError as e:
  1334. logger.error(
  1335. "Could not write restored MFA key file to %s: %s — "
  1336. "aborting BEFORE database swap (DB unchanged).",
  1337. dst_key,
  1338. e,
  1339. exc_info=True,
  1340. )
  1341. raise HTTPException(
  1342. status_code=500,
  1343. detail=("Restore aborted: MFA key write failed. Database is unchanged. Check server logs."),
  1344. ) from e
  1345. # 5. Replace database
  1346. logger.info("Restoring database from backup...")
  1347. if is_sqlite():
  1348. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  1349. # Use SQLite's online backup API instead of shutil.copy2.
  1350. # The pragma at database.py:19 runs the live DB in WAL mode,
  1351. # which means a naive file copy is unsafe: anything written
  1352. # to the live DB before this call that hasn't been
  1353. # checkpointed yet (seed_default_groups + init_db on first
  1354. # start, plus whatever background heartbeats wrote during
  1355. # the request window) sits in bambuddy.db-wal with valid
  1356. # checksums. The route handler's own `db: Depends(get_db)`
  1357. # session also keeps a connection checked out across
  1358. # engine.dispose(), holding fds to the WAL inode. With
  1359. # `shutil.copy2` SQLite finds the stale WAL on the next
  1360. # open and silently re-applies those page-level writes on
  1361. # top of the restored DB, partially clobbering it with
  1362. # fresh-install state — the user sees a "successful"
  1363. # restore where most rows and settings have reverted to
  1364. # defaults (#1211 / #668). The page-by-page backup API
  1365. # opens both DBs as real SQLite connections, takes the
  1366. # right locks, and routes new pages through the live DB's
  1367. # own WAL — so concurrent open sessions see their own
  1368. # snapshot until they close (transaction isolation) but
  1369. # can't corrupt the restored state.
  1370. import sqlite3
  1371. src_conn = sqlite3.connect(str(backup_db))
  1372. try:
  1373. dst_conn = sqlite3.connect(str(db_path))
  1374. try:
  1375. src_conn.backup(dst_conn)
  1376. finally:
  1377. dst_conn.close()
  1378. finally:
  1379. src_conn.close()
  1380. else:
  1381. # Import SQLite backup into PostgreSQL
  1382. logger.info("Importing SQLite backup into PostgreSQL...")
  1383. await _import_sqlite_to_postgres(backup_db)
  1384. # 6. Replace data directories
  1385. # For Docker compatibility: clear contents then copy (don't delete mount points)
  1386. dirs_to_restore = [
  1387. ("archive", base_dir / "archive"),
  1388. ("virtual_printer", base_dir / "virtual_printer"),
  1389. ("plate_calibration", app_settings.plate_calibration_dir),
  1390. ("icons", base_dir / "icons"),
  1391. ("projects", base_dir / "projects"),
  1392. ("overlay-branding", base_dir / "overlay-branding"),
  1393. ]
  1394. skipped_dirs = []
  1395. for name, dest_dir in dirs_to_restore:
  1396. src_dir = (
  1397. temp_path / name
  1398. ) # SEC-PATH-OK: name iterates the dirs_to_restore tuple of constant strings ("archive", "virtual_printer", ...)
  1399. if src_dir.exists():
  1400. logger.info("Restoring %s directory...", name)
  1401. try:
  1402. # Clear destination contents (not the dir itself - may be Docker mount)
  1403. if dest_dir.exists():
  1404. for item in dest_dir.iterdir():
  1405. try:
  1406. if item.is_dir():
  1407. shutil.rmtree(item)
  1408. else:
  1409. item.unlink()
  1410. except OSError as e:
  1411. logger.warning("Could not delete %s: %s", item, e)
  1412. else:
  1413. dest_dir.mkdir(parents=True, exist_ok=True)
  1414. # Copy contents from backup
  1415. for item in src_dir.iterdir():
  1416. dest_item = dest_dir / item.name
  1417. if item.is_dir():
  1418. shutil.copytree(item, dest_item)
  1419. else:
  1420. shutil.copy2(item, dest_item)
  1421. except OSError as e:
  1422. logger.warning("Could not restore %s directory: %s", name, e)
  1423. skipped_dirs.append(name)
  1424. # 7. Reset the encryption singleton so the migration that runs
  1425. # inside init_db() picks up the restored key file (if a new one
  1426. # was written above). Without this reset, _get_fernet would
  1427. # return the cached Fernet instance built from the previous key.
  1428. import backend.app.core.encryption as _enc_mod
  1429. _enc_mod._fernet_instance = None
  1430. _enc_mod._key_source = None
  1431. _enc_mod._warn_shown = False
  1432. # 8. Reinitialize the database engine and apply schema migrations so that
  1433. # tables added after the backup was created (e.g. ams_labels) exist
  1434. # immediately, without requiring a manual restart.
  1435. await reinitialize_database()
  1436. await init_db()
  1437. # 9. Sign everyone out. The restored users and auth tokens come from
  1438. # another point in time, possibly written by older code, so no
  1439. # session issued before the restore should stay valid.
  1440. from backend.app.core import database as _db_mod
  1441. async with _db_mod.engine.begin() as conn:
  1442. await _db_mod.invalidate_all_sessions(conn)
  1443. # Open dashboards of signed-in users too: they are never signed in
  1444. # again. API-key and anonymous ones are not closed outright (nothing
  1445. # ended theirs), but the restored data decides what they may still see: the anonymous ones
  1446. # go if the backup turns authentication on, and the refresh closes
  1447. # those of a key the backup does not have (or has under another key).
  1448. from backend.app.core.auth import invalidate_auth_enabled_cache
  1449. from backend.app.core.websocket import ws_manager
  1450. # Read from the restored data: this request has just cached the
  1451. # setting it had before.
  1452. invalidate_auth_enabled_cache()
  1453. # Cloud presets were cached per user of the replaced user table.
  1454. from backend.app.api.routes.cloud import forget_all_cloud_presets
  1455. forget_all_cloud_presets()
  1456. async with _db_mod.async_session() as auth_db:
  1457. auth_on = await is_auth_enabled(auth_db)
  1458. if auth_on:
  1459. await ws_manager.close_signed_in()
  1460. await ws_manager.close_anonymous()
  1461. await ws_manager.refresh_printer_scopes()
  1462. logger.info("Restore complete - restart required")
  1463. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  1464. if skipped_dirs:
  1465. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  1466. return {
  1467. "success": True,
  1468. "message": message,
  1469. }
  1470. except HTTPException:
  1471. # Preserve specific HTTP error responses raised inside the restore
  1472. # body (e.g. the key-write OSError → 500). The blanket
  1473. # except Exception below would otherwise swallow them and replace
  1474. # the operator-facing detail with a generic message.
  1475. raise
  1476. except Exception as e:
  1477. logger.error("Restore failed: %s", e, exc_info=True)
  1478. return JSONResponse(
  1479. status_code=500,
  1480. content={"success": False, "message": "Restore failed. Check server logs for details."},
  1481. )
  1482. @router.get("/network-interfaces")
  1483. async def get_network_interfaces(
  1484. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1485. ):
  1486. """Get available network interfaces with all IPs (primary + aliases)."""
  1487. from backend.app.services.network_utils import get_all_interface_ips
  1488. interfaces = get_all_interface_ips()
  1489. return {"interfaces": interfaces}
  1490. @router.get("/virtual-printer/models")
  1491. async def get_virtual_printer_models(
  1492. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1493. ):
  1494. """Get available virtual printer models."""
  1495. from backend.app.services.virtual_printer import (
  1496. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1497. VIRTUAL_PRINTER_MODELS,
  1498. )
  1499. return {
  1500. "models": VIRTUAL_PRINTER_MODELS,
  1501. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1502. }
  1503. def _legacy_vp_status(status: dict, printer_scope: PrinterScope) -> dict:
  1504. """The first virtual printer's status, without what names its target for a limited caller."""
  1505. if printer_scope.is_unrestricted:
  1506. return status
  1507. return {key: value for key, value in status.items() if key not in ("name", "serial", "target_printer_ip", "proxy")}
  1508. @router.get("/virtual-printer")
  1509. async def get_virtual_printer_settings(
  1510. db: AsyncSession = Depends(get_db),
  1511. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1512. printer_scope: PrinterScope = RequestPrinterScope,
  1513. ):
  1514. """Get virtual printer settings and status."""
  1515. from backend.app.services.virtual_printer import (
  1516. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1517. virtual_printer_manager,
  1518. )
  1519. enabled = await get_setting(db, "virtual_printer_enabled")
  1520. access_code = await get_setting(db, "virtual_printer_access_code")
  1521. mode = await get_setting(db, "virtual_printer_mode")
  1522. model = await get_setting(db, "virtual_printer_model")
  1523. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  1524. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  1525. tailscale_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  1526. archive_name_source = await get_setting(db, "virtual_printer_archive_name_source")
  1527. from backend.app.models.virtual_printer import VP_MODE_ARCHIVE, normalize_vp_mode
  1528. return {
  1529. "enabled": enabled == "true" if enabled else False,
  1530. "access_code_set": bool(access_code),
  1531. # Normalize on read so older settings rows (with `immediate` /
  1532. # `print_queue`) come out as `archive` / `queue` for the frontend.
  1533. "mode": normalize_vp_mode(mode) or VP_MODE_ARCHIVE,
  1534. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1535. # A target the caller can't see is not named.
  1536. "target_printer_id": int(target_printer_id)
  1537. if target_printer_id and printer_scope.allows(int(target_printer_id))
  1538. else None,
  1539. "remote_interface_ip": remote_interface_ip or "",
  1540. "tailscale_disabled": tailscale_disabled_raw == "true" if tailscale_disabled_raw else True,
  1541. "archive_name_source": archive_name_source if archive_name_source in ("metadata", "filename") else "metadata",
  1542. "status": _legacy_vp_status(virtual_printer_manager.get_status(), printer_scope),
  1543. }
  1544. @router.put("/virtual-printer")
  1545. async def update_virtual_printer_settings(
  1546. enabled: bool = None,
  1547. access_code: str = None,
  1548. mode: str = None,
  1549. model: str = None,
  1550. target_printer_id: int = None,
  1551. remote_interface_ip: str = None,
  1552. tailscale_disabled: bool = None,
  1553. archive_name_source: str = None,
  1554. db: AsyncSession = Depends(get_db),
  1555. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1556. printer_scope: PrinterScope = RequestPrinterScope,
  1557. ):
  1558. """Update virtual printer settings and restart services if needed.
  1559. For proxy mode with SSDP proxy (dual-homed setup):
  1560. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  1561. - Local interface is auto-detected based on target printer IP
  1562. """
  1563. from sqlalchemy import select
  1564. from backend.app.models.printer import Printer
  1565. from backend.app.services.virtual_printer import (
  1566. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1567. VIRTUAL_PRINTER_MODELS,
  1568. virtual_printer_manager,
  1569. )
  1570. # Get current values
  1571. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  1572. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1573. # Default to `archive` (the canonical name) but tolerate legacy `immediate`
  1574. # in the stored value — normalized later before validation.
  1575. current_mode = await get_setting(db, "virtual_printer_mode") or "archive"
  1576. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  1577. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  1578. current_target_id = int(current_target_id_str) if current_target_id_str else None
  1579. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  1580. current_ts_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  1581. # Default True (opt-in) when the setting has never been saved — matches the model default.
  1582. current_ts_disabled = current_ts_disabled_raw == "true" if current_ts_disabled_raw else True
  1583. # Apply updates
  1584. new_enabled = enabled if enabled is not None else current_enabled
  1585. new_access_code = access_code if access_code is not None else current_access_code
  1586. new_mode = mode if mode is not None else current_mode
  1587. new_model = model if model is not None else current_model
  1588. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  1589. # One bridging to a printer the caller can't use is not theirs to change,
  1590. # and they can't aim it at such a printer.
  1591. from backend.app.models.virtual_printer import VirtualPrinter as FirstVP
  1592. # The first virtual printer is the one these settings reach.
  1593. first_vp = (await db.execute(select(FirstVP).order_by(FirstVP.position, FirstVP.id).limit(1))).scalar_one_or_none()
  1594. if not printer_scope.allows(current_target_id) or (
  1595. first_vp is not None and not printer_scope.allows(first_vp.target_printer_id)
  1596. ):
  1597. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  1598. if target_printer_id is not None and not printer_scope.allows(target_printer_id):
  1599. return JSONResponse(status_code=400, content={"detail": f"Printer with ID {target_printer_id} not found"})
  1600. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  1601. new_ts_disabled = tailscale_disabled if tailscale_disabled is not None else current_ts_disabled
  1602. # Validate mode. Canonical wire values are `archive` / `review` / `queue`
  1603. # / `proxy`; legacy `immediate` and `print_queue` are accepted as aliases
  1604. # and translated before storage so support bundles stop showing the old
  1605. # confusing pair (#1429 mode-label discrepancy).
  1606. from backend.app.models.virtual_printer import VP_MODE_VALUES, normalize_vp_mode
  1607. canonical_mode = normalize_vp_mode(new_mode)
  1608. if canonical_mode not in VP_MODE_VALUES:
  1609. return JSONResponse(
  1610. status_code=400,
  1611. content={
  1612. "detail": f"Mode must be one of: {', '.join(VP_MODE_VALUES)}",
  1613. },
  1614. )
  1615. new_mode = canonical_mode
  1616. # Validate archive_name_source
  1617. if archive_name_source is not None and archive_name_source not in ("metadata", "filename"):
  1618. return JSONResponse(
  1619. status_code=400,
  1620. content={"detail": "archive_name_source must be 'metadata' or 'filename'"},
  1621. )
  1622. # Validate model
  1623. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  1624. return JSONResponse(
  1625. status_code=400,
  1626. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  1627. )
  1628. # Mode-specific validation and printer lookup
  1629. target_printer_ip = ""
  1630. target_printer_serial = ""
  1631. if new_mode == "proxy":
  1632. # Proxy mode requires target printer when enabling
  1633. if new_enabled and not new_target_id:
  1634. # If just switching to proxy mode (not explicitly enabling), auto-disable
  1635. if enabled is None:
  1636. new_enabled = False
  1637. else:
  1638. return JSONResponse(
  1639. status_code=400,
  1640. content={"detail": "Target printer is required for proxy mode"},
  1641. )
  1642. # Look up printer IP and serial if we have a target
  1643. if new_target_id:
  1644. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  1645. printer = result.scalar_one_or_none()
  1646. if not printer:
  1647. return JSONResponse(
  1648. status_code=400,
  1649. content={"detail": f"Printer with ID {new_target_id} not found"},
  1650. )
  1651. target_printer_ip = printer.ip_address
  1652. target_printer_serial = printer.serial_number
  1653. # Access code not required for proxy mode
  1654. else:
  1655. # Non-proxy modes require access code when enabling
  1656. if new_enabled and not new_access_code:
  1657. # If just switching modes (not explicitly enabling), auto-disable
  1658. if enabled is None:
  1659. new_enabled = False
  1660. else:
  1661. return JSONResponse(
  1662. status_code=400,
  1663. content={"detail": "Access code is required when enabling virtual printer"},
  1664. )
  1665. # Validate access code length (Bambu Studio requires exactly 8 characters)
  1666. if access_code is not None and access_code and len(access_code) != 8:
  1667. return JSONResponse(
  1668. status_code=400,
  1669. content={"detail": "Access code must be exactly 8 characters"},
  1670. )
  1671. # Save settings
  1672. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  1673. if access_code is not None:
  1674. await set_setting(db, "virtual_printer_access_code", access_code)
  1675. await set_setting(db, "virtual_printer_mode", new_mode)
  1676. if model is not None:
  1677. await set_setting(db, "virtual_printer_model", model)
  1678. if target_printer_id is not None:
  1679. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  1680. if remote_interface_ip is not None:
  1681. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  1682. if tailscale_disabled is not None:
  1683. await set_setting(db, "virtual_printer_tailscale_disabled", "true" if tailscale_disabled else "false")
  1684. if archive_name_source is not None:
  1685. await set_setting(db, "virtual_printer_archive_name_source", archive_name_source)
  1686. # Propagate tailscale_disabled to the first VirtualPrinter row so sync_from_db() picks it up
  1687. if tailscale_disabled is not None:
  1688. if first_vp is not None:
  1689. first_vp.tailscale_disabled = new_ts_disabled
  1690. await db.commit()
  1691. db.expire_all()
  1692. # Reconfigure virtual printer
  1693. try:
  1694. await virtual_printer_manager.configure(
  1695. enabled=new_enabled,
  1696. access_code=new_access_code,
  1697. mode=new_mode,
  1698. model=new_model,
  1699. target_printer_ip=target_printer_ip,
  1700. target_printer_serial=target_printer_serial,
  1701. remote_interface_ip=new_remote_iface,
  1702. )
  1703. except ValueError as e:
  1704. logger.warning("Virtual printer configuration validation error: %s", e)
  1705. return JSONResponse(
  1706. status_code=400,
  1707. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  1708. )
  1709. except Exception as e:
  1710. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  1711. return JSONResponse(
  1712. status_code=500,
  1713. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  1714. )
  1715. return await get_virtual_printer_settings(db, printer_scope=printer_scope)
  1716. # =============================================================================
  1717. # MQTT Relay Settings
  1718. # =============================================================================
  1719. @router.get("/mqtt/status")
  1720. async def get_mqtt_status(
  1721. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1722. ):
  1723. """Get MQTT relay connection status."""
  1724. from backend.app.services.mqtt_relay import mqtt_relay
  1725. return mqtt_relay.get_status()