github_backup.py 18 KB

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