refactor(migrator): centralize git in GitRunner
CI / test (push) Canceled after 0s

Introduce git.GitRunner as the sole git-op seam: the only place git is
invoked. It owns subprocess execution, per-op timeout, error redaction, and
auth delivery. Forge tokens move off the remote URL entirely onto a
non-persisted per-op http.<host>.extraHeader, so they never reach the
command line, a remote URL, or .git/config.

Rewrite the mirror procedure to drive GitRunner and retire the URL-token
helpers (_authed/_bare/_redact/_scrub_remote_tokens) plus the try/finally
scrub -- their reason to exist vanishes. mirror_repo's signature and report
stay unchanged; cli/migrate import the re-exported GitError/timeout
unchanged. The procedure's ordering invariants are now locked by a
recording-fake test, and an AST guard fails the suite if any git op bypasses
the seam.

Closes the 2026-08-11 audit's HIGH (token in GitError) and MEDIUM (token
in .git/config) at one structural root cause.

Closes #1
This commit is contained in:
AlexKucera committed 2026-08-11 15:36:35 +02:00
1 parent 137734673d
commit 1613ec72b8
10 files changed
+669 -223

No files matched your search

+2
View File
@@ -18,6 +18,8 @@ Project maintainer (Alexander Kucera).
- `test_smoke.py` — package imports + version.
- `test_refs.py` — `#NNN`/URL cross-reference rewrite + `NumberMap`.
- `test_clients.py` — `ApiClient` pagination, param cleaning, 4xx handling, JSON POST, all via `httpx.MockTransport` (no network).
- `test_git.py` — the `GitRunner` seam (auth delivery via non-persisted `extraHeader`, known-secret redaction, timeout/error contract, `ok` never raises) + an AST guard that git is invoked only through `GitRunner`. Driven by a recording exec fake; no git binary, no network.
- `test_mirror.py` — the mirror procedure's ordering invariants (capture → prune → mirror push → PR-head push; LFS gated on the probe) and per-op auth wiring (fetch=source, push=target, local ref ops=none), via a recording exec fake that captures command intent only — never the token.
- Keep tests network-free: never hit live Codeberg/Gitea from the suite. The end-to-end run is a manual CLI invocation, not a test.
## Verification
+176
View File
@@ -0,0 +1,176 @@
"""GitRunner — the sole git-op seam.
Exercised through its external interface via a recording fake of the exec
callable (same "inject a fake of the external dependency" convention as
test_clients.MockTransport). The fake records command intent only — it never
reads ``forge.token``, so no fixture can leak a credential.
"""
from __future__ import annotations
import subprocess
import pytest
from codeberg_to_gitea_migrator.git import (
DEFAULT_GIT_TIMEOUT,
Forge,
GitError,
GitRunner,
_auth_args,
redact,
)
SRC = Forge("https://codeberg.org/o/r.git", "src-secret")
TGT = Forge("https://git.babylondreams.de/o/r.git", "tgt-secret")
def _ok(stdout: str = "") -> subprocess.CompletedProcess:
return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout, stderr="")
class _Fake:
"""Recording exec: captures (cmd, stdin, auth_url); never the token."""
def __init__(self, *, result=_ok(), raise_giterror=False):
self._result = result
self._raise = raise_giterror
self.calls: list[tuple[tuple[str, ...], str | None, str | None]] = []
self.timeouts: list[float] = []
def __call__(self, cmd, *, timeout, stdin, auth):
self.calls.append((tuple(cmd), stdin, auth.url if auth else None))
self.timeouts.append(timeout)
if self._raise:
raise GitError("boom")
return self._result
# --- auth delivery: token composed INSIDE the adapter, never in the URL/cmd ---
def test_auth_args_builds_nonpersisted_extraheader():
# The only place the token appears; matches the REST client's "token <T>" scheme.
assert _auth_args(SRC) == [
"-c",
"http.https://codeberg.org.extraHeader=Authorization: token src-secret",
]
def test_auth_args_matches_host_not_full_repo_path():
# One header covers every repo on the host — long enough to match, short of the path.
assert _auth_args(TGT) == [
"-c",
"http.https://git.babylondreams.de.extraHeader=Authorization: token tgt-secret",
]
def test_runner_passes_auth_to_exec_but_fake_never_sees_token():
fake = _Fake()
runner = GitRunner(timeout=10, exec=fake)
runner.run(["git", "fetch", "origin"], auth=SRC)
cmd, stdin, auth_url = fake.calls[0]
assert cmd == ("git", "fetch", "origin") # clean — no token, no -c
assert stdin is None
assert auth_url == "https://codeberg.org/o/r.git" # forge identity, not its token
def test_runner_no_auth_means_local_op():
fake = _Fake()
runner = GitRunner(exec=fake)
runner.run(["git", "update-ref", "--stdin"], stdin="delete x\n")
assert fake.calls[0] == (("git", "update-ref", "--stdin"), "delete x\n", None)
# --- redaction: known secret first, then legacy oauth2: fallback (story #15) ---
def test_redact_uses_known_secret_for_new_form():
text = "git failed: -c http.https://x.extraHeader=Authorization: token src-secret"
assert "src-secret" not in redact(text, "src-secret")
assert "Authorization: token ***" in redact(text, "src-secret") # scheme label kept
def test_redact_keeps_authorization_label_for_diagnostics():
assert redact("Authorization: token src-secret", "src-secret") == "Authorization: token ***"
def test_redact_falls_back_to_legacy_oauth2_regex_when_secret_not_literal():
# Percent-encoded in a URL → not a literal match; regex still masks it.
assert (
redact("https://oauth2:s3cr3t@host/o.git", "different") == "https://oauth2:***@host/o.git"
)
def test_redact_passes_clean_text_through():
assert redact("https://codeberg.org/o/r.git") == "https://codeberg.org/o/r.git"
# --- error contract: timeout + non-zero raise redacted GitError; ok never raises ---
def test_capture_returns_stdout():
runner = GitRunner(exec=_Fake(result=_ok(stdout="refs/pull/1 abc\n")))
assert runner.capture(["git", "for-each-ref", "refs/pull/"]) == "refs/pull/1 abc\n"
def test_timeout_is_threaded_to_exec():
fake = _Fake()
GitRunner(timeout=42, exec=fake).run(["git", "x"])
assert fake.timeouts == [42] # the per-runner timeout reaches every exec call
assert DEFAULT_GIT_TIMEOUT == 1800.0
def test_ok_returns_false_without_raising_on_failure():
assert GitRunner(exec=_Fake(raise_giterror=True)).ok(["git", "lfs", "version"]) is False
def test_ok_returns_true_on_success():
assert GitRunner(exec=_Fake(result=_ok())).ok(["git", "lfs", "version"]) is True
def test_ok_takes_no_auth():
fake = _Fake()
GitRunner(exec=fake).ok(["git", "lfs", "version"])
assert fake.calls[0][2] is None # the LFS probe is a local version check
def test_run_propagates_giterror():
with pytest.raises(GitError):
GitRunner(exec=_Fake(raise_giterror=True)).run(["git", "x"])
def test_capture_propagates_giterror():
with pytest.raises(GitError):
GitRunner(exec=_Fake(raise_giterror=True)).capture(["git", "x"])
# --- regression guard: no git op may bypass the seam (story #18) ---
def test_git_is_the_sole_subprocess_caller():
"""AST-walk every production module; subprocess may appear only in git.py."""
import ast
import pathlib
import codeberg_to_gitea_migrator
pkg = pathlib.Path(codeberg_to_gitea_migrator.__file__).parent
offenders = []
for src in sorted(pkg.glob("*.py")):
if src.name == "git.py":
continue
tree = ast.parse(src.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module == "subprocess":
offenders.append(f"{src.name}: imports subprocess (use git.GitRunner)")
if (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "subprocess"
):
offenders.append(
f"{src.name}: calls subprocess.{node.func.attr} (use git.GitRunner)"
)
assert not offenders, "git ops must go through git.GitRunner:\n" + "\n".join(offenders)
+162 -21
View File
@@ -1,32 +1,173 @@
"""Redaction helpers keep forge tokens out of error text and stored git config.
"""The git-mirror procedure's ordering invariants.
Pure-function checks (no network): ``_authed`` embeds the token in the URL,
``_redact`` masks it for logs/exceptions, and ``_bare`` strips it for the
on-disk remote config scrub.
Driven through a recording fake of the GitRunner exec callable (no git binary,
no network). The fake records command intent only — ``auth.url``, never
``auth.token`` — so the procedure's correctness (its command *sequence* and
which forge each step authenticates against) is locked without a credential
ever reaching a fixture.
"""
from codeberg_to_gitea_migrator.mirror import _authed, _bare, _redact
from __future__ import annotations
import subprocess
from codeberg_to_gitea_migrator.git import GitError
from codeberg_to_gitea_migrator.mirror import mirror_repo
SRC_URL = "https://codeberg.org/o/r.git"
TGT_URL = "https://git.babylondreams.de/o/r.git"
def test_redact_masks_token_keeps_url_shape():
url = _authed("https://codeberg.org/o/r.git", "s3cr3t")
assert "s3cr3t" not in _redact(url)
assert _redact(url) == "https://oauth2:***@codeberg.org/o/r.git"
def _ok(stdout: str = "") -> subprocess.CompletedProcess:
return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout, stderr="")
def test_bare_strips_userinfo_entirely():
url = _authed("https://codeberg.org/o/r.git", "s3cr3t")
assert _bare(url) == "https://codeberg.org/o/r.git"
class FakeExec:
"""Recording exec: (cmd, stdin, auth_url). Synthesizes for-each-ref output."""
def __init__(
self,
*,
pull_heads: dict[int, str] | None = None,
lfs: bool = True,
target_exists: bool = False,
):
self._pull = dict(pull_heads or {})
self._lfs = lfs
self._target_exists = target_exists
self.calls: list[tuple[tuple[str, ...], str | None, str | None]] = []
def __call__(self, cmd, *, timeout, stdin, auth):
self.calls.append((tuple(cmd), stdin, auth.url if auth else None))
if "for-each-ref" in cmd:
if "--format=%(refname) %(objectname)" in cmd: # pull-head capture
out = "\n".join(f"refs/pull/{n}/head {s}" for n, s in sorted(self._pull.items()))
return _ok(out)
return _ok("\n".join(f"refs/pull/{n}/head" for n in sorted(self._pull))) # prune list
if "lfs" in cmd and "version" in cmd:
if not self._lfs:
raise GitError("no git-lfs")
return _ok()
if "remote" in cmd and "add" in cmd and "target" in cmd and self._target_exists:
raise GitError("remote target already exists")
return _ok()
def cmds(self) -> list[tuple[str, ...]]:
return [c for c, _, _ in self.calls]
def auth_for(self, *tokens: str) -> str | None:
# Exact-token match: a needle must be a whole argv element, so a test's
# tmp_path (which embeds the test name — test_puSHes / test_reFETCH)
# can't masquerade as the `push`/`fetch` subcommand.
return next(au for cmd, _, au in self.calls if all(t in cmd for t in tokens))
def auth_for_substring(self, needle: str) -> str | None:
return next(au for cmd, _, au in self.calls if any(needle in t for t in cmd))
def test_handles_percent_encoded_token_chars():
# A token with a space and '@' is percent-encoded by _authed; both helpers
# must still match the encoded form up to the literal '@' delimiter.
url = _authed("https://codeberg.org/o/r.git", "a b@c")
assert "a%20b%40c" not in _redact(url)
assert _bare(url) == "https://codeberg.org/o/r.git"
def _index(cmds, *tokens) -> int:
for i, c in enumerate(cmds):
if all(t in c for t in tokens): # exact argv-token membership
return i
raise AssertionError(f"no call with tokens {tokens}; got {cmds}")
def test_no_token_untouched():
assert _redact("https://codeberg.org/o/r.git") == "https://codeberg.org/o/r.git"
assert _bare("https://codeberg.org/o/r.git") == "https://codeberg.org/o/r.git"
def _index_sub(cmds, needle: str) -> int:
for i, c in enumerate(cmds):
if any(needle in t for t in c): # substring within one argv token
return i
raise AssertionError(f"no call with substring {needle}; got {cmds}")
# --- ordering invariants (story #7) ---
def test_ordering_capture_before_prune_before_mirror_before_prhead(tmp_path):
fake = FakeExec(pull_heads={1: "aaa", 2: "bbb"})
mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
cmds = fake.cmds()
i_capture = _index(cmds, "--format=%(refname) %(objectname)") # pull-head capture
i_prune = _index(cmds, "update-ref") # the actual prune (batched delete)
i_mirror = _index(cmds, "push", "--mirror")
i_prhead = _index_sub(cmds, "refs/heads/_pr") # refspec token: <sha>:refs/heads/_pr/<n>
assert i_capture < i_prune < i_mirror < i_prhead
def test_report_shape_unchanged(tmp_path):
fake = FakeExec(pull_heads={1: "aaa", 2: "bbb"})
report = mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
assert report["lfs_pushed"] is True
assert report["pr_head_branches"] == 2
assert report["bare"].endswith("r.git")
def test_no_pull_heads_skips_pr_head_push_and_prune(tmp_path):
fake = FakeExec(pull_heads={})
mirror_repo(SRC_URL, TGT_URL, "s", "t", tmp_path / "w", git_exec=fake)
cmds = fake.cmds()
assert not any(any("refs/heads/_pr" in t for t in c) for c in cmds)
assert not any("update-ref" in c for c in cmds) # nothing to prune
# --- auth wiring (story #9): fetch=source, push=target, local ref ops=none ---
def test_clone_and_fetch_authenticate_as_source(tmp_path):
fake = FakeExec()
mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
assert fake.auth_for("clone", "--mirror") == SRC_URL
def test_pushes_authenticate_as_target(tmp_path):
fake = FakeExec(pull_heads={1: "aaa"})
mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
assert fake.auth_for("push", "--mirror") == TGT_URL
assert fake.auth_for_substring("refs/heads/_pr") == TGT_URL
def test_local_ref_ops_carry_no_auth(tmp_path):
fake = FakeExec(pull_heads={1: "aaa"})
mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
# update-ref is a local op; remote set-url/add write a token-free URL.
assert fake.auth_for("update-ref") is None
assert fake.auth_for("remote", "add", "target") is None
def test_refetch_path_authenticates_fetch_as_source(tmp_path):
(tmp_path / "w" / "r.git").mkdir(parents=True) # bare exists → re-fetch, not clone
fake = FakeExec()
mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
cmds = fake.cmds()
assert not any("clone" in c for c in cmds)
assert fake.auth_for("fetch") == SRC_URL
def test_lfs_target_remote_is_idempotent_on_rerun(tmp_path):
# The bare mirror persists on disk across runs, so on a re-run `remote add
# target` fails (already registered). The procedure must fall back to
# set-url and stay green — observable behaviour unchanged (spec #9).
(tmp_path / "w" / "r.git").mkdir(parents=True) # bare exists → re-fetch path
fake = FakeExec(target_exists=True)
report = mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
cmds = fake.cmds()
assert any("remote" in c and "add" in c and "target" in c for c in cmds)
assert any("remote" in c and "set-url" in c and "target" in c for c in cmds)
assert report["lfs_pushed"] is True
# --- LFS: probe gates fetch+push; missing binary skips gracefully (story #4) ---
def test_missing_git_lfs_skips_lfs_ops(tmp_path):
fake = FakeExec(pull_heads={1: "aaa"}, lfs=False)
report = mirror_repo(SRC_URL, TGT_URL, "s", "t", tmp_path / "w", git_exec=fake)
lfs_calls = [c for c in fake.cmds() if "lfs" in c]
assert lfs_calls == [("git", "lfs", "version")] # probe only; no fetch/push
assert report["lfs_pushed"] is False
def test_lfs_fetch_authenticates_as_source_push_as_target(tmp_path):
fake = FakeExec(pull_heads={1: "aaa"})
mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake)
assert fake.auth_for("lfs", "fetch") == SRC_URL
assert fake.auth_for("lfs", "push") == TGT_URL