settings.py 60 KB

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