settings.py 68 KB

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