settings.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. import io
  2. import logging
  3. import os
  4. import zipfile
  5. from datetime import datetime
  6. from pathlib import Path
  7. from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
  8. from fastapi.responses import FileResponse, JSONResponse
  9. from pydantic import BaseModel, Field
  10. from sqlalchemy import delete, func, select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.auth import RequirePermissionIfAuthEnabled, caller_is_api_key, require_energy_cost_update
  13. from backend.app.core.config import settings as app_settings
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.models.settings import Settings
  17. from backend.app.models.user import User
  18. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  19. logger = logging.getLogger(__name__)
  20. router = APIRouter(prefix="/settings", tags=["settings"])
  21. DEFAULT_SETTINGS = AppSettings()
  22. # Sensitive credential fields blanked for API-key callers
  23. _SENSITIVE_FIELDS_FOR_API_KEY = (
  24. "mqtt_password",
  25. "ha_token",
  26. "prometheus_token",
  27. "virtual_printer_access_code",
  28. "ldap_bind_password",
  29. )
  30. async def get_setting(db: AsyncSession, key: str) -> str | None:
  31. """Get a single setting value by key."""
  32. result = await db.execute(select(Settings).where(Settings.key == key))
  33. setting = result.scalar_one_or_none()
  34. return setting.value if setting else None
  35. async def get_external_login_url(db: AsyncSession) -> str:
  36. """Get the external URL for the login page.
  37. Uses external_url from settings if available, otherwise falls back to APP_URL env var.
  38. Args:
  39. db: Database session
  40. Returns:
  41. Full URL to the login page
  42. """
  43. import os
  44. external_url = await get_setting(db, "external_url")
  45. if external_url:
  46. external_url = external_url.rstrip("/")
  47. else:
  48. external_url = os.environ.get("APP_URL", "http://localhost:5173")
  49. return external_url + "/login"
  50. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  51. """Set a single setting value."""
  52. from backend.app.core.db_dialect import upsert_setting
  53. await upsert_setting(db, Settings, key, value)
  54. async def _build_settings_response(db: AsyncSession, is_api_key: bool = False) -> AppSettings:
  55. """Build the full settings response, scrubbing secrets for API-key callers."""
  56. settings_dict = DEFAULT_SETTINGS.model_dump()
  57. result = await db.execute(select(Settings))
  58. for setting in result.scalars().all():
  59. if setting.key not in settings_dict:
  60. continue
  61. if setting.key in [
  62. "auto_archive",
  63. "save_thumbnails",
  64. "capture_finish_photo",
  65. "spoolman_enabled",
  66. "spoolman_disable_weight_sync",
  67. "spoolman_report_partial_usage",
  68. "auto_add_unknown_rfid",
  69. "disable_filament_warnings",
  70. "prefer_lowest_filament",
  71. "check_updates",
  72. "check_printer_firmware",
  73. "include_beta_updates",
  74. "virtual_printer_enabled",
  75. "ftp_retry_enabled",
  76. "mqtt_enabled",
  77. "mqtt_use_tls",
  78. "ha_enabled",
  79. "per_printer_mapping_expanded",
  80. "prometheus_enabled",
  81. "user_notifications_enabled",
  82. "queue_drying_enabled",
  83. "queue_drying_block",
  84. "ambient_drying_enabled",
  85. "print_drying_enabled",
  86. "require_plate_clear",
  87. "queue_shortest_first",
  88. "default_bed_levelling",
  89. "default_flow_cali",
  90. "default_vibration_cali",
  91. "default_layer_inspect",
  92. "default_timelapse",
  93. "default_nozzle_offset_cali",
  94. "ldap_enabled",
  95. "ldap_auto_provision",
  96. "local_login_enabled",
  97. "preheat_enabled",
  98. ]:
  99. settings_dict[setting.key] = setting.value.lower() == "true"
  100. elif setting.key in [
  101. "default_filament_cost",
  102. "energy_cost_per_kwh",
  103. "ams_temp_good",
  104. "ams_temp_fair",
  105. "library_disk_warning_gb",
  106. "low_stock_threshold",
  107. ]:
  108. settings_dict[setting.key] = float(setting.value)
  109. elif setting.key in [
  110. "ams_humidity_good",
  111. "ams_humidity_fair",
  112. "ams_history_retention_days",
  113. "printer_sensor_history_retention_days",
  114. "ftp_retry_count",
  115. "ftp_retry_delay",
  116. "ftp_timeout",
  117. "mqtt_port",
  118. "stagger_group_size",
  119. "stagger_interval_minutes",
  120. "forecast_global_lead_time_days",
  121. "session_max_hours",
  122. "pipeline_max_copies",
  123. "preheat_max_wait_seconds",
  124. "preheat_soak_seconds",
  125. "queue_max_concurrent_uploads",
  126. ]:
  127. settings_dict[setting.key] = int(setting.value)
  128. elif setting.key == "default_printer_id":
  129. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  130. elif setting.key == "open_in_slicer":
  131. # None means "inherit from preferred_slicer" (#1329). The PUT path
  132. # serializes None as the literal string "None"; strip it back so
  133. # the frontend sees a true null and falls back as intended.
  134. settings_dict[setting.key] = setting.value if setting.value and setting.value != "None" else None
  135. else:
  136. settings_dict[setting.key] = setting.value
  137. ha_settings = await get_homeassistant_settings(db)
  138. settings_dict.update(ha_settings)
  139. # ldap_bind_password is never returned to any caller
  140. settings_dict["ldap_bind_password"] = ""
  141. if is_api_key:
  142. for field in _SENSITIVE_FIELDS_FOR_API_KEY:
  143. if field in settings_dict:
  144. settings_dict[field] = ""
  145. return AppSettings(**settings_dict)
  146. @router.get("", response_model=AppSettings)
  147. @router.get("/", response_model=AppSettings)
  148. async def get_settings(
  149. db: AsyncSession = Depends(get_db),
  150. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  151. _is_api_key: bool = Depends(caller_is_api_key),
  152. ):
  153. """Get all application settings."""
  154. return await _build_settings_response(db, is_api_key=_is_api_key)
  155. @router.put("/", response_model=AppSettings)
  156. async def update_settings(
  157. settings_update: AppSettingsUpdate,
  158. db: AsyncSession = Depends(get_db),
  159. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  160. ):
  161. """Update application settings."""
  162. update_data = settings_update.model_dump(exclude_unset=True)
  163. # Safety refusals on disabling local login (#1589). Two failure modes
  164. # would otherwise lock everyone out of the install:
  165. # 1. No enabled OIDC provider exists — nobody could authenticate.
  166. # 2. The caller has no UserOIDCLink — they would lock themselves out
  167. # even if other admins are linked.
  168. # Either case returns HTTP 400 instead of silently saving. The
  169. # ``BAMBUDDY_LOCAL_LOGIN=true`` env-var bypass on /auth/login is a
  170. # separate recovery path; the refusals here protect the *default*
  171. # configuration where the env var is absent.
  172. if update_data.get("local_login_enabled") is False:
  173. from backend.app.models.oidc_provider import OIDCProvider, UserOIDCLink
  174. enabled_count = await db.scalar(select(func.count(OIDCProvider.id)).where(OIDCProvider.is_enabled.is_(True)))
  175. if not enabled_count:
  176. raise HTTPException(
  177. status_code=400,
  178. detail="Cannot disable local login: no OIDC provider is enabled.",
  179. )
  180. if current_user is not None:
  181. caller_links = await db.scalar(
  182. select(func.count(UserOIDCLink.id)).where(UserOIDCLink.user_id == current_user.id)
  183. )
  184. if not caller_links:
  185. raise HTTPException(
  186. status_code=400,
  187. detail="Cannot disable local login: your account has no OIDC link, so you would lock yourself out.",
  188. )
  189. # Check if any MQTT settings are being updated
  190. mqtt_keys = {
  191. "mqtt_enabled",
  192. "mqtt_broker",
  193. "mqtt_port",
  194. "mqtt_username",
  195. "mqtt_password",
  196. "mqtt_topic_prefix",
  197. "mqtt_use_tls",
  198. }
  199. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  200. for key, value in update_data.items():
  201. # Convert value to string for storage
  202. if isinstance(value, bool):
  203. str_value = "true" if value else "false"
  204. elif value is None:
  205. str_value = "None"
  206. else:
  207. str_value = str(value)
  208. await set_setting(db, key, str_value)
  209. await db.commit()
  210. # Expire all objects to ensure fresh reads after commit
  211. db.expire_all()
  212. # Reconfigure MQTT relay if any MQTT settings changed
  213. if mqtt_updated:
  214. try:
  215. from backend.app.services.mqtt_relay import mqtt_relay
  216. mqtt_settings = {
  217. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  218. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  219. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  220. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  221. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  222. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  223. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  224. }
  225. await mqtt_relay.configure(mqtt_settings)
  226. except Exception:
  227. pass # Don't fail the settings update if MQTT reconfiguration fails
  228. # Return updated settings (never scrub secrets on PUT — caller has SETTINGS_UPDATE permission)
  229. return await _build_settings_response(db, is_api_key=False)
  230. @router.patch("/", response_model=AppSettings)
  231. @router.patch("", response_model=AppSettings)
  232. async def patch_settings(
  233. settings_update: AppSettingsUpdate,
  234. db: AsyncSession = Depends(get_db),
  235. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  236. ):
  237. """Partially update application settings (same as PUT, for REST compatibility)."""
  238. return await update_settings(settings_update, db, _)
  239. class ElectricityPriceUpdate(BaseModel):
  240. """Payload for ``POST /settings/electricity-price`` (#1356).
  241. Mirrors the field name documented in ``wiki/features/energy.md`` so the
  242. Home Assistant ``rest_command`` example needs only a URL change, not a
  243. payload change. Plain non-negative float; tariffs can go as low as 0.0 in
  244. some markets (e.g. free hours).
  245. """
  246. energy_cost_per_kwh: float = Field(ge=0)
  247. @router.post("/electricity-price", response_model=AppSettings)
  248. async def update_electricity_price(
  249. payload: ElectricityPriceUpdate,
  250. db: AsyncSession = Depends(get_db),
  251. _: User | None = Depends(require_energy_cost_update()),
  252. _is_api_key: bool = Depends(caller_is_api_key),
  253. ):
  254. """Update the per-kWh electricity cost used by the energy-tracking pipeline.
  255. This is the only settings field writable via API key, gated by the
  256. ``can_update_energy_cost`` toggle on the key. JWT users still need the
  257. standard ``SETTINGS_UPDATE`` permission. See #1356 for the rationale —
  258. the general ``PATCH /settings`` route remains denied for API keys because
  259. it can rewrite SMTP/LDAP/MQTT credentials, which is a much wider surface
  260. than the documented dynamic-tariff use case requires.
  261. """
  262. await set_setting(db, "energy_cost_per_kwh", str(payload.energy_cost_per_kwh))
  263. await db.commit()
  264. db.expire_all()
  265. return await _build_settings_response(db, is_api_key=_is_api_key)
  266. @router.post("/reset", response_model=AppSettings)
  267. async def reset_settings(
  268. db: AsyncSession = Depends(get_db),
  269. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  270. ):
  271. """Reset all settings to defaults."""
  272. # Delete all settings
  273. result = await db.execute(select(Settings))
  274. for setting in result.scalars().all():
  275. await db.delete(setting)
  276. await db.commit()
  277. return DEFAULT_SETTINGS
  278. @router.get("/default-sidebar-order")
  279. async def get_default_sidebar_order(
  280. db: AsyncSession = Depends(get_db),
  281. ):
  282. """Get the admin-set default sidebar order.
  283. Intentionally unauthenticated: non-admin users need to read this value to apply
  284. the default sidebar order, but may lack SETTINGS_READ permission.
  285. The value is non-sensitive (sidebar item IDs only).
  286. """
  287. value = await get_setting(db, "default_sidebar_order")
  288. return {"default_sidebar_order": value or ""}
  289. # Fields exposed via /ui-preferences without SETTINGS_READ. Each entry MUST be
  290. # non-sensitive (no credentials, no PII, no secret tokens) — granting SETTINGS_READ
  291. # also grants visibility of SMTP/LDAP/MQTT passwords and similar, so the goal of
  292. # this endpoint is exactly to NOT require that permission for UI rendering hints.
  293. # When adding a field here, confirm it doesn't carry anything sensitive.
  294. _UI_PREFERENCE_FIELDS: tuple[str, ...] = (
  295. "require_plate_clear",
  296. "check_printer_firmware",
  297. "camera_view_mode",
  298. "time_format",
  299. "date_format",
  300. "drying_presets",
  301. "ams_humidity_thresholds",
  302. "ams_humidity_good",
  303. "ams_humidity_fair",
  304. "ams_temp_good",
  305. "ams_temp_fair",
  306. "bed_cooled_threshold",
  307. # Temperature / fan-speed presets for the printer-card popovers. Numbers
  308. # only; no PII / credentials.
  309. "nozzle_temp_presets",
  310. "bed_temp_presets",
  311. "chamber_temp_presets",
  312. "fan_speed_presets",
  313. )
  314. @router.get("/ui-preferences")
  315. async def get_ui_preferences(db: AsyncSession = Depends(get_db)):
  316. """Get the curated subset of settings that any page needs to render correctly.
  317. Intentionally not gated on SETTINGS_READ — every authenticated user (and
  318. every page that loads for them) needs these fields, but granting SETTINGS_READ
  319. would also grant visibility of secrets (SMTP/LDAP/MQTT credentials, etc.).
  320. Same pattern as /default-sidebar-order (#1293).
  321. Reuses _build_settings_response so the typed values match what /settings
  322. returns for fields with the same name — bool/int/float/str types stay in
  323. sync without a separate type-coercion path.
  324. """
  325. full = await _build_settings_response(db, is_api_key=False)
  326. dumped = full.model_dump()
  327. return {key: dumped[key] for key in _UI_PREFERENCE_FIELDS if key in dumped}
  328. @router.get("/check-ffmpeg")
  329. async def check_ffmpeg(
  330. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  331. ):
  332. """Check if ffmpeg is installed and available.
  333. Gated on ``SETTINGS_READ`` (audit finding I4 — the binary path was
  334. leaking the host filesystem layout to unauthenticated callers).
  335. ``require_permission_if_auth_enabled`` returns ``None`` only when
  336. auth is disabled (in which case there's no privacy boundary to
  337. enforce); otherwise it raises 401/403 before we get here.
  338. """
  339. from backend.app.services.camera import get_ffmpeg_path
  340. ffmpeg_path = get_ffmpeg_path()
  341. return {
  342. "installed": ffmpeg_path is not None,
  343. "path": ffmpeg_path,
  344. }
  345. @router.get("/spoolman")
  346. async def get_spoolman_settings(
  347. db: AsyncSession = Depends(get_db),
  348. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  349. ):
  350. """Get Spoolman integration settings."""
  351. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  352. spoolman_url = await get_setting(db, "spoolman_url") or ""
  353. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  354. spoolman_disable_weight_sync = await get_setting(db, "spoolman_disable_weight_sync") or "false"
  355. spoolman_report_partial_usage = await get_setting(db, "spoolman_report_partial_usage") or "true"
  356. auto_add_unknown_rfid = await get_setting(db, "auto_add_unknown_rfid") or "true"
  357. return {
  358. "spoolman_enabled": spoolman_enabled,
  359. "spoolman_url": spoolman_url,
  360. "spoolman_sync_mode": spoolman_sync_mode,
  361. "spoolman_disable_weight_sync": spoolman_disable_weight_sync,
  362. "spoolman_report_partial_usage": spoolman_report_partial_usage,
  363. "auto_add_unknown_rfid": auto_add_unknown_rfid,
  364. }
  365. @router.put("/spoolman")
  366. async def update_spoolman_settings(
  367. settings: dict,
  368. db: AsyncSession = Depends(get_db),
  369. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  370. ):
  371. """Update Spoolman integration settings."""
  372. if "spoolman_enabled" in settings:
  373. old_val = await get_setting(db, "spoolman_enabled") or "false"
  374. new_val = settings["spoolman_enabled"]
  375. await set_setting(db, "spoolman_enabled", new_val)
  376. # Switching to Spoolman: clear built-in inventory slot assignments
  377. if old_val.lower() != "true" and new_val.lower() == "true":
  378. from backend.app.models.spool_assignment import SpoolAssignment
  379. result = await db.execute(delete(SpoolAssignment))
  380. logger.info("Cleared %d spool assignments on switch to Spoolman mode", result.rowcount)
  381. # Switching back to internal mode: clear Spoolman slot assignments — the
  382. # symmetric counterpart of the clear above. Without this, stale
  383. # spoolman_slot_assignments rows linger and would wrongly count as
  384. # "assigned" in any mode-agnostic check (e.g. the missing-spool-
  385. # assignment notification, which unions both tables — #1473).
  386. elif old_val.lower() == "true" and new_val.lower() != "true":
  387. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  388. result = await db.execute(delete(SpoolmanSlotAssignment))
  389. logger.info("Cleared %d Spoolman slot assignments on switch to internal mode", result.rowcount)
  390. if "spoolman_url" in settings:
  391. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  392. if "spoolman_sync_mode" in settings:
  393. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  394. if "spoolman_disable_weight_sync" in settings:
  395. await set_setting(db, "spoolman_disable_weight_sync", settings["spoolman_disable_weight_sync"])
  396. if "spoolman_report_partial_usage" in settings:
  397. await set_setting(db, "spoolman_report_partial_usage", settings["spoolman_report_partial_usage"])
  398. if "auto_add_unknown_rfid" in settings:
  399. await set_setting(db, "auto_add_unknown_rfid", settings["auto_add_unknown_rfid"])
  400. spoolman_changed = "spoolman_enabled" in settings or "spoolman_url" in settings
  401. await db.commit()
  402. db.expire_all()
  403. if spoolman_changed:
  404. from backend.app.services.location_service import maybe_sync_spoolman_locations
  405. if await maybe_sync_spoolman_locations(db):
  406. await db.commit()
  407. # Return updated settings
  408. return await get_spoolman_settings(db)
  409. async def get_homeassistant_settings(db: AsyncSession) -> dict:
  410. """
  411. Get Home Assistant integration settings.
  412. Environment variables (HA_URL, HA_TOKEN) take precedence over database settings.
  413. """
  414. import os
  415. # Check environment variables first
  416. ha_url_env = os.environ.get("HA_URL")
  417. ha_token_env = os.environ.get("HA_TOKEN")
  418. # Fall back to database values
  419. ha_url = ha_url_env or await get_setting(db, "ha_url") or ""
  420. ha_token = ha_token_env or await get_setting(db, "ha_token") or ""
  421. ha_enabled_db = await get_setting(db, "ha_enabled") or "false"
  422. # Track which settings come from environment
  423. ha_url_from_env = bool(ha_url_env)
  424. ha_token_from_env = bool(ha_token_env)
  425. ha_env_managed = ha_url_from_env and ha_token_from_env
  426. # Auto-enable when both env vars are set, otherwise use database value
  427. if ha_url_env and ha_token_env:
  428. ha_enabled = True
  429. else:
  430. ha_enabled = ha_enabled_db.lower() == "true"
  431. return {
  432. "ha_enabled": ha_enabled,
  433. "ha_url": ha_url,
  434. "ha_token": ha_token,
  435. "ha_url_from_env": ha_url_from_env,
  436. "ha_token_from_env": ha_token_from_env,
  437. "ha_env_managed": ha_env_managed,
  438. }
  439. async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
  440. """Create a complete backup ZIP (database + all data directories).
  441. If output_path is given, the ZIP is written there.
  442. Otherwise a temporary file is created (caller must clean up).
  443. Returns (zip_path, filename).
  444. """
  445. import shutil
  446. import tempfile
  447. from backend.app.core.db_dialect import is_sqlite
  448. base_dir = app_settings.base_dir
  449. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  450. with tempfile.TemporaryDirectory() as temp_dir:
  451. temp_path = Path(temp_dir)
  452. if is_sqlite():
  453. from sqlalchemy import text
  454. from backend.app.core.database import engine
  455. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  456. # Checkpoint WAL to ensure all data is in main db file
  457. async with engine.begin() as conn:
  458. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  459. # Copy database file
  460. shutil.copy2(db_path, temp_path / "bambuddy.db")
  461. else:
  462. # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
  463. # This makes backups restorable on both SQLite and Postgres installs.
  464. import json
  465. import sqlite3
  466. from sqlalchemy import create_engine as create_sync_engine
  467. from backend.app.core.database import Base, engine
  468. backup_db_path = temp_path / "bambuddy.db"
  469. metadata = Base.metadata
  470. # Build the portable SQLite schema with SQLAlchemy's own DDL rather
  471. # than a hand-rolled CREATE TABLE. metadata.create_all() emits the
  472. # exact schema a native SQLite install gets — NOT NULL, DEFAULT
  473. # (server_default=func.now() → CURRENT_TIMESTAMP), foreign keys,
  474. # unique constraints and indexes. The previous name+type-only
  475. # rebuild dropped all of these, so a Postgres→SQLite restore left
  476. # server_default columns (e.g. spoolbuddy_devices.created_at) with
  477. # no DEFAULT — SQLAlchemy omits such columns on INSERT and the DB
  478. # then wrote NULL, which 500'd on the next read (#2526). Using the
  479. # real DDL also keeps the #1333 BLOB guard: LargeBinary still
  480. # renders as BLOB, so OIDC icon bytes survive the round trip.
  481. schema_engine = create_sync_engine(f"sqlite:///{backup_db_path}")
  482. try:
  483. metadata.create_all(schema_engine)
  484. finally:
  485. schema_engine.dispose()
  486. dst = sqlite3.connect(str(backup_db_path))
  487. # Export data from Postgres to SQLite
  488. async with engine.connect() as conn:
  489. for table in metadata.sorted_tables:
  490. result = await conn.execute(table.select())
  491. rows = result.fetchall()
  492. if not rows:
  493. continue
  494. columns = list(result.keys())
  495. placeholders = ", ".join(["?"] * len(columns))
  496. col_list = ", ".join(columns)
  497. insert_sql = f"INSERT INTO {table.name} ({col_list}) VALUES ({placeholders})" # noqa: S608 # nosec B608 — table/column names from ORM metadata, not user input
  498. def _serialize_row(row):
  499. return tuple(json.dumps(v) if isinstance(v, (list, dict)) else v for v in row)
  500. dst.executemany(insert_sql, [_serialize_row(row) for row in rows])
  501. dst.commit()
  502. dst.close()
  503. logger.info("PostgreSQL backup exported to portable SQLite format")
  504. # Copy data directories (if they exist)
  505. dirs_to_backup = [
  506. ("archive", base_dir / "archive"),
  507. ("virtual_printer", base_dir / "virtual_printer"),
  508. ("plate_calibration", app_settings.plate_calibration_dir),
  509. ("icons", base_dir / "icons"),
  510. ("projects", base_dir / "projects"),
  511. ]
  512. for name, src_dir in dirs_to_backup:
  513. if src_dir.exists() and any(src_dir.iterdir()):
  514. try:
  515. shutil.copytree(
  516. src_dir, temp_path / name
  517. ) # SEC-PATH-OK: name iterates the dirs_to_backup tuple of constant strings ("archive", "virtual_printer", ...)
  518. except shutil.Error as e:
  519. logger.warning("Some files in %s could not be copied: %s", name, e)
  520. except PermissionError as e:
  521. logger.warning("Permission denied copying %s: %s", name, e)
  522. # Include the MFA encryption key as a ZIP top-level entry alongside
  523. # bambuddy.db. Without it, encrypted client_secret / TOTP secret rows
  524. # would be unrecoverable after restore on a host without MFA_ENCRYPTION_KEY set.
  525. from backend.app.core.paths import resolve_data_dir
  526. mfa_key_src = resolve_data_dir() / ".mfa_encryption_key"
  527. if mfa_key_src.exists() and mfa_key_src.is_file():
  528. try:
  529. shutil.copy2(mfa_key_src, temp_path / ".mfa_encryption_key")
  530. except OSError as exc:
  531. logger.error(
  532. "Could not include MFA encryption key in backup (%s). "
  533. "The backup ZIP will not contain the key — restore on a "
  534. "keyless host will fail for encrypted secrets.",
  535. exc,
  536. )
  537. raise
  538. # Create ZIP
  539. if output_path is not None:
  540. zip_file = (
  541. output_path / filename
  542. ) # SEC-PATH-OK: filename = f"bambuddy-backup-{datetime.now()...}.zip" generated in create_backup_zip itself
  543. else:
  544. fd, tmp = tempfile.mkstemp(suffix=".zip")
  545. os.close(fd)
  546. zip_file = Path(tmp)
  547. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  548. for file_path in temp_path.rglob("*"):
  549. if file_path.is_file():
  550. arcname = file_path.relative_to(temp_path)
  551. zf.write(file_path, arcname)
  552. return zip_file, filename
  553. @router.get("/backup")
  554. async def create_backup(
  555. db: AsyncSession = Depends(get_db),
  556. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  557. ):
  558. """Create a complete backup (database + all files) as a ZIP download."""
  559. from starlette.background import BackgroundTask
  560. try:
  561. zip_file, filename = await create_backup_zip()
  562. return FileResponse(
  563. path=zip_file,
  564. filename=filename,
  565. media_type="application/zip",
  566. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  567. )
  568. except Exception as e:
  569. logger.error("Backup failed: %s", e, exc_info=True)
  570. return JSONResponse(
  571. status_code=500,
  572. content={"success": False, "message": "Backup failed. Check server logs for details."},
  573. )
  574. async def _import_sqlite_to_postgres(sqlite_path: Path, postgres_url: str):
  575. """Import data from a SQLite database file into the current PostgreSQL database.
  576. Used for cross-database restore (SQLite backup → PostgreSQL).
  577. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  578. """
  579. import sqlite3
  580. from sqlalchemy import text
  581. from backend.app.core.database import Base, _create_engine
  582. # Create a temporary engine for the import (current engine was disposed)
  583. pg_engine = _create_engine()
  584. try:
  585. # Open SQLite file directly (sync — it's a local file read)
  586. src = sqlite3.connect(str(sqlite_path))
  587. src.row_factory = sqlite3.Row
  588. # Get list of tables from SQLite (skip internal/FTS tables)
  589. cursor = src.execute(
  590. "SELECT name FROM sqlite_master WHERE type='table' "
  591. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  592. )
  593. src_tables = {row["name"] for row in cursor.fetchall()}
  594. # Get Postgres tables from our ORM models
  595. metadata = Base.metadata
  596. pg_tables = set(metadata.tables.keys())
  597. # Only import tables that exist in both source and destination
  598. tables_to_import = src_tables & pg_tables
  599. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  600. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  601. # This avoids all FK ordering/orphan issues during import.
  602. saved_fks = {}
  603. for table in metadata.sorted_tables:
  604. fks = list(table.foreign_key_constraints)
  605. if fks:
  606. saved_fks[table.name] = fks
  607. for fk in fks:
  608. table.constraints.discard(fk)
  609. async with pg_engine.begin() as conn:
  610. # Cap how long DROP TABLE will wait for AccessExclusiveLock so
  611. # any residual concurrent writer (per-printer MQTT clients
  612. # writing reactively, an AMS history recorder firing on its
  613. # hourly cadence) surfaces a fast `lock_timeout` error instead
  614. # of blocking the restore for 30 s or producing a deadlock.
  615. # SET LOCAL scopes to this transaction only; outside this
  616. # restore path the global default (no timeout) applies.
  617. await conn.execute(text("SET LOCAL lock_timeout = '10s'"))
  618. # Drop every existing table in the public schema with CASCADE
  619. # rather than `metadata.drop_all`. Two reasons:
  620. # 1. The user's live DB may carry orphan tables from removed
  621. # features (e.g. the legacy `spoolman_slot_assignments`,
  622. # `spoolman_k_profile`) that hold FK constraints back to
  623. # ORM tables. `drop_all` doesn't know they exist and emits
  624. # `DROP TABLE printers` without CASCADE — Postgres refuses
  625. # and the whole restore aborts (#XXXX).
  626. # 2. Even within the metadata, `drop_all` is FK-ordered and
  627. # breaks if a future schema rename leaves old constraints
  628. # around. CASCADE is the right tool for a destructive
  629. # restore: the user is intentionally wiping state.
  630. await conn.execute(
  631. text(
  632. "DO $$ DECLARE r RECORD; BEGIN "
  633. "FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP "
  634. "EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE'; "
  635. "END LOOP; END $$;"
  636. )
  637. )
  638. await conn.run_sync(metadata.create_all)
  639. # Restore FK definitions in metadata (needed for re-adding later)
  640. for table_name, fks in saved_fks.items():
  641. table_obj = metadata.tables[table_name]
  642. for fk in fks:
  643. table_obj.constraints.add(fk)
  644. # Phase 2: Import data (no FKs to worry about)
  645. async with pg_engine.begin() as conn:
  646. # Import each table in dependency order (parents before children)
  647. for table_name in sorted_tables:
  648. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  649. if not rows:
  650. continue
  651. # Filter to columns that exist in the Postgres table
  652. src_columns = rows[0].keys()
  653. pg_table = metadata.tables.get(table_name)
  654. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  655. columns = [c for c in src_columns if c in pg_columns]
  656. if not columns:
  657. continue
  658. col_list = ", ".join(columns)
  659. param_list = ", ".join(f":{c}" for c in columns)
  660. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  661. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  662. # Identify columns that need type conversion (SQLite stores booleans
  663. # as int and datetimes as str — asyncpg requires native Python types)
  664. from datetime import datetime as dt
  665. bool_columns = set()
  666. datetime_columns = set()
  667. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  668. if pg_table is not None:
  669. for col in pg_table.columns:
  670. if col.name not in columns:
  671. continue
  672. col_type = str(col.type)
  673. if col_type == "BOOLEAN":
  674. bool_columns.add(col.name)
  675. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  676. datetime_columns.add(col.name)
  677. # Track NOT NULL columns with defaults — older backups may have NULL
  678. # for columns added after the backup was created
  679. if not col.nullable:
  680. if col.default is not None:
  681. default = col.default.arg
  682. if callable(default):
  683. default = default(None)
  684. not_null_defaults[col.name] = default
  685. elif col.server_default is not None:
  686. # server_default=func.now() → use current timestamp
  687. if col.name in datetime_columns:
  688. not_null_defaults[col.name] = "__now__"
  689. else:
  690. # Try to extract literal server default
  691. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  692. if sd is not None:
  693. not_null_defaults[col.name] = sd
  694. now = dt.now()
  695. def _convert_row(
  696. row, cols=columns, bools=bool_columns, dts=datetime_columns, nn_defaults=not_null_defaults, _now=now
  697. ):
  698. result = {}
  699. for c in cols:
  700. val = row[c]
  701. if val is None and c in nn_defaults:
  702. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  703. if val is not None:
  704. if c in bools:
  705. val = bool(val)
  706. elif c in dts and isinstance(val, str):
  707. try:
  708. val = dt.fromisoformat(val)
  709. except ValueError:
  710. pass
  711. result[c] = val
  712. return result
  713. batch = [_convert_row(row) for row in rows]
  714. await conn.execute(insert_sql, batch)
  715. logger.info("Imported %d rows into %s", len(batch), table_name)
  716. # Reset sequences to max(id) + 1 for each table with an id column
  717. for table_name in sorted_tables:
  718. try:
  719. async with conn.begin_nested():
  720. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  721. max_id = result.scalar()
  722. if max_id is not None:
  723. seq_name = f"{table_name}_id_seq"
  724. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  725. except Exception:
  726. pass # Table may not have an id column or sequence
  727. src.close()
  728. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  729. # Recreate FK constraints from ORM metadata (not from saved definitions).
  730. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  731. from sqlalchemy.schema import AddConstraint
  732. failed_fks = []
  733. for table in metadata.sorted_tables:
  734. for fk in table.foreign_key_constraints:
  735. try:
  736. async with pg_engine.begin() as fk_conn:
  737. await fk_conn.execute(AddConstraint(fk))
  738. except Exception:
  739. failed_fks.append(f"{table.name}.{fk.name}")
  740. if failed_fks:
  741. logger.warning(
  742. "Could not restore %d FK constraints (orphaned data in SQLite): %s",
  743. len(failed_fks),
  744. ", ".join(failed_fks),
  745. )
  746. finally:
  747. await pg_engine.dispose()
  748. @router.post("/restore")
  749. async def restore_backup(
  750. file: UploadFile = File(...),
  751. db: AsyncSession = Depends(get_db),
  752. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  753. ):
  754. """Restore from a complete backup ZIP.
  755. Replaces the database and all data directories from the backup ZIP.
  756. Requires a restart after restore.
  757. """
  758. import shutil
  759. import tempfile
  760. from fastapi import HTTPException
  761. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  762. from backend.app.core.db_dialect import is_sqlite
  763. from backend.app.services.virtual_printer import virtual_printer_manager
  764. base_dir = app_settings.base_dir
  765. with tempfile.TemporaryDirectory() as temp_dir:
  766. temp_path = Path(temp_dir)
  767. # 1. Read and extract ZIP
  768. content = await file.read()
  769. # Check if it's a valid ZIP
  770. if not file.filename or not file.filename.endswith(".zip"):
  771. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  772. try:
  773. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  774. for name in zf.namelist():
  775. # Reject path-traversal payloads: any entry whose resolved
  776. # path escapes temp_path would allow writing arbitrary files
  777. # on the host (ZipSlip / CVE-2006-5456).
  778. dest = (
  779. temp_path / name
  780. ).resolve() # SEC-PATH-OK: is_relative_to containment check below before extractall
  781. # is_relative_to (Python 3.9+) covers both relative
  782. # path-traversal (../etc/passwd) and absolute-path overrides
  783. # (/etc/passwd) — str.startswith was vulnerable to
  784. # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
  785. # a /tmp/abc prefix check).
  786. if not dest.is_relative_to(temp_path.resolve()):
  787. raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
  788. zf.extractall(temp_path)
  789. except zipfile.BadZipFile:
  790. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  791. # 2. Validate backup
  792. backup_db = temp_path / "bambuddy.db"
  793. if not backup_db.exists():
  794. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  795. try:
  796. import asyncio
  797. # 3. Stop virtual printer if running (releases file locks)
  798. try:
  799. if virtual_printer_manager.is_enabled:
  800. logger.info("Stopping virtual printer for restore...")
  801. await virtual_printer_manager.configure(enabled=False)
  802. await asyncio.sleep(1)
  803. except Exception as e:
  804. logger.warning("Failed to stop virtual printer: %s", e)
  805. # 3b. Pause timer-based background services BEFORE the DB swap.
  806. # close_all_connections() below only disposes the engine's pool,
  807. # not the asyncio tasks that opened sessions from it. The print
  808. # scheduler (30 s cadence), smart-plug snapshot loop (30 s), and
  809. # notification digest loop all
  810. # wake up and call async_session(), which lazily re-creates a
  811. # pool connection holding RowExclusiveLock on print_queue /
  812. # smart_plug_energy_snapshots / etc. The DROP TABLE CASCADE
  813. # pass in the PostgreSQL restore path needs AccessExclusiveLock
  814. # on every public table, producing an AB/BA deadlock and a
  815. # full restore rollback. Successful restore already requires a
  816. # container restart, so we don't restart the services here.
  817. try:
  818. from backend.app.services.notification_service import notification_service
  819. from backend.app.services.print_scheduler import scheduler as print_scheduler
  820. from backend.app.services.smart_plug_manager import smart_plug_manager
  821. logger.info("Pausing background services for restore...")
  822. print_scheduler.stop()
  823. smart_plug_manager.stop_scheduler()
  824. notification_service.stop_digest_scheduler()
  825. # In-flight loop iterations need a moment to commit + release
  826. # their DB sessions before we dispose() the engine pool.
  827. await asyncio.sleep(1.0)
  828. except Exception as e:
  829. logger.warning("Could not cleanly pause background services: %s", e)
  830. # 4. Close current database connections
  831. logger.info("Closing database connections...")
  832. await close_all_connections()
  833. # B1: Restore the MFA encryption key file BEFORE the database swap.
  834. # If the key write fails (OSError, RO disk, full disk, EACCES) we
  835. # can still abort while the live DB is intact. Doing this AFTER the
  836. # DB swap would leave the database with rows encrypted under the
  837. # backup's key but the running install holding only the old key —
  838. # every encrypted secret becomes unrecoverable.
  839. from backend.app.core.paths import resolve_data_dir
  840. mfa_key_src = temp_path / ".mfa_encryption_key"
  841. if mfa_key_src.exists() and mfa_key_src.is_file():
  842. dst_key = resolve_data_dir() / ".mfa_encryption_key"
  843. tmp_key = dst_key.parent / ".mfa_encryption_key.restore-tmp"
  844. try:
  845. dst_key.parent.mkdir(parents=True, exist_ok=True)
  846. # S1: atomic write with restrictive mode from creation.
  847. # O_TRUNC because a stale tmp may exist from a prior
  848. # failed restore attempt — we want to overwrite it.
  849. fd = os.open(str(tmp_key), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
  850. try:
  851. os.write(fd, mfa_key_src.read_bytes())
  852. finally:
  853. os.close(fd)
  854. # POSIX rename(2) — atomic when source/dest are on the
  855. # same filesystem (we're staying inside dst_key.parent).
  856. os.replace(str(tmp_key), str(dst_key))
  857. # S9: warn if the FS doesn't enforce 0o600
  858. actual_mode = dst_key.stat().st_mode & 0o777
  859. if actual_mode != 0o600:
  860. logger.warning(
  861. "Restored MFA key file %s: filesystem did not enforce 0o600 "
  862. "(actual: 0o%o). Key may be world-readable on Windows / SMB / FUSE.",
  863. dst_key,
  864. actual_mode,
  865. )
  866. logger.info("Restored .mfa_encryption_key from backup")
  867. except OSError as e:
  868. logger.error(
  869. "Could not write restored MFA key file to %s: %s — "
  870. "aborting BEFORE database swap (DB unchanged).",
  871. dst_key,
  872. e,
  873. exc_info=True,
  874. )
  875. raise HTTPException(
  876. status_code=500,
  877. detail=("Restore aborted: MFA key write failed. Database is unchanged. Check server logs."),
  878. ) from e
  879. # 5. Replace database
  880. logger.info("Restoring database from backup...")
  881. if is_sqlite():
  882. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  883. # Use SQLite's online backup API instead of shutil.copy2.
  884. # The pragma at database.py:19 runs the live DB in WAL mode,
  885. # which means a naive file copy is unsafe: anything written
  886. # to the live DB before this call that hasn't been
  887. # checkpointed yet (seed_default_groups + init_db on first
  888. # start, plus whatever background heartbeats wrote during
  889. # the request window) sits in bambuddy.db-wal with valid
  890. # checksums. The route handler's own `db: Depends(get_db)`
  891. # session also keeps a connection checked out across
  892. # engine.dispose(), holding fds to the WAL inode. With
  893. # `shutil.copy2` SQLite finds the stale WAL on the next
  894. # open and silently re-applies those page-level writes on
  895. # top of the restored DB, partially clobbering it with
  896. # fresh-install state — the user sees a "successful"
  897. # restore where most rows and settings have reverted to
  898. # defaults (#1211 / #668). The page-by-page backup API
  899. # opens both DBs as real SQLite connections, takes the
  900. # right locks, and routes new pages through the live DB's
  901. # own WAL — so concurrent open sessions see their own
  902. # snapshot until they close (transaction isolation) but
  903. # can't corrupt the restored state.
  904. import sqlite3
  905. src_conn = sqlite3.connect(str(backup_db))
  906. try:
  907. dst_conn = sqlite3.connect(str(db_path))
  908. try:
  909. src_conn.backup(dst_conn)
  910. finally:
  911. dst_conn.close()
  912. finally:
  913. src_conn.close()
  914. else:
  915. # Import SQLite backup into PostgreSQL
  916. logger.info("Importing SQLite backup into PostgreSQL...")
  917. await _import_sqlite_to_postgres(backup_db, app_settings.database_url)
  918. # 6. Replace data directories
  919. # For Docker compatibility: clear contents then copy (don't delete mount points)
  920. dirs_to_restore = [
  921. ("archive", base_dir / "archive"),
  922. ("virtual_printer", base_dir / "virtual_printer"),
  923. ("plate_calibration", app_settings.plate_calibration_dir),
  924. ("icons", base_dir / "icons"),
  925. ("projects", base_dir / "projects"),
  926. ]
  927. skipped_dirs = []
  928. for name, dest_dir in dirs_to_restore:
  929. src_dir = (
  930. temp_path / name
  931. ) # SEC-PATH-OK: name iterates the dirs_to_restore tuple of constant strings ("archive", "virtual_printer", ...)
  932. if src_dir.exists():
  933. logger.info("Restoring %s directory...", name)
  934. try:
  935. # Clear destination contents (not the dir itself - may be Docker mount)
  936. if dest_dir.exists():
  937. for item in dest_dir.iterdir():
  938. try:
  939. if item.is_dir():
  940. shutil.rmtree(item)
  941. else:
  942. item.unlink()
  943. except OSError as e:
  944. logger.warning("Could not delete %s: %s", item, e)
  945. else:
  946. dest_dir.mkdir(parents=True, exist_ok=True)
  947. # Copy contents from backup
  948. for item in src_dir.iterdir():
  949. dest_item = dest_dir / item.name
  950. if item.is_dir():
  951. shutil.copytree(item, dest_item)
  952. else:
  953. shutil.copy2(item, dest_item)
  954. except OSError as e:
  955. logger.warning("Could not restore %s directory: %s", name, e)
  956. skipped_dirs.append(name)
  957. # 7. Reset the encryption singleton so the migration that runs
  958. # inside init_db() picks up the restored key file (if a new one
  959. # was written above). Without this reset, _get_fernet would
  960. # return the cached Fernet instance built from the previous key.
  961. import backend.app.core.encryption as _enc_mod
  962. _enc_mod._fernet_instance = None
  963. _enc_mod._key_source = None
  964. _enc_mod._warn_shown = False
  965. # 8. Reinitialize the database engine and apply schema migrations so that
  966. # tables added after the backup was created (e.g. ams_labels) exist
  967. # immediately, without requiring a manual restart.
  968. await reinitialize_database()
  969. await init_db()
  970. logger.info("Restore complete - restart required")
  971. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  972. if skipped_dirs:
  973. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  974. return {
  975. "success": True,
  976. "message": message,
  977. }
  978. except HTTPException:
  979. # Preserve specific HTTP error responses raised inside the restore
  980. # body (e.g. the key-write OSError → 500). The blanket
  981. # except Exception below would otherwise swallow them and replace
  982. # the operator-facing detail with a generic message.
  983. raise
  984. except Exception as e:
  985. logger.error("Restore failed: %s", e, exc_info=True)
  986. return JSONResponse(
  987. status_code=500,
  988. content={"success": False, "message": "Restore failed. Check server logs for details."},
  989. )
  990. @router.get("/network-interfaces")
  991. async def get_network_interfaces(
  992. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  993. ):
  994. """Get available network interfaces with all IPs (primary + aliases)."""
  995. from backend.app.services.network_utils import get_all_interface_ips
  996. interfaces = get_all_interface_ips()
  997. return {"interfaces": interfaces}
  998. @router.get("/virtual-printer/models")
  999. async def get_virtual_printer_models(
  1000. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1001. ):
  1002. """Get available virtual printer models."""
  1003. from backend.app.services.virtual_printer import (
  1004. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1005. VIRTUAL_PRINTER_MODELS,
  1006. )
  1007. return {
  1008. "models": VIRTUAL_PRINTER_MODELS,
  1009. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1010. }
  1011. @router.get("/virtual-printer")
  1012. async def get_virtual_printer_settings(
  1013. db: AsyncSession = Depends(get_db),
  1014. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1015. ):
  1016. """Get virtual printer settings and status."""
  1017. from backend.app.services.virtual_printer import (
  1018. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1019. virtual_printer_manager,
  1020. )
  1021. enabled = await get_setting(db, "virtual_printer_enabled")
  1022. access_code = await get_setting(db, "virtual_printer_access_code")
  1023. mode = await get_setting(db, "virtual_printer_mode")
  1024. model = await get_setting(db, "virtual_printer_model")
  1025. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  1026. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  1027. tailscale_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  1028. archive_name_source = await get_setting(db, "virtual_printer_archive_name_source")
  1029. from backend.app.models.virtual_printer import VP_MODE_ARCHIVE, normalize_vp_mode
  1030. return {
  1031. "enabled": enabled == "true" if enabled else False,
  1032. "access_code_set": bool(access_code),
  1033. # Normalize on read so older settings rows (with `immediate` /
  1034. # `print_queue`) come out as `archive` / `queue` for the frontend.
  1035. "mode": normalize_vp_mode(mode) or VP_MODE_ARCHIVE,
  1036. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1037. "target_printer_id": int(target_printer_id) if target_printer_id else None,
  1038. "remote_interface_ip": remote_interface_ip or "",
  1039. "tailscale_disabled": tailscale_disabled_raw == "true" if tailscale_disabled_raw else True,
  1040. "archive_name_source": archive_name_source if archive_name_source in ("metadata", "filename") else "metadata",
  1041. "status": virtual_printer_manager.get_status(),
  1042. }
  1043. @router.put("/virtual-printer")
  1044. async def update_virtual_printer_settings(
  1045. enabled: bool = None,
  1046. access_code: str = None,
  1047. mode: str = None,
  1048. model: str = None,
  1049. target_printer_id: int = None,
  1050. remote_interface_ip: str = None,
  1051. tailscale_disabled: bool = None,
  1052. archive_name_source: str = None,
  1053. db: AsyncSession = Depends(get_db),
  1054. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1055. ):
  1056. """Update virtual printer settings and restart services if needed.
  1057. For proxy mode with SSDP proxy (dual-homed setup):
  1058. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  1059. - Local interface is auto-detected based on target printer IP
  1060. """
  1061. from sqlalchemy import select
  1062. from backend.app.models.printer import Printer
  1063. from backend.app.services.virtual_printer import (
  1064. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1065. VIRTUAL_PRINTER_MODELS,
  1066. virtual_printer_manager,
  1067. )
  1068. # Get current values
  1069. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  1070. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1071. # Default to `archive` (the canonical name) but tolerate legacy `immediate`
  1072. # in the stored value — normalized later before validation.
  1073. current_mode = await get_setting(db, "virtual_printer_mode") or "archive"
  1074. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  1075. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  1076. current_target_id = int(current_target_id_str) if current_target_id_str else None
  1077. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  1078. current_ts_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  1079. # Default True (opt-in) when the setting has never been saved — matches the model default.
  1080. current_ts_disabled = current_ts_disabled_raw == "true" if current_ts_disabled_raw else True
  1081. # Apply updates
  1082. new_enabled = enabled if enabled is not None else current_enabled
  1083. new_access_code = access_code if access_code is not None else current_access_code
  1084. new_mode = mode if mode is not None else current_mode
  1085. new_model = model if model is not None else current_model
  1086. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  1087. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  1088. new_ts_disabled = tailscale_disabled if tailscale_disabled is not None else current_ts_disabled
  1089. # Validate mode. Canonical wire values are `archive` / `review` / `queue`
  1090. # / `proxy`; legacy `immediate` and `print_queue` are accepted as aliases
  1091. # and translated before storage so support bundles stop showing the old
  1092. # confusing pair (#1429 mode-label discrepancy).
  1093. from backend.app.models.virtual_printer import VP_MODE_VALUES, normalize_vp_mode
  1094. canonical_mode = normalize_vp_mode(new_mode)
  1095. if canonical_mode not in VP_MODE_VALUES:
  1096. return JSONResponse(
  1097. status_code=400,
  1098. content={
  1099. "detail": f"Mode must be one of: {', '.join(VP_MODE_VALUES)}",
  1100. },
  1101. )
  1102. new_mode = canonical_mode
  1103. # Validate archive_name_source
  1104. if archive_name_source is not None and archive_name_source not in ("metadata", "filename"):
  1105. return JSONResponse(
  1106. status_code=400,
  1107. content={"detail": "archive_name_source must be 'metadata' or 'filename'"},
  1108. )
  1109. # Validate model
  1110. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  1111. return JSONResponse(
  1112. status_code=400,
  1113. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  1114. )
  1115. # Mode-specific validation and printer lookup
  1116. target_printer_ip = ""
  1117. target_printer_serial = ""
  1118. if new_mode == "proxy":
  1119. # Proxy mode requires target printer when enabling
  1120. if new_enabled and not new_target_id:
  1121. # If just switching to proxy mode (not explicitly enabling), auto-disable
  1122. if enabled is None:
  1123. new_enabled = False
  1124. else:
  1125. return JSONResponse(
  1126. status_code=400,
  1127. content={"detail": "Target printer is required for proxy mode"},
  1128. )
  1129. # Look up printer IP and serial if we have a target
  1130. if new_target_id:
  1131. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  1132. printer = result.scalar_one_or_none()
  1133. if not printer:
  1134. return JSONResponse(
  1135. status_code=400,
  1136. content={"detail": f"Printer with ID {new_target_id} not found"},
  1137. )
  1138. target_printer_ip = printer.ip_address
  1139. target_printer_serial = printer.serial_number
  1140. # Access code not required for proxy mode
  1141. else:
  1142. # Non-proxy modes require access code when enabling
  1143. if new_enabled and not new_access_code:
  1144. # If just switching modes (not explicitly enabling), auto-disable
  1145. if enabled is None:
  1146. new_enabled = False
  1147. else:
  1148. return JSONResponse(
  1149. status_code=400,
  1150. content={"detail": "Access code is required when enabling virtual printer"},
  1151. )
  1152. # Validate access code length (Bambu Studio requires exactly 8 characters)
  1153. if access_code is not None and access_code and len(access_code) != 8:
  1154. return JSONResponse(
  1155. status_code=400,
  1156. content={"detail": "Access code must be exactly 8 characters"},
  1157. )
  1158. # Save settings
  1159. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  1160. if access_code is not None:
  1161. await set_setting(db, "virtual_printer_access_code", access_code)
  1162. await set_setting(db, "virtual_printer_mode", new_mode)
  1163. if model is not None:
  1164. await set_setting(db, "virtual_printer_model", model)
  1165. if target_printer_id is not None:
  1166. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  1167. if remote_interface_ip is not None:
  1168. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  1169. if tailscale_disabled is not None:
  1170. await set_setting(db, "virtual_printer_tailscale_disabled", "true" if tailscale_disabled else "false")
  1171. if archive_name_source is not None:
  1172. await set_setting(db, "virtual_printer_archive_name_source", archive_name_source)
  1173. # Propagate tailscale_disabled to the first VirtualPrinter row so sync_from_db() picks it up
  1174. if tailscale_disabled is not None:
  1175. from backend.app.models.virtual_printer import VirtualPrinter as VPModel
  1176. vp_result = await db.execute(select(VPModel).order_by(VPModel.position).limit(1))
  1177. first_vp = vp_result.scalar_one_or_none()
  1178. if first_vp is not None:
  1179. first_vp.tailscale_disabled = new_ts_disabled
  1180. await db.commit()
  1181. db.expire_all()
  1182. # Reconfigure virtual printer
  1183. try:
  1184. await virtual_printer_manager.configure(
  1185. enabled=new_enabled,
  1186. access_code=new_access_code,
  1187. mode=new_mode,
  1188. model=new_model,
  1189. target_printer_ip=target_printer_ip,
  1190. target_printer_serial=target_printer_serial,
  1191. remote_interface_ip=new_remote_iface,
  1192. )
  1193. except ValueError as e:
  1194. logger.warning("Virtual printer configuration validation error: %s", e)
  1195. return JSONResponse(
  1196. status_code=400,
  1197. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  1198. )
  1199. except Exception as e:
  1200. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  1201. return JSONResponse(
  1202. status_code=500,
  1203. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  1204. )
  1205. return await get_virtual_printer_settings(db)
  1206. # =============================================================================
  1207. # MQTT Relay Settings
  1208. # =============================================================================
  1209. @router.get("/mqtt/status")
  1210. async def get_mqtt_status(
  1211. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1212. ):
  1213. """Get MQTT relay connection status."""
  1214. from backend.app.services.mqtt_relay import mqtt_relay
  1215. return mqtt_relay.get_status()