gitea.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. """Gitea backend — overrides GitHubBackend where Gitea's API diverges."""
  2. import base64
  3. import json
  4. import logging
  5. import re
  6. from datetime import datetime, timezone
  7. import httpx
  8. from backend.app.services.git_providers.github import GitHubBackend
  9. logger = logging.getLogger(__name__)
  10. class GiteaBackend(GitHubBackend):
  11. """Backend for Gitea instances.
  12. Gitea's Git Data API (/api/v1/repos/{owner}/{repo}/git/...) is *mostly*
  13. compatible with GitHub's, but diverges on three points that broke real-world
  14. backups (#1224, #1225, #1239):
  15. 1. ``GET /git/refs/heads/{branch}`` returns a *list* of matching refs even
  16. when only one matches; GitHub returns a single object. The push paths
  17. below extract the SHA via ``_ref_sha()`` instead of the GitHub-style
  18. ``["object"]["sha"]`` chain.
  19. 2. The Git Data API (blobs/trees/commits/refs) refuses writes against an
  20. empty repository — every blob POST returns 404 until the repo has at
  21. least one commit. ``_create_initial_commit()`` is overridden to use the
  22. Contents API, which seeds the branch + initial commit in a single call.
  23. 3. The Git Data API does not support atomic multi-file commits — each file
  24. requires a separate blob POST followed by a tree/commit/ref sequence.
  25. ``push_files()`` is overridden to use the Contents API
  26. (``POST /repos/.../contents`` with a ``files`` array), which commits all
  27. changed files in a single round-trip and avoids partial-commit failures.
  28. """
  29. @staticmethod
  30. def _ref_sha(ref_data) -> str:
  31. """Extract the commit SHA from Gitea's list-shaped ref response."""
  32. if isinstance(ref_data, list):
  33. if not ref_data:
  34. raise ValueError("Empty refs list returned by Gitea API")
  35. return ref_data[0]["object"]["sha"]
  36. return ref_data["object"]["sha"]
  37. @staticmethod
  38. def _commit_tree_sha(commit_data: dict) -> str | None:
  39. """Extract the tree SHA from a commit response.
  40. GitHub's ``GET /git/commits/{sha}`` returns the GitCommit schema with
  41. ``tree`` at the top level. Gitea's same-named endpoint may return the
  42. wrapped Commit schema where ``tree`` lives under ``commit``. Try the
  43. flat shape first (GitHub-compatible deployments and some Gitea/Forgejo
  44. versions) then fall back to the wrapped shape.
  45. """
  46. tree_node = commit_data.get("tree")
  47. if not isinstance(tree_node, dict):
  48. tree_node = (commit_data.get("commit") or {}).get("tree")
  49. if isinstance(tree_node, dict):
  50. return tree_node.get("sha")
  51. return None
  52. # Gitea/Forgejo can be hosted under a URL path prefix (ROOT_URL like
  53. # https://host/gitea), so the repo lives at /<prefix...>/<owner>/<repo>
  54. # rather than at the host root (#2642). Capture the scheme+host+prefix as
  55. # one group and the final two path segments as owner/repo; the lazy prefix
  56. # group is empty for a root-hosted instance. One shared pattern keeps
  57. # parse_repo_url() and get_api_base() from drifting.
  58. _HTTPS_REPO_RE = re.compile(
  59. r"(https?://[\w.\-]+(?::\d+)?(?:/[\w.\-]+)*?)/([\w.\-]{1,100})/([\w.\-]{1,100})(?:\.git)?/?$"
  60. )
  61. def parse_repo_url(self, url: str) -> tuple[str, str]:
  62. """Return (owner, repo) — accepts both https:// and http:// for self-hosted instances."""
  63. if not url or len(url) > 500:
  64. raise ValueError("Invalid Git URL: URL too long or empty")
  65. match = self._HTTPS_REPO_RE.match(url)
  66. if match:
  67. return match.group(2), match.group(3).removesuffix(".git")
  68. match = re.match(
  69. r"git@[\w.\-]+:([\w.\-]{1,100})/([\w.\-]{1,100})(?:\.git)?$",
  70. url,
  71. )
  72. if match:
  73. return match.group(1), match.group(2).removesuffix(".git")
  74. raise ValueError(f"Cannot parse repository URL: {url}")
  75. def get_api_base(self, repo_url: str) -> str:
  76. """Derive API base from the repository URL's scheme, host and any path prefix."""
  77. match = self._HTTPS_REPO_RE.match(repo_url)
  78. if match:
  79. return f"{match.group(1)}/api/v1"
  80. raise ValueError(f"Cannot derive API base from URL: {repo_url}")
  81. def get_headers(self, token: str) -> dict:
  82. headers = super().get_headers(token)
  83. headers["Accept"] = "application/json"
  84. return headers
  85. async def _blob_shas_at(
  86. self,
  87. client: httpx.AsyncClient,
  88. headers: dict,
  89. api_base: str,
  90. owner: str,
  91. repo: str,
  92. ref: str,
  93. ) -> tuple[dict[str, str] | None, str]:
  94. """Paged override of GitHub's single-GET tree read (#2656).
  95. Divergence four, alongside the three in the class docstring. GitHub's
  96. recursive trees endpoint is not paginated and signals overflow with
  97. ``truncated: true``, which the inherited implementation hard-fails on.
  98. Gitea and Forgejo *do* page the same endpoint — ``page``/``per_page``,
  99. with ``total_count`` alongside the tree — so the inherited version would
  100. read only the first page and then report every category beyond it as
  101. absent from the commit. A restore that silently skips categories is the
  102. exact failure the GitHub version refuses to allow, so this pages instead.
  103. The cap mirrors GitLab's: reaching it means there are more pages, and
  104. that is a failure rather than a partial result.
  105. """
  106. blobs: dict[str, str] = {}
  107. page = 1
  108. while page <= 50:
  109. response = await client.get(
  110. f"{api_base}/repos/{owner}/{repo}/git/trees/{ref}",
  111. headers=headers,
  112. params={"recursive": "true", "page": page, "per_page": 1000},
  113. )
  114. if response.status_code == 404:
  115. return None, f"Commit or tree '{ref}' not found in the repository"
  116. if response.status_code != 200:
  117. return None, (
  118. f"Failed to list tree (HTTP {response.status_code}): {self._truncated_response_text(response)}"
  119. )
  120. try:
  121. data = response.json()
  122. except ValueError:
  123. return None, "Non-JSON response listing tree"
  124. if not isinstance(data, dict):
  125. return None, "Unexpected shape listing tree"
  126. entries = data.get("tree")
  127. if not isinstance(entries, list):
  128. entries = []
  129. for item in entries:
  130. if not isinstance(item, dict) or item.get("type") != "blob":
  131. continue
  132. path, sha = item.get("path"), item.get("sha")
  133. if isinstance(path, str) and isinstance(sha, str) and path and sha:
  134. blobs[path] = sha
  135. # total_count counts every entry, trees included, so compare against
  136. # what this page returned rather than against len(blobs).
  137. total = data.get("total_count")
  138. seen = (page - 1) * 1000 + len(entries)
  139. if not isinstance(total, int) or seen >= total or not entries:
  140. return blobs, ""
  141. page += 1
  142. return None, (
  143. "Repository tree exceeds the listing limit, so the backup contents cannot be "
  144. "enumerated reliably. Rotate the backup repository."
  145. )
  146. async def push_files(
  147. self,
  148. repo_url: str,
  149. token: str,
  150. branch: str,
  151. files: dict,
  152. client: httpx.AsyncClient,
  153. _allow_branch_create: bool = True,
  154. ) -> dict:
  155. """Push files via the Git Data API, normalising Gitea's list-shaped ref response."""
  156. try:
  157. owner, repo = self.parse_repo_url(repo_url)
  158. api_base = self.get_api_base(repo_url)
  159. headers = self.get_headers(token)
  160. ref_response = await client.get(f"{api_base}/repos/{owner}/{repo}/git/refs/heads/{branch}", headers=headers)
  161. if ref_response.status_code == 404:
  162. if not _allow_branch_create:
  163. return {
  164. "status": "failed",
  165. "message": (
  166. f"Branch '{branch}' not found after creation — possible replication lag. "
  167. "The next scheduled backup will retry."
  168. ),
  169. }
  170. return await self._create_branch_and_push(
  171. client, headers, api_base, owner, repo, branch, files, repo_url, token
  172. )
  173. if ref_response.status_code != 200:
  174. return {
  175. "status": "failed",
  176. "message": f"Failed to get branch ref: {ref_response.status_code}",
  177. "error": self._truncated_response_text(ref_response),
  178. }
  179. current_commit_sha = self._ref_sha(ref_response.json())
  180. commit_response = await client.get(
  181. f"{api_base}/repos/{owner}/{repo}/git/commits/{current_commit_sha}", headers=headers
  182. )
  183. if commit_response.status_code != 200:
  184. msg = f"Failed to get current commit (HTTP {commit_response.status_code}): {self._truncated_response_text(commit_response)}"
  185. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  186. return {"status": "failed", "message": msg}
  187. current_tree_sha = self._commit_tree_sha(commit_response.json())
  188. if not current_tree_sha:
  189. msg = (
  190. f"Failed to extract tree SHA from commit response: {self._truncated_response_text(commit_response)}"
  191. )
  192. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  193. return {"status": "failed", "message": msg}
  194. tree_response = await client.get(
  195. f"{api_base}/repos/{owner}/{repo}/git/trees/{current_tree_sha}?recursive=1", headers=headers
  196. )
  197. if tree_response.status_code != 200:
  198. msg = f"Failed to list existing tree (HTTP {tree_response.status_code}): {self._truncated_response_text(tree_response)}"
  199. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  200. return {"status": "failed", "message": msg, "error": self._truncated_response_text(tree_response)}
  201. tree_data = tree_response.json()
  202. # Gitea's tree API can report ``truncated: true`` for large
  203. # listings; if we honour the partial map, the dedup check misses
  204. # and every file gets re-uploaded each run.
  205. if tree_data.get("truncated"):
  206. msg = (
  207. "Repository tree exceeds the Gitea API listing limit (truncated=true). "
  208. "Rotate the backup repository to avoid silent file-by-file churn on every backup."
  209. )
  210. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  211. return {"status": "failed", "message": msg}
  212. existing_files: dict[str, str] = {}
  213. for item in tree_data.get("tree", []):
  214. if item.get("type") != "blob":
  215. continue
  216. path, sha = item.get("path"), item.get("sha")
  217. if not path or not sha:
  218. logger.warning("push_files: skipping malformed tree entry: %s", item)
  219. continue
  220. existing_files[path] = sha
  221. api_files = []
  222. files_changed = 0
  223. for path, content in files.items():
  224. content_str = json.dumps(content, indent=2, default=str)
  225. content_bytes = content_str.encode("utf-8")
  226. content_b64 = base64.b64encode(content_bytes).decode()
  227. content_sha = self._blob_sha(content_bytes)
  228. if path in existing_files:
  229. if existing_files[path] == content_sha:
  230. continue
  231. api_files.append(
  232. {"operation": "update", "path": path, "content": content_b64, "sha": existing_files[path]}
  233. )
  234. else:
  235. api_files.append({"operation": "create", "path": path, "content": content_b64})
  236. files_changed += 1
  237. if not api_files:
  238. return {"status": "skipped", "message": "No changes to commit", "commit_sha": None, "files_changed": 0}
  239. commit_message = f"Bambuddy backup - {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}"
  240. response = await client.post(
  241. f"{api_base}/repos/{owner}/{repo}/contents",
  242. headers=headers,
  243. json={"branch": branch, "message": commit_message, "files": api_files},
  244. )
  245. if response.status_code == 404:
  246. return {
  247. "status": "failed",
  248. "message": "Contents API endpoint not found — your Gitea instance may be older than v1.18 or the API may be disabled by an administrator (POST /contents returned 404)",
  249. }
  250. if response.status_code == 409:
  251. return {
  252. "status": "failed",
  253. "message": (
  254. "Conflict committing files — the branch likely advanced concurrently "
  255. "(web-UI edit, another backup run, or path-vs-tree collision). "
  256. "The next scheduled backup will re-read the current tree and resolve this."
  257. ),
  258. }
  259. if response.status_code not in (200, 201):
  260. return {
  261. "status": "failed",
  262. "message": f"Backup commit failed: {self._truncated_response_text(response)}",
  263. }
  264. commit_sha = (response.json().get("commit") or {}).get("sha")
  265. message = (
  266. f"Backup successful - {files_changed} files updated"
  267. if commit_sha
  268. else f"Backup successful - {files_changed} files updated (commit SHA not reported by server)"
  269. )
  270. return {
  271. "status": "success",
  272. "message": message,
  273. "commit_sha": commit_sha,
  274. "files_changed": files_changed,
  275. }
  276. except Exception as e:
  277. logger.exception("push_files failed for %s branch=%s", repo_url, branch)
  278. return {"status": "failed", "message": str(e), "error": str(e)}
  279. async def _create_branch_and_push(
  280. self,
  281. client: httpx.AsyncClient,
  282. headers: dict,
  283. api_base: str,
  284. owner: str,
  285. repo: str,
  286. branch: str,
  287. files: dict,
  288. repo_url: str,
  289. token: str,
  290. ) -> dict:
  291. """Create branch (from default branch or as initial commit) then push."""
  292. try:
  293. repo_response = await client.get(f"{api_base}/repos/{owner}/{repo}", headers=headers)
  294. if repo_response.status_code != 200:
  295. msg = f"Failed to get repo info (HTTP {repo_response.status_code}): {self._truncated_response_text(repo_response)}"
  296. logger.warning("_create_branch_and_push %s/%s: %s", owner, repo, msg)
  297. return {"status": "failed", "message": msg}
  298. default_branch = repo_response.json().get("default_branch", "main")
  299. # GET the default branch to confirm the repo is non-empty; SHA is intentionally unused —
  300. # POST /branches takes a branch name, not a SHA.
  301. ref_response = await client.get(
  302. f"{api_base}/repos/{owner}/{repo}/git/refs/heads/{default_branch}", headers=headers
  303. )
  304. if ref_response.status_code != 200:
  305. return await self._create_initial_commit(client, headers, api_base, owner, repo, branch, files)
  306. create_ref = await client.post(
  307. f"{api_base}/repos/{owner}/{repo}/branches",
  308. headers=headers,
  309. json={"new_branch_name": branch, "old_ref_name": default_branch},
  310. )
  311. if create_ref.status_code == 403:
  312. msg = f"Permission denied creating branch '{branch}' — token may lack write access to this repository"
  313. logger.warning("_create_branch_and_push %s/%s: 403 %s", owner, repo, msg)
  314. return {"status": "failed", "message": msg}
  315. if create_ref.status_code == 409:
  316. msg = f"Branch '{branch}' already exists (possible race condition)"
  317. logger.warning("_create_branch_and_push %s/%s: 409 %s", owner, repo, msg)
  318. return {"status": "failed", "message": msg}
  319. if create_ref.status_code != 201:
  320. msg = f"Failed to create branch '{branch}' (HTTP {create_ref.status_code}): {self._truncated_response_text(create_ref)}"
  321. logger.warning("_create_branch_and_push %s/%s: %s", owner, repo, msg)
  322. return {"status": "failed", "message": msg}
  323. logger.info("Re-entering push_files after branch create %s/%s -> %s", owner, repo, branch)
  324. return await self.push_files(repo_url, token, branch, files, client, _allow_branch_create=False)
  325. except Exception as e:
  326. logger.exception("_create_branch_and_push failed for %s/%s branch=%s", owner, repo, branch)
  327. return {"status": "failed", "message": str(e), "error": str(e)}
  328. async def _create_initial_commit(
  329. self,
  330. client: httpx.AsyncClient,
  331. headers: dict,
  332. api_base: str,
  333. owner: str,
  334. repo: str,
  335. branch: str,
  336. files: dict,
  337. ) -> dict:
  338. """Seed an empty Gitea repository via the Contents API.
  339. Gitea's Git Data API requires the repository to have at least one
  340. commit before it accepts blob/tree/commit writes; on an empty repo
  341. every ``POST /git/blobs`` returns 404. The Contents API is the
  342. documented bootstrap path: a single ``POST /repos/{owner}/{repo}/contents``
  343. with a ``files`` array creates the initial commit and the target
  344. branch in one round-trip (Gitea 1.18+, Forgejo all versions).
  345. """
  346. try:
  347. if not files:
  348. return {"status": "skipped", "message": "No files to commit", "commit_sha": None, "files_changed": 0}
  349. api_files = []
  350. for path, content in files.items():
  351. content_str = json.dumps(content, indent=2, default=str)
  352. content_b64 = base64.b64encode(content_str.encode("utf-8")).decode()
  353. api_files.append({"operation": "create", "path": path, "content": content_b64})
  354. commit_message = f"Initial Bambuddy backup - {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}"
  355. body = {
  356. "branch": branch,
  357. "new_branch": branch,
  358. "message": commit_message,
  359. "files": api_files,
  360. }
  361. response = await client.post(
  362. f"{api_base}/repos/{owner}/{repo}/contents",
  363. headers=headers,
  364. json=body,
  365. )
  366. if response.status_code not in (200, 201):
  367. return {
  368. "status": "failed",
  369. "message": f"Failed to create initial commit: {self._truncated_response_text(response)}",
  370. }
  371. data = response.json()
  372. commit_sha = (data.get("commit") or {}).get("sha")
  373. message = (
  374. f"Initial backup created - {len(files)} files"
  375. if commit_sha
  376. else f"Initial backup created - {len(files)} files (commit SHA not reported by server)"
  377. )
  378. return {
  379. "status": "success",
  380. "message": message,
  381. "commit_sha": commit_sha,
  382. "files_changed": len(files),
  383. }
  384. except Exception as e:
  385. logger.exception("_create_initial_commit failed for %s/%s branch=%s", owner, repo, branch)
  386. return {"status": "failed", "message": str(e), "error": str(e)}