settings.py 86 KB

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