settings.py 88 KB

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