settings.py 81 KB

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