settings.py 88 KB

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