settings.py 83 KB

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