settings.py 62 KB

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