settings.py 81 KB

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