Files
codeberg-to-gitea-migrator/src/codeberg_to_gitea_migrator/migrate.py
T
AlexKucera 299c061f26
CI / test (push) Canceled after 0s
fix(security): mask forge tokens in logs and disk
Close two token-leak paths in the git mirror and harden the supply
chain per the OWASP audit (audit/2026-08-11/security-report.md).

Runtime fixes:
- mirror GitError masks the embedded oauth2:<token> in both the
  failing command line and git's stderr before raising; cli now
  catches GitError with a clean message instead of an uncaught
  traceback that printed the live token.
- Scrub token-bearing remote URLs from the bare config at the end
  of each run so tokens aren't persisted in .git/config.
- Default mirror workdir is per-user 0700 (/tmp/cb2gitea-<uid>),
  not a world-readable /tmp/cb2gitea.

Supply chain:
- Commit uv.lock; CI installs via uv sync --frozen (hash-verified).
- Pin Gitea Actions to commit SHAs, not mutable @vN tags.
- Pin the ruff rule set and exclude audit/ for reproducible linting.

Adds tests/test_mirror.py for the redaction helpers.
2026-08-11 11:48:32 +02:00

173 lines
6.1 KiB
Python

"""End-to-end migration orchestration.
``migrate_repo`` ties the pieces together: open both forge clients, (re)create
the target repository, mirror git data, then replay labels, milestones,
issues+PRs (+comments), and releases (+assets). Cross-references are rewritten
to the target's fresh number space.
"""
from __future__ import annotations
import logging
import os
import tempfile
from pathlib import Path
from .clients import ApiClient, ApiError
from .issues import RefCtx, migrate_issues_and_prs, migrate_labels, migrate_milestones
from .mirror import mirror_repo
from .refs import NumberMap
from .releases import migrate_releases
log = logging.getLogger(__name__)
DEFAULT_SOURCE = "https://codeberg.org"
DEFAULT_TARGET = "https://git.babylondreams.de"
class MigrationError(RuntimeError):
pass
def _git_url(web_root: str, owner: str, name: str) -> str:
return f"{web_root.rstrip('/')}/{owner}/{name}.git"
def _target_exists(tgt: ApiClient, owner: str, name: str) -> dict | None:
"""Return the target repo metadata, or None if it doesn't exist."""
try:
return tgt.get(f"/repos/{owner}/{name}")
except ApiError as exc:
if exc.status == 404:
return None
raise
def _is_fresh(tgt: ApiClient, owner: str, name: str) -> bool:
"""A repo counts as fresh (safe to populate) when it has no issues/PRs yet."""
issues = tgt.get_all(f"/repos/{owner}/{name}/issues", state="all", type="issues")
pulls = tgt.get_all(f"/repos/{owner}/{name}/pulls", state="all")
return not issues and not pulls
def _ensure_target_repo(
tgt: ApiClient, owner: str, name: str, source_meta: dict, *, delete_existing: bool
) -> None:
"""Ensure a fresh target repo exists to populate.
Repo creation is a privileged step: Gitea's ``POST /user/repos`` needs the
``write:user`` scope, which migration tokens often lack. So the repo may be
pre-created by hand (web UI) — we then just populate it. If the target
already exists *and* isn't fresh, we refuse unless ``--delete-existing``
(re-running would duplicate issues/PRs, which the API can't upsert).
"""
existing = _target_exists(tgt, owner, name)
if existing is not None:
if delete_existing:
log.warning("deleting existing target repo %s/%s", owner, name)
try:
tgt.delete(f"/repos/{owner}/{name}")
except ApiError as exc:
raise MigrationError(
f"could not delete {owner}/{name} (token needs admin scope): {exc}"
) from exc
existing = None
elif not _is_fresh(tgt, owner, name):
raise MigrationError(
f"target repo {owner}/{name} already exists and isn't empty "
"(has issues/PRs); re-running would duplicate them. "
"Delete it first, then re-run."
)
else:
log.info("target repo %s/%s already exists (fresh) — populating", owner, name)
if existing is not None:
return
body = {
"name": name,
"description": source_meta.get("description") or "",
"private": bool(source_meta.get("private")),
"default_branch": source_meta.get("default_branch") or "main",
"has_issues": True,
"has_pull_requests": True,
"has_wiki": bool(source_meta.get("has_wiki", False)),
"has_projects": bool(source_meta.get("has_projects", False)),
"auto_init": False,
}
me = tgt.get("/user")
endpoint = "/user/repos" if me.get("login") == owner else f"/orgs/{owner}/repos"
try:
tgt.post(endpoint, body=body)
except ApiError as exc:
if exc.status in (401, 403):
raise MigrationError(
f"cannot create target repo {owner}/{name}: token lacks the needed "
f"scope ({exc.status}). Create the empty repo on Gitea first "
"(web UI), then re-run — the migrator will populate it."
) from exc
raise
log.info("created target repo %s/%s", owner, name)
def migrate_repo(
*,
source_url: str,
target_url: str,
owner: str,
name: str,
source_token: str,
target_token: str,
delete_existing: bool = False,
workdir: Path | None = None,
skip_git: bool = False,
skip_issues: bool = False,
skip_releases: bool = False,
) -> dict:
"""Migrate one repo from source forge to target forge. Returns a report."""
if not source_token or not target_token:
raise MigrationError("both source and target tokens are required")
numbers = NumberMap()
report: dict = {"owner": owner, "name": name}
with (
ApiClient(source_url, source_token) as src,
ApiClient(target_url, target_token) as tgt,
):
source_meta = src.get(f"/repos/{owner}/{name}")
_ensure_target_repo(tgt, owner, name, source_meta, delete_existing=delete_existing)
ref = RefCtx(
numbers=numbers,
source_web_root=src.web_root,
target_web_root=tgt.web_root,
)
if not skip_git:
workdir = workdir or Path(tempfile.gettempdir()) / f"cb2gitea-{os.getuid()}"
git_report = mirror_repo(
source_url=_git_url(src.web_root, owner, name),
target_url=_git_url(tgt.web_root, owner, name),
source_token=source_token,
target_token=target_token,
workdir=workdir,
)
report["git"] = git_report
log.info("git mirror done: %s", git_report)
if not skip_issues:
label_id_map, _name_map = migrate_labels(src, tgt, owner, name)
milestone_map = migrate_milestones(src, tgt, owner, name)
migrate_issues_and_prs(src, tgt, owner, name, label_id_map, milestone_map, ref)
report["labels"] = len(label_id_map)
report["milestones"] = len(milestone_map)
report["issues_prs"] = len(numbers)
if not skip_releases:
report["releases"] = migrate_releases(src, tgt, owner, name, ref)
log.info("migration complete: %s", report)
return report