settings.py 80 KB

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