settings.py 62 KB

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