settings.py 69 KB

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