settings.py 72 KB

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