settings.py 62 KB

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