settings.py 87 KB

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