gitea.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. Because the page size is
  105. the server's choice rather than ours (see below), the cap is a page count
  106. and not a file count.
  107. """
  108. blobs: dict[str, str] = {}
  109. seen = 0
  110. page = 1
  111. while page <= 50:
  112. response = await client.get(
  113. f"{api_base}/repos/{owner}/{repo}/git/trees/{ref}",
  114. headers=headers,
  115. params={"recursive": "true", "page": page, "per_page": 1000},
  116. )
  117. if response.status_code == 404:
  118. return None, f"Commit or tree '{ref}' not found in the repository"
  119. if response.status_code != 200:
  120. return None, (
  121. f"Failed to list tree (HTTP {response.status_code}): {self._truncated_response_text(response)}"
  122. )
  123. try:
  124. data = response.json()
  125. except ValueError:
  126. return None, "Non-JSON response listing tree"
  127. if not isinstance(data, dict):
  128. return None, "Unexpected shape listing tree"
  129. entries = data.get("tree")
  130. if not isinstance(entries, list):
  131. entries = []
  132. for item in entries:
  133. if not isinstance(item, dict) or item.get("type") != "blob":
  134. continue
  135. path, sha = item.get("path"), item.get("sha")
  136. if isinstance(path, str) and isinstance(sha, str) and path and sha:
  137. blobs[path] = sha
  138. # total_count counts every entry, trees included, so compare against
  139. # what came back rather than against len(blobs).
  140. #
  141. # Count what the server actually returned, never the per_page we
  142. # asked for: Gitea clamps per_page to MAX_RESPONSE_ITEMS, which
  143. # defaults to 50. Deriving the offset from the requested 1000 made
  144. # page 2 report 1050 entries seen, which clears any total_count below
  145. # that — so the loop stopped and returned the first two pages of a
  146. # much larger tree as a success. The restore then read every missing
  147. # path as "category not present in this commit" and skipped it
  148. # silently, the exact failure this override exists to prevent.
  149. total = data.get("total_count")
  150. seen += len(entries)
  151. if not isinstance(total, int) or seen >= total or not entries:
  152. return blobs, ""
  153. page += 1
  154. return None, (
  155. "Repository tree exceeds the listing limit, so the backup contents cannot be "
  156. "enumerated reliably. Rotate the backup repository."
  157. )
  158. async def push_files(
  159. self,
  160. repo_url: str,
  161. token: str,
  162. branch: str,
  163. files: dict,
  164. client: httpx.AsyncClient,
  165. _allow_branch_create: bool = True,
  166. ) -> dict:
  167. """Push files via the Git Data API, normalising Gitea's list-shaped ref response."""
  168. try:
  169. owner, repo = self.parse_repo_url(repo_url)
  170. api_base = self.get_api_base(repo_url)
  171. headers = self.get_headers(token)
  172. ref_response = await client.get(f"{api_base}/repos/{owner}/{repo}/git/refs/heads/{branch}", headers=headers)
  173. if ref_response.status_code == 404:
  174. if not _allow_branch_create:
  175. return {
  176. "status": "failed",
  177. "message": (
  178. f"Branch '{branch}' not found after creation — possible replication lag. "
  179. "The next scheduled backup will retry."
  180. ),
  181. }
  182. return await self._create_branch_and_push(
  183. client, headers, api_base, owner, repo, branch, files, repo_url, token
  184. )
  185. if ref_response.status_code != 200:
  186. return {
  187. "status": "failed",
  188. "message": f"Failed to get branch ref: {ref_response.status_code}",
  189. "error": self._truncated_response_text(ref_response),
  190. }
  191. current_commit_sha = self._ref_sha(ref_response.json())
  192. commit_response = await client.get(
  193. f"{api_base}/repos/{owner}/{repo}/git/commits/{current_commit_sha}", headers=headers
  194. )
  195. if commit_response.status_code != 200:
  196. msg = f"Failed to get current commit (HTTP {commit_response.status_code}): {self._truncated_response_text(commit_response)}"
  197. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  198. return {"status": "failed", "message": msg}
  199. current_tree_sha = self._commit_tree_sha(commit_response.json())
  200. if not current_tree_sha:
  201. msg = (
  202. f"Failed to extract tree SHA from commit response: {self._truncated_response_text(commit_response)}"
  203. )
  204. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  205. return {"status": "failed", "message": msg}
  206. tree_response = await client.get(
  207. f"{api_base}/repos/{owner}/{repo}/git/trees/{current_tree_sha}?recursive=1", headers=headers
  208. )
  209. if tree_response.status_code != 200:
  210. msg = f"Failed to list existing tree (HTTP {tree_response.status_code}): {self._truncated_response_text(tree_response)}"
  211. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  212. return {"status": "failed", "message": msg, "error": self._truncated_response_text(tree_response)}
  213. tree_data = tree_response.json()
  214. # Gitea's tree API can report ``truncated: true`` for large
  215. # listings; if we honour the partial map, the dedup check misses
  216. # and every file gets re-uploaded each run.
  217. if tree_data.get("truncated"):
  218. msg = (
  219. "Repository tree exceeds the Gitea API listing limit (truncated=true). "
  220. "Rotate the backup repository to avoid silent file-by-file churn on every backup."
  221. )
  222. logger.warning("push_files %s/%s: %s", owner, repo, msg)
  223. return {"status": "failed", "message": msg}
  224. existing_files: dict[str, str] = {}
  225. for item in tree_data.get("tree", []):
  226. if item.get("type") != "blob":
  227. continue
  228. path, sha = item.get("path"), item.get("sha")
  229. if not path or not sha:
  230. logger.warning("push_files: skipping malformed tree entry: %s", item)
  231. continue
  232. existing_files[path] = sha
  233. api_files = []
  234. files_changed = 0
  235. for path, content in files.items():
  236. content_str = json.dumps(content, indent=2, default=str)
  237. content_bytes = content_str.encode("utf-8")
  238. content_b64 = base64.b64encode(content_bytes).decode()
  239. content_sha = self._blob_sha(content_bytes)
  240. if path in existing_files:
  241. if existing_files[path] == content_sha:
  242. continue
  243. api_files.append(
  244. {"operation": "update", "path": path, "content": content_b64, "sha": existing_files[path]}
  245. )
  246. else:
  247. api_files.append({"operation": "create", "path": path, "content": content_b64})
  248. files_changed += 1
  249. if not api_files:
  250. return {"status": "skipped", "message": "No changes to commit", "commit_sha": None, "files_changed": 0}
  251. commit_message = f"Bambuddy backup - {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}"
  252. response = await client.post(
  253. f"{api_base}/repos/{owner}/{repo}/contents",
  254. headers=headers,
  255. json={"branch": branch, "message": commit_message, "files": api_files},
  256. )
  257. if response.status_code == 404:
  258. return {
  259. "status": "failed",
  260. "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)",
  261. }
  262. if response.status_code == 409:
  263. return {
  264. "status": "failed",
  265. "message": (
  266. "Conflict committing files — the branch likely advanced concurrently "
  267. "(web-UI edit, another backup run, or path-vs-tree collision). "
  268. "The next scheduled backup will re-read the current tree and resolve this."
  269. ),
  270. }
  271. if response.status_code not in (200, 201):
  272. return {
  273. "status": "failed",
  274. "message": f"Backup commit failed: {self._truncated_response_text(response)}",
  275. }
  276. commit_sha = (response.json().get("commit") or {}).get("sha")
  277. message = (
  278. f"Backup successful - {files_changed} files updated"
  279. if commit_sha
  280. else f"Backup successful - {files_changed} files updated (commit SHA not reported by server)"
  281. )
  282. return {
  283. "status": "success",
  284. "message": message,
  285. "commit_sha": commit_sha,
  286. "files_changed": files_changed,
  287. }
  288. except Exception as e:
  289. logger.exception("push_files failed for %s branch=%s", repo_url, branch)
  290. return {"status": "failed", "message": str(e), "error": str(e)}
  291. async def _create_branch_and_push(
  292. self,
  293. client: httpx.AsyncClient,
  294. headers: dict,
  295. api_base: str,
  296. owner: str,
  297. repo: str,
  298. branch: str,
  299. files: dict,
  300. repo_url: str,
  301. token: str,
  302. ) -> dict:
  303. """Create branch (from default branch or as initial commit) then push."""
  304. try:
  305. repo_response = await client.get(f"{api_base}/repos/{owner}/{repo}", headers=headers)
  306. if repo_response.status_code != 200:
  307. msg = f"Failed to get repo info (HTTP {repo_response.status_code}): {self._truncated_response_text(repo_response)}"
  308. logger.warning("_create_branch_and_push %s/%s: %s", owner, repo, msg)
  309. return {"status": "failed", "message": msg}
  310. default_branch = repo_response.json().get("default_branch", "main")
  311. # GET the default branch to confirm the repo is non-empty; SHA is intentionally unused —
  312. # POST /branches takes a branch name, not a SHA.
  313. ref_response = await client.get(
  314. f"{api_base}/repos/{owner}/{repo}/git/refs/heads/{default_branch}", headers=headers
  315. )
  316. if ref_response.status_code != 200:
  317. return await self._create_initial_commit(client, headers, api_base, owner, repo, branch, files)
  318. create_ref = await client.post(
  319. f"{api_base}/repos/{owner}/{repo}/branches",
  320. headers=headers,
  321. json={"new_branch_name": branch, "old_ref_name": default_branch},
  322. )
  323. if create_ref.status_code == 403:
  324. msg = f"Permission denied creating branch '{branch}' — token may lack write access to this repository"
  325. logger.warning("_create_branch_and_push %s/%s: 403 %s", owner, repo, msg)
  326. return {"status": "failed", "message": msg}
  327. if create_ref.status_code == 409:
  328. msg = f"Branch '{branch}' already exists (possible race condition)"
  329. logger.warning("_create_branch_and_push %s/%s: 409 %s", owner, repo, msg)
  330. return {"status": "failed", "message": msg}
  331. if create_ref.status_code != 201:
  332. msg = f"Failed to create branch '{branch}' (HTTP {create_ref.status_code}): {self._truncated_response_text(create_ref)}"
  333. logger.warning("_create_branch_and_push %s/%s: %s", owner, repo, msg)
  334. return {"status": "failed", "message": msg}
  335. logger.info("Re-entering push_files after branch create %s/%s -> %s", owner, repo, branch)
  336. return await self.push_files(repo_url, token, branch, files, client, _allow_branch_create=False)
  337. except Exception as e:
  338. logger.exception("_create_branch_and_push failed for %s/%s branch=%s", owner, repo, branch)
  339. return {"status": "failed", "message": str(e), "error": str(e)}
  340. async def _create_initial_commit(
  341. self,
  342. client: httpx.AsyncClient,
  343. headers: dict,
  344. api_base: str,
  345. owner: str,
  346. repo: str,
  347. branch: str,
  348. files: dict,
  349. ) -> dict:
  350. """Seed an empty Gitea repository via the Contents API.
  351. Gitea's Git Data API requires the repository to have at least one
  352. commit before it accepts blob/tree/commit writes; on an empty repo
  353. every ``POST /git/blobs`` returns 404. The Contents API is the
  354. documented bootstrap path: a single ``POST /repos/{owner}/{repo}/contents``
  355. with a ``files`` array creates the initial commit and the target
  356. branch in one round-trip (Gitea 1.18+, Forgejo all versions).
  357. """
  358. try:
  359. if not files:
  360. return {"status": "skipped", "message": "No files to commit", "commit_sha": None, "files_changed": 0}
  361. api_files = []
  362. for path, content in files.items():
  363. content_str = json.dumps(content, indent=2, default=str)
  364. content_b64 = base64.b64encode(content_str.encode("utf-8")).decode()
  365. api_files.append({"operation": "create", "path": path, "content": content_b64})
  366. commit_message = f"Initial Bambuddy backup - {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}"
  367. body = {
  368. "branch": branch,
  369. "new_branch": branch,
  370. "message": commit_message,
  371. "files": api_files,
  372. }
  373. response = await client.post(
  374. f"{api_base}/repos/{owner}/{repo}/contents",
  375. headers=headers,
  376. json=body,
  377. )
  378. if response.status_code not in (200, 201):
  379. return {
  380. "status": "failed",
  381. "message": f"Failed to create initial commit: {self._truncated_response_text(response)}",
  382. }
  383. data = response.json()
  384. commit_sha = (data.get("commit") or {}).get("sha")
  385. message = (
  386. f"Initial backup created - {len(files)} files"
  387. if commit_sha
  388. else f"Initial backup created - {len(files)} files (commit SHA not reported by server)"
  389. )
  390. return {
  391. "status": "success",
  392. "message": message,
  393. "commit_sha": commit_sha,
  394. "files_changed": len(files),
  395. }
  396. except Exception as e:
  397. logger.exception("_create_initial_commit failed for %s/%s branch=%s", owner, repo, branch)
  398. return {"status": "failed", "message": str(e), "error": str(e)}