github_backup.py 17 KB

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