fix(security): mask forge tokens in logs and disk
CI / test (push) Canceled after 0s

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.
This commit is contained in:
AlexKucera committed 2026-08-11 11:48:32 +02:00
1 parent 7d26e2d4ca
commit 299c061f26
10 files changed
+633 -11

No files matched your search

+3 -1
View File
@@ -24,7 +24,7 @@ Console script: `codeberg-to-gitea`.
## Module map
- `clients.py` — `ApiClient`: bearer auth, transparent pagination (`page`/`limit`), retry on 429/5xx, `get/post/patch/delete`, `raw_get` (binary), `post_multipart` (asset upload).
- `mirror.py` — `git clone --mirror` + `push --mirror`; captures `refs/pull/<n>/head` SHAs and recreates them as target branches `refs/heads/_pr/<n>` (so deleted-branch PRs survive), prunes Forgejo-internal `refs/pull/*` before push, mirrors LFS objects.
- `mirror.py` — `git clone --mirror` + `push --mirror`; captures `refs/pull/<n>/head` SHAs and recreates them as target branches `refs/heads/_pr/<n>` (so deleted-branch PRs survive), prunes Forgejo-internal `refs/pull/*` before push, mirrors LFS objects. Tokens are masked in any `GitError` and scrubbed from the on-disk remote config after each run; the mirror workdir is per-user `0700`.
- `refs.py` — `NumberMap` + `rewrite`: rewrites `#NNN` refs and source issue/PR URLs to the target's fresh number space (source numbers are sparse after deletions).
- `issues.py` — labels, milestones, issues + PRs + comments. Two-pass: create in source-number order (build number map), then rewrite title/body refs + stream comments. PR head falls back to `_pr/<n>` when the source branch is gone.
- `releases.py` — non-draft releases + asset re-upload. Treats a 404 releases endpoint (feature disabled) as "none".
@@ -39,12 +39,14 @@ Console script: `codeberg-to-gitea`.
- Fidelity is intentionally bounded: the public Gitea API stamps issue/PR/comment author (→ migration token user) and timestamps server-side; assignees and reactions are not migrated. Cross-references ARE rewritten to stay correct.
- Repo creation needs the target token to have `write:user` scope; otherwise create the empty repo by hand first (the migrator then populates a fresh target).
- Migration is intentionally one-shot per repo (cutover model): populate a fresh target once, then freeze the source. There is no incremental/delta sync; re-running on a populated target refuses unless `--delete-existing`, which wipes and redoes everything with fresh numbers. Incremental `--update` was considered and deliberately not built.
- Forge API tokens are secrets: the mirror path never lets them reach logs, exceptions, or the persisted `/tmp/cb2gitea-<uid>/.git/config`. Don't reintroduce bare tokens into error messages or stored URLs.
## Verification
- `pytest` (testpaths = `tests`) — refs rewriting, number map, client pagination (mock transport, no network).
- `ruff check .` and `ruff format --check .`.
- End-to-end: `CODEBERG_TOKEN=… GITEA_TOKEN=… codeberg-to-gitea migrate owner/name`.
- CI installs from the committed, hash-verified `uv.lock` (`uv sync --frozen --extra dev`) with Gitea Actions pinned to commit SHAs; run `uv lock` then `uv lock --check` when changing dependencies.
## Child DOX Index
+4
View File
@@ -18,6 +18,7 @@ import typer
from . import __version__
from .clients import ApiClient, ApiError
from .migrate import DEFAULT_SOURCE, DEFAULT_TARGET, MigrationError, migrate_repo
from .mirror import GitError
app = typer.Typer(
name="codeberg-to-gitea",
@@ -81,6 +82,9 @@ def migrate(
except ApiError as exc:
typer.echo(f"API error: {exc}", err=True)
raise typer.Exit(1) from exc
except GitError as exc:
typer.echo(f"git error: {exc}", err=True)
raise typer.Exit(1) from exc
typer.echo(f"✓ migrated {owner}/{name}: {report}")
+2 -1
View File
@@ -9,6 +9,7 @@ to the target's fresh number space.
from __future__ import annotations
import logging
import os
import tempfile
from pathlib import Path
@@ -145,7 +146,7 @@ def migrate_repo(
)
if not skip_git:
workdir = workdir or Path(tempfile.gettempdir()) / "cb2gitea"
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),
+53 -3
View File
@@ -9,6 +9,7 @@ repo.
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
@@ -30,12 +31,51 @@ def _authed(url: str, token: str) -> str:
return urlunsplit(parts._replace(netloc=f"{userinfo}@{parts.netloc}"))
_TOKEN_RE = re.compile(r"(oauth2:)[^@]+(@)")
def _redact(text: str) -> str:
"""Mask any embedded ``oauth2:<token>`` so secrets never reach logs/exceptions."""
return _TOKEN_RE.sub(r"\1***\2", text)
def _bare(url: str) -> str:
"""Strip an ``oauth2:<token>@`` userinfo, returning the bare URL."""
return _TOKEN_RE.sub("", url)
def _scrub_remote_tokens(bare: Path) -> None:
"""Rewrite token-bearing remote URLs in the bare config to bare form.
The mirror is left on disk for inspection / re-push; strip the embedded
``oauth2:<token>`` so it isn't persisted in plaintext in ``.git/config``.
A re-run re-injects auth via :func:`_authed`, so scrubbing is safe. Best-effort.
"""
listing = subprocess.run( # noqa: S603 - argv list, no shell
["git", "--git-dir", str(bare), "remote", "-v"], capture_output=True, text=True
)
for line in listing.stdout.splitlines():
parts = line.split("\t")
if len(parts) < 2:
continue
name = parts[0]
url = parts[1].split(" ")[0]
if "oauth2:" in url:
subprocess.run( # noqa: S603 - argv list, no shell
["git", "--git-dir", str(bare), "remote", "set-url", name, _bare(url)],
capture_output=True,
)
def _run(cmd: list[str], cwd: Path | None = None) -> None:
proc = subprocess.run( # noqa: S603 - argv list, no shell
cmd, cwd=cwd, capture_output=True, text=True
)
if proc.returncode != 0:
raise GitError(f"git failed ({proc.returncode}): {' '.join(cmd)}\n{proc.stderr.strip()}")
raise GitError(
f"git failed ({proc.returncode}): {' '.join(_redact(a) for a in cmd)}"
f"\n{_redact(proc.stderr.strip())}"
)
def _run_capture(cmd: list[str], cwd: Path | None = None) -> str:
@@ -44,7 +84,10 @@ def _run_capture(cmd: list[str], cwd: Path | None = None) -> str:
cmd, cwd=cwd, capture_output=True, text=True
)
if proc.returncode != 0:
raise GitError(f"git failed ({proc.returncode}): {' '.join(cmd)}\n{proc.stderr.strip()}")
raise GitError(
f"git failed ({proc.returncode}): {' '.join(_redact(a) for a in cmd)}"
f"\n{_redact(proc.stderr.strip())}"
)
return proc.stdout
@@ -125,6 +168,10 @@ def mirror_repo(
clone is left there (useful for inspection / re-push).
"""
workdir.mkdir(parents=True, exist_ok=True)
try:
workdir.chmod(0o700) # private even on a shared /tmp
except OSError:
pass
bare = workdir / (Path(source_url).name.removesuffix(".git") + ".git")
src = _authed(source_url, source_token)
@@ -173,11 +220,14 @@ def mirror_repo(
_run(["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"])
lfs_pushed = True
_scrub_remote_tokens(bare)
return {"bare": str(bare), "lfs_pushed": lfs_pushed, "pr_head_branches": len(pull_heads)}
if __name__ == "__main__": # self-check — URL auth only, no network
if __name__ == "__main__": # self-check — URL auth + redaction, no network
url = _authed("https://codeberg.org/AlexKucera/helm.git", "t ok@en")
assert url == "https://oauth2:t%20ok%40en@codeberg.org/AlexKucera/helm.git", url
assert _authed("https://x/o.git", "") == "https://x/o.git"
assert _redact(url) == "https://oauth2:***@codeberg.org/AlexKucera/helm.git", _redact(url)
assert _bare(url) == "https://codeberg.org/AlexKucera/helm.git", _bare(url)
print("mirror self-check ok:", url)