settings.py 81 KB

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