settings.py 60 KB

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