settings.py 82 KB

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