settings.py 61 KB

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