settings.py 65 KB

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