gitea.py 22 KB

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