settings.py 65 KB

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