"""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 " 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)