github_backup.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. """API routes for GitHub profile backup."""
  2. import logging
  3. from fastapi import APIRouter, Depends, HTTPException, Query
  4. from sqlalchemy import delete, desc, select
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  7. from backend.app.core.database import get_db
  8. from backend.app.core.permissions import Permission
  9. from backend.app.models.github_backup import GitHubBackupConfig, GitHubBackupLog
  10. from backend.app.models.user import User
  11. from backend.app.schemas.github_backup import (
  12. REF_PATTERN,
  13. CloudAccountCounts,
  14. GitHubBackupConfigCreate,
  15. GitHubBackupConfigResponse,
  16. GitHubBackupConfigUpdate,
  17. GitHubBackupLogResponse,
  18. GitHubBackupStatus,
  19. GitHubBackupTriggerResponse,
  20. GitHubCommitListResponse,
  21. GitHubRestorePreview,
  22. GitHubRestoreRequest,
  23. GitHubRestoreResponse,
  24. GitHubTestConnectionResponse,
  25. ProviderType,
  26. )
  27. from backend.app.services.github_backup import github_backup_service
  28. from backend.app.services.github_restore import github_restore_service
  29. logger = logging.getLogger(__name__)
  30. router = APIRouter(prefix="/github-backup", tags=["github-backup"])
  31. _PUBLIC_REPO_ERROR = (
  32. "Refusing to save: the target repository is not private. Bambuddy backups "
  33. "include MQTT credentials, Home Assistant tokens, Prometheus tokens, your "
  34. "Bambu Cloud email, the printer access codes via K-profiles, and other "
  35. "settings that must not be exposed publicly. Make the repository private "
  36. "in your provider's UI and try again."
  37. )
  38. _UNKNOWN_VISIBILITY_ERROR = (
  39. "Refusing to save: could not confirm the target repository is private. "
  40. "Bambuddy backups contain credentials and must never go to a public or "
  41. "internal-visibility repository. Verify the URL, the access token's scope, "
  42. "and that your provider exposes the 'private' / 'visibility' field on its "
  43. "repo API."
  44. )
  45. async def _enforce_private_repo(repo_url: str, token: str, provider: str) -> None:
  46. """Run a test_connection and refuse if the repo is not confirmed private.
  47. Used by POST and PATCH /config so a backup configuration can never be
  48. saved against a public repository.
  49. The URL is policy-checked first: the Gitea and Forgejo backends derive
  50. their API base from this value (``get_api_base``) and then request it with
  51. the supplied token, so an unchecked repository_url is an outbound fetch to
  52. an operator-supplied host. A self-hosted Gitea on the LAN is the normal
  53. case, so the LAN-service tier applies — this only rules out the targets
  54. that are wrong under any topology.
  55. """
  56. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  57. try:
  58. assert_safe_lan_service_url(repo_url, label="Repository URL")
  59. except ValueError as exc:
  60. raise HTTPException(status_code=422, detail=str(exc)) from exc
  61. result = await github_backup_service.test_connection(repo_url, token, provider=provider)
  62. if not result.get("success"):
  63. message = result.get("message") or "Connection test failed"
  64. raise HTTPException(status_code=400, detail=f"Cannot verify repository: {message}")
  65. is_private = result.get("is_private")
  66. if is_private is None:
  67. raise HTTPException(status_code=400, detail=_UNKNOWN_VISIBILITY_ERROR)
  68. if is_private is False:
  69. raise HTTPException(status_code=400, detail=_PUBLIC_REPO_ERROR)
  70. async def _count_cloud_accounts(db: AsyncSession) -> tuple[int, int]:
  71. """How many Bambu / Orca accounts a backup would collect from.
  72. Asks the collector itself rather than re-deriving the rule, so the number
  73. the UI gates on can't drift from the number the backup actually uses
  74. (#2717). Counts only — never who.
  75. """
  76. try:
  77. bambu, orca = await github_backup_service.cloud_accounts(db)
  78. return len(bambu), len(orca)
  79. except Exception:
  80. # A settings page must still render when a credential store is
  81. # unreadable; the toggle simply shows as unavailable.
  82. logger.warning("Failed to count connected cloud accounts", exc_info=True)
  83. return 0, 0
  84. @router.get("/cloud-accounts", response_model=CloudAccountCounts)
  85. async def get_cloud_accounts(
  86. db: AsyncSession = Depends(get_db),
  87. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  88. ):
  89. """How many cloud accounts the Cloud Profiles category would collect from.
  90. Its own endpoint rather than a field on ``/config``, because the settings
  91. form needs this before any config exists — ``/config`` answers ``null``
  92. until the first save, which would leave the toggle disabled during the
  93. very setup it's part of.
  94. """
  95. bambu, orca = await _count_cloud_accounts(db)
  96. return CloudAccountCounts(bambu=bambu, orca=orca)
  97. def _config_to_response(config: GitHubBackupConfig) -> dict:
  98. """Convert config model to response dict."""
  99. return {
  100. "id": config.id,
  101. "repository_url": config.repository_url,
  102. "has_token": bool(config.access_token),
  103. "branch": config.branch,
  104. "provider": config.provider,
  105. "allow_insecure_http": config.allow_insecure_http,
  106. "schedule_enabled": config.schedule_enabled,
  107. "schedule_type": config.schedule_type,
  108. "backup_kprofiles": config.backup_kprofiles,
  109. "backup_cloud_profiles": config.backup_cloud_profiles,
  110. "backup_settings": config.backup_settings,
  111. "backup_spools": config.backup_spools,
  112. "backup_archives": config.backup_archives,
  113. "enabled": config.enabled,
  114. "last_backup_at": config.last_backup_at,
  115. "last_backup_status": config.last_backup_status,
  116. "last_backup_message": config.last_backup_message,
  117. "last_backup_commit_sha": config.last_backup_commit_sha,
  118. "next_scheduled_run": config.next_scheduled_run,
  119. "created_at": config.created_at,
  120. "updated_at": config.updated_at,
  121. }
  122. @router.get("/config", response_model=GitHubBackupConfigResponse | None)
  123. async def get_config(
  124. db: AsyncSession = Depends(get_db),
  125. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  126. ):
  127. """Get the current GitHub backup configuration."""
  128. result = await db.execute(select(GitHubBackupConfig).limit(1))
  129. config = result.scalar_one_or_none()
  130. if not config:
  131. return None
  132. return _config_to_response(config)
  133. @router.post("/config", response_model=GitHubBackupConfigResponse)
  134. async def save_config(
  135. config_data: GitHubBackupConfigCreate,
  136. db: AsyncSession = Depends(get_db),
  137. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  138. ):
  139. """Create or update GitHub backup configuration.
  140. Only one configuration is supported. If one exists, it will be updated.
  141. The target repository must be private — Bambuddy backups carry MQTT
  142. credentials, HA/Prometheus tokens, the Bambu Cloud email, and printer
  143. access codes (via K-profiles), so a public repo is a hard reject.
  144. """
  145. await _enforce_private_repo(
  146. config_data.repository_url,
  147. config_data.access_token,
  148. config_data.provider.value,
  149. )
  150. # Check for existing config
  151. result = await db.execute(select(GitHubBackupConfig).limit(1))
  152. config = result.scalar_one_or_none()
  153. if config:
  154. # Update existing
  155. config.repository_url = config_data.repository_url
  156. config.access_token = config_data.access_token
  157. config.branch = config_data.branch
  158. config.provider = config_data.provider.value
  159. config.schedule_enabled = config_data.schedule_enabled
  160. config.schedule_type = config_data.schedule_type.value
  161. config.backup_kprofiles = config_data.backup_kprofiles
  162. config.backup_cloud_profiles = config_data.backup_cloud_profiles
  163. config.backup_settings = config_data.backup_settings
  164. config.backup_spools = config_data.backup_spools
  165. config.backup_archives = config_data.backup_archives
  166. config.allow_insecure_http = config_data.allow_insecure_http
  167. config.enabled = config_data.enabled
  168. # Calculate next scheduled run if enabled
  169. if config.schedule_enabled:
  170. config.next_scheduled_run = github_backup_service.calculate_next_run(config.schedule_type)
  171. else:
  172. config.next_scheduled_run = None
  173. logger.info("Updated GitHub backup config: %s", config.repository_url)
  174. else:
  175. # Create new
  176. config = GitHubBackupConfig(
  177. repository_url=config_data.repository_url,
  178. access_token=config_data.access_token,
  179. branch=config_data.branch,
  180. provider=config_data.provider.value,
  181. schedule_enabled=config_data.schedule_enabled,
  182. schedule_type=config_data.schedule_type.value,
  183. backup_kprofiles=config_data.backup_kprofiles,
  184. backup_cloud_profiles=config_data.backup_cloud_profiles,
  185. backup_settings=config_data.backup_settings,
  186. backup_spools=config_data.backup_spools,
  187. backup_archives=config_data.backup_archives,
  188. allow_insecure_http=config_data.allow_insecure_http,
  189. enabled=config_data.enabled,
  190. )
  191. if config.schedule_enabled:
  192. config.next_scheduled_run = github_backup_service.calculate_next_run(config.schedule_type)
  193. db.add(config)
  194. logger.info("Created GitHub backup config: %s", config.repository_url)
  195. await db.commit()
  196. await db.refresh(config)
  197. return _config_to_response(config)
  198. @router.patch("/config", response_model=GitHubBackupConfigResponse)
  199. async def update_config(
  200. update_data: GitHubBackupConfigUpdate,
  201. db: AsyncSession = Depends(get_db),
  202. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  203. ):
  204. """Partially update GitHub backup configuration."""
  205. result = await db.execute(select(GitHubBackupConfig).limit(1))
  206. config = result.scalar_one_or_none()
  207. if not config:
  208. raise HTTPException(status_code=404, detail="No configuration found")
  209. update_dict = update_data.model_dump(exclude_unset=True)
  210. # Validate HTTP URL restriction when the URL policy is being changed. This avoids blocking unrelated autosaves
  211. # for legacy configs that already contain an HTTP URL.
  212. if "repository_url" in update_dict or "allow_insecure_http" in update_dict:
  213. url_to_check = update_dict.get("repository_url", config.repository_url)
  214. effective_allow_http = update_dict.get("allow_insecure_http", config.allow_insecure_http)
  215. if url_to_check and url_to_check.startswith("http://") and not effective_allow_http:
  216. raise HTTPException(
  217. status_code=422,
  218. detail="This URL uses HTTP instead of HTTPS. Enable 'Allow insecure HTTP' if your instance does not use TLS.",
  219. )
  220. # Re-verify the repo is private whenever the target changes — new URL,
  221. # new token, or new provider. We DON'T re-test on every unrelated PATCH
  222. # (e.g. toggling backup_archives) so flipping schedule settings doesn't
  223. # round-trip a live API call.
  224. target_changed = "repository_url" in update_dict or "access_token" in update_dict or "provider" in update_dict
  225. if target_changed:
  226. provider_value = update_dict.get("provider", config.provider)
  227. if hasattr(provider_value, "value"):
  228. provider_value = provider_value.value
  229. await _enforce_private_repo(
  230. update_dict.get("repository_url", config.repository_url),
  231. update_dict.get("access_token", config.access_token),
  232. provider_value,
  233. )
  234. for key, value in update_dict.items():
  235. if key in ("schedule_type", "provider") and value is not None:
  236. setattr(config, key, value.value)
  237. else:
  238. setattr(config, key, value)
  239. # Recalculate next scheduled run if schedule settings changed
  240. if "schedule_enabled" in update_dict or "schedule_type" in update_dict:
  241. if config.schedule_enabled:
  242. config.next_scheduled_run = github_backup_service.calculate_next_run(config.schedule_type)
  243. else:
  244. config.next_scheduled_run = None
  245. await db.commit()
  246. await db.refresh(config)
  247. logger.info("Updated GitHub backup config: %s", config.repository_url)
  248. return _config_to_response(config)
  249. @router.delete("/config")
  250. async def delete_config(
  251. db: AsyncSession = Depends(get_db),
  252. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  253. ):
  254. """Delete the GitHub backup configuration and all logs."""
  255. result = await db.execute(select(GitHubBackupConfig).limit(1))
  256. config = result.scalar_one_or_none()
  257. if not config:
  258. raise HTTPException(status_code=404, detail="No configuration found")
  259. await db.delete(config)
  260. await db.commit()
  261. logger.info("Deleted GitHub backup config")
  262. return {"message": "Configuration deleted"}
  263. @router.post("/test", response_model=GitHubTestConnectionResponse)
  264. async def test_connection(
  265. repo_url: str = Query(..., description="Repository URL"),
  266. token: str = Query(..., description="Personal Access Token"),
  267. provider: ProviderType = Query(default=ProviderType.GITHUB, description="Git provider key"),
  268. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  269. ):
  270. """Test Git provider connection with provided credentials."""
  271. result = await github_backup_service.test_connection(repo_url, token, provider=provider)
  272. return GitHubTestConnectionResponse(**result)
  273. @router.post("/test-stored", response_model=GitHubTestConnectionResponse)
  274. async def test_stored_connection(
  275. db: AsyncSession = Depends(get_db),
  276. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  277. ):
  278. """Test GitHub connection using stored configuration."""
  279. result = await db.execute(select(GitHubBackupConfig).limit(1))
  280. config = result.scalar_one_or_none()
  281. if not config:
  282. raise HTTPException(status_code=404, detail="No configuration found")
  283. if not config.access_token:
  284. raise HTTPException(status_code=400, detail="No access token configured")
  285. test_result = await github_backup_service.test_connection(
  286. config.repository_url,
  287. config.access_token,
  288. provider=config.provider,
  289. )
  290. return GitHubTestConnectionResponse(**test_result)
  291. @router.post("/run", response_model=GitHubBackupTriggerResponse)
  292. async def trigger_backup(
  293. db: AsyncSession = Depends(get_db),
  294. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  295. ):
  296. """Manually trigger a backup."""
  297. result = await db.execute(select(GitHubBackupConfig).limit(1))
  298. config = result.scalar_one_or_none()
  299. if not config:
  300. raise HTTPException(status_code=404, detail="No configuration found. Configure backup first.")
  301. if not config.enabled:
  302. raise HTTPException(status_code=400, detail="Backup is disabled")
  303. backup_result = await github_backup_service.run_backup(config.id, trigger="manual")
  304. return GitHubBackupTriggerResponse(**backup_result)
  305. @router.get("/status", response_model=GitHubBackupStatus)
  306. async def get_status(
  307. db: AsyncSession = Depends(get_db),
  308. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  309. ):
  310. """Get current backup status."""
  311. result = await db.execute(select(GitHubBackupConfig).limit(1))
  312. config = result.scalar_one_or_none()
  313. if not config:
  314. return GitHubBackupStatus(
  315. configured=False,
  316. enabled=False,
  317. is_running=False,
  318. progress=None,
  319. last_backup_at=None,
  320. last_backup_status=None,
  321. next_scheduled_run=None,
  322. )
  323. return GitHubBackupStatus(
  324. configured=True,
  325. enabled=config.enabled,
  326. is_running=github_backup_service.is_running,
  327. restore_running=github_restore_service.is_running,
  328. progress=github_backup_service.progress or github_restore_service.progress,
  329. last_backup_at=config.last_backup_at,
  330. last_backup_status=config.last_backup_status,
  331. next_scheduled_run=config.next_scheduled_run,
  332. )
  333. @router.get("/commits", response_model=GitHubCommitListResponse)
  334. async def list_commits(
  335. limit: int = Query(default=20, ge=1, le=100),
  336. db: AsyncSession = Depends(get_db),
  337. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_RESTORE),
  338. ):
  339. """List recent backup commits so the user can pick one to restore from."""
  340. result = await db.execute(select(GitHubBackupConfig).limit(1))
  341. config = result.scalar_one_or_none()
  342. if not config:
  343. raise HTTPException(status_code=404, detail="No configuration found. Configure backup first.")
  344. commit_result = await github_restore_service.list_commits(config, limit=limit)
  345. return GitHubCommitListResponse(**commit_result)
  346. @router.get("/restore/preview", response_model=GitHubRestorePreview)
  347. async def preview_restore(
  348. ref: str = Query(default="HEAD", pattern=REF_PATTERN),
  349. db: AsyncSession = Depends(get_db),
  350. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_RESTORE),
  351. ):
  352. """Report which categories a given backup commit contains."""
  353. result = await db.execute(select(GitHubBackupConfig).limit(1))
  354. config = result.scalar_one_or_none()
  355. if not config:
  356. raise HTTPException(status_code=404, detail="No configuration found. Configure backup first.")
  357. preview = await github_restore_service.preview(db, config, ref=ref)
  358. return GitHubRestorePreview(**preview)
  359. @router.post("/restore", response_model=GitHubRestoreResponse)
  360. async def restore_backup(
  361. request: GitHubRestoreRequest,
  362. db: AsyncSession = Depends(get_db),
  363. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_RESTORE),
  364. ):
  365. """Restore selected categories from one backup commit.
  366. Note there is no private-repo gate here, unlike the config endpoints: that
  367. check exists to stop credentials leaving the instance, and this path only
  368. reads. A config can only be saved against a private repo anyway.
  369. """
  370. result = await db.execute(select(GitHubBackupConfig).limit(1))
  371. config = result.scalar_one_or_none()
  372. if not config:
  373. raise HTTPException(status_code=404, detail="No configuration found. Configure backup first.")
  374. restore_result = await github_restore_service.run_restore(
  375. config.id,
  376. ref=request.ref,
  377. categories=request.categories,
  378. overwrite_existing=request.overwrite_existing,
  379. )
  380. return GitHubRestoreResponse(**restore_result)
  381. @router.get("/logs", response_model=list[GitHubBackupLogResponse])
  382. async def get_logs(
  383. limit: int = Query(default=50, ge=1, le=200),
  384. offset: int = Query(default=0, ge=0),
  385. db: AsyncSession = Depends(get_db),
  386. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  387. ):
  388. """Get backup logs."""
  389. result = await db.execute(select(GitHubBackupConfig).limit(1))
  390. config = result.scalar_one_or_none()
  391. if not config:
  392. return []
  393. logs_result = await db.execute(
  394. select(GitHubBackupLog)
  395. .where(GitHubBackupLog.config_id == config.id)
  396. .order_by(desc(GitHubBackupLog.started_at))
  397. .offset(offset)
  398. .limit(limit)
  399. )
  400. logs = logs_result.scalars().all()
  401. return [
  402. GitHubBackupLogResponse(
  403. id=log.id,
  404. config_id=log.config_id,
  405. started_at=log.started_at,
  406. completed_at=log.completed_at,
  407. status=log.status,
  408. trigger=log.trigger,
  409. commit_sha=log.commit_sha,
  410. files_changed=log.files_changed,
  411. error_message=log.error_message,
  412. )
  413. for log in logs
  414. ]
  415. @router.delete("/logs")
  416. async def clear_logs(
  417. keep_last: int = Query(default=10, ge=0, le=100, description="Number of recent logs to keep"),
  418. db: AsyncSession = Depends(get_db),
  419. _: User | None = RequirePermissionIfAuthEnabled(Permission.GITHUB_BACKUP),
  420. ):
  421. """Clear backup logs, optionally keeping the most recent entries."""
  422. result = await db.execute(select(GitHubBackupConfig).limit(1))
  423. config = result.scalar_one_or_none()
  424. if not config:
  425. return {"deleted": 0, "message": "No configuration found"}
  426. if keep_last > 0:
  427. # Get IDs to keep
  428. keep_result = await db.execute(
  429. select(GitHubBackupLog.id)
  430. .where(GitHubBackupLog.config_id == config.id)
  431. .order_by(desc(GitHubBackupLog.started_at))
  432. .limit(keep_last)
  433. )
  434. keep_ids = [row[0] for row in keep_result.fetchall()]
  435. if keep_ids:
  436. delete_result = await db.execute(
  437. delete(GitHubBackupLog).where(
  438. GitHubBackupLog.config_id == config.id, GitHubBackupLog.id.not_in(keep_ids)
  439. )
  440. )
  441. else:
  442. delete_result = await db.execute(delete(GitHubBackupLog).where(GitHubBackupLog.config_id == config.id))
  443. else:
  444. delete_result = await db.execute(delete(GitHubBackupLog).where(GitHubBackupLog.config_id == config.id))
  445. await db.commit()
  446. deleted_count = delete_result.rowcount
  447. logger.info("Deleted %s GitHub backup logs (kept %s)", deleted_count, keep_last)
  448. return {"deleted": deleted_count, "message": f"Deleted {deleted_count} logs"}