settings.py 68 KB

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