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:
1 parent
137734673d
commit
1613ec72b8
10 files changed
+669
-223
No files matched your search
@@ -1,136 +1,35 @@
|
||||
"""Git mirror: code, full history, branches, tags, and LFS objects.
|
||||
"""Git mirror procedure: code, full history, branches, tags, and LFS objects.
|
||||
|
||||
Mirrors the source repository's git data to the target with
|
||||
``git clone --mirror`` + ``git push --mirror``. LFS objects (if any) are
|
||||
fetched and pushed separately — mirror push does not carry them. Both steps are
|
||||
no-ops when there's nothing LFS in the source, so this is safe to run on any
|
||||
repo.
|
||||
Drives git exclusively through :class:`git.GitRunner` — the sole git-op seam —
|
||||
so per-op timeout, error redaction, and auth delivery are properties of running
|
||||
git, not a per-call bolt-on. The token never reaches a remote URL or
|
||||
``.git/config``: auth is delivered per op via a non-persisted git config
|
||||
override (see :mod:`git`). This module's value is the *ordering* of the
|
||||
procedure (capture pull-heads → prune forge-internal refs → mirror push →
|
||||
recreate deleted-branch PR heads → LFS), which is what its tests lock.
|
||||
|
||||
Every network-bound git op runs under a timeout (``DEFAULT_GIT_TIMEOUT``,
|
||||
overridable via ``--git-timeout``) so a stalled TCP connection aborts with a
|
||||
clear :class:`GitError` instead of hanging the migration forever.
|
||||
Every network git op runs under ``DEFAULT_GIT_TIMEOUT`` (``--git-timeout``) so a
|
||||
stalled connection aborts with a clear :class:`GitError` instead of hanging.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
|
||||
from .git import DEFAULT_GIT_TIMEOUT, Forge, GitError, GitRunner, _real_exec
|
||||
|
||||
# Re-exported so cli.py / migrate.py keep importing these from here — the seam
|
||||
# owns them now, but the orchestration + CLI layers stay untouched by this
|
||||
# refactor (a bare re-export, not a re-implementation).
|
||||
__all__ = ["DEFAULT_GIT_TIMEOUT", "GitError", "mirror_repo"]
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: Per-op ceiling for network git ops (clone/fetch/push). Generous so a legit
|
||||
#: large clone completes; small enough that a stalled connection is caught.
|
||||
DEFAULT_GIT_TIMEOUT = 1800.0
|
||||
|
||||
|
||||
class GitError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _authed(url: str, token: str) -> str:
|
||||
"""Inject ``oauth2:<token>`` into an https git URL for private-repo access."""
|
||||
parts = urlsplit(url)
|
||||
if parts.scheme != "https" or not token:
|
||||
return url
|
||||
userinfo = f"oauth2:{quote(token, safe='')}"
|
||||
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_capture(
|
||||
cmd: list[str],
|
||||
cwd: Path | None = None,
|
||||
*,
|
||||
timeout: float = DEFAULT_GIT_TIMEOUT,
|
||||
input: str | None = None,
|
||||
) -> str:
|
||||
"""Run git, return stdout; raise on non-zero or timeout (errors carry stderr).
|
||||
|
||||
The error message redacts any ``oauth2:<token>`` embedded in the command or
|
||||
stderr so forge secrets never reach logs or tracebacks.
|
||||
"""
|
||||
try:
|
||||
proc = subprocess.run( # noqa: S603 - argv list, no shell
|
||||
cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout, input=input
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise GitError(f"git timed out after {timeout}s: {_redact(' '.join(cmd))}") from exc
|
||||
if proc.returncode != 0:
|
||||
raise GitError(
|
||||
f"git failed ({proc.returncode}): {' '.join(_redact(a) for a in cmd)}"
|
||||
f"\n{_redact(proc.stderr.strip())}"
|
||||
)
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def _run(
|
||||
cmd: list[str],
|
||||
cwd: Path | None = None,
|
||||
*,
|
||||
timeout: float = DEFAULT_GIT_TIMEOUT,
|
||||
input: str | None = None,
|
||||
) -> None:
|
||||
"""Run git, raising on non-zero/timeout. Thin wrapper over :func:`_run_capture`."""
|
||||
_run_capture(cmd, cwd, timeout=timeout, input=input)
|
||||
|
||||
|
||||
def _prune_internal_refs(bare: Path) -> None:
|
||||
"""Delete forge-managed refs (refs/pull/*) that the target won't accept.
|
||||
|
||||
Batched into a single ``update-ref --stdin`` so one process prunes them all,
|
||||
instead of spawning a git process per ref.
|
||||
"""
|
||||
listing = _run_capture(
|
||||
["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"]
|
||||
)
|
||||
refs = listing.split()
|
||||
if not refs:
|
||||
return
|
||||
stdin = "".join(f"delete {r}\n" for r in refs)
|
||||
_run(["git", "--git-dir", str(bare), "update-ref", "--stdin"], input=stdin)
|
||||
|
||||
|
||||
def _capture_pull_heads(bare: Path) -> dict[int, str]:
|
||||
def _capture_pull_heads(runner: GitRunner, bare: Path) -> dict[int, str]:
|
||||
"""Map PR number → head SHA from refs/pull/<n>/head before they're pruned."""
|
||||
listing = _run_capture(
|
||||
listing = runner.capture(
|
||||
[
|
||||
"git",
|
||||
"--git-dir",
|
||||
@@ -146,8 +45,7 @@ def _capture_pull_heads(bare: Path) -> dict[int, str]:
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
ref, sha = parts
|
||||
# refs/pull/<n>/head only — skip /merge test refs.
|
||||
if not ref.endswith("/head"):
|
||||
if not ref.endswith("/head"): # skip refs/pull/<n>/merge test refs
|
||||
continue
|
||||
try:
|
||||
number = int(ref.split("/")[2])
|
||||
@@ -158,22 +56,21 @@ def _capture_pull_heads(bare: Path) -> dict[int, str]:
|
||||
return heads
|
||||
|
||||
|
||||
def _lfs_installed() -> bool:
|
||||
proc = subprocess.run( # noqa: S603
|
||||
["git", "lfs", "version"], capture_output=True, text=True
|
||||
)
|
||||
return proc.returncode == 0
|
||||
def _prune_internal_refs(runner: GitRunner, bare: Path) -> None:
|
||||
"""Delete forge-managed refs (refs/pull/*) the target won't accept.
|
||||
|
||||
|
||||
def _ensure_remote(bare: Path, name: str, url: str) -> None:
|
||||
"""Create or update a git remote in a bare mirror."""
|
||||
add = subprocess.run( # noqa: S603
|
||||
["git", "--git-dir", str(bare), "remote", "add", name, url],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
One ``update-ref --stdin`` prunes them all instead of a git process per ref.
|
||||
"""
|
||||
listing = runner.capture(
|
||||
["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"]
|
||||
)
|
||||
refs = listing.split()
|
||||
if not refs:
|
||||
return
|
||||
runner.run(
|
||||
["git", "--git-dir", str(bare), "update-ref", "--stdin"],
|
||||
stdin="".join(f"delete {r}\n" for r in refs),
|
||||
)
|
||||
if add.returncode != 0:
|
||||
_run(["git", "--git-dir", str(bare), "remote", "set-url", name, url])
|
||||
|
||||
|
||||
def mirror_repo(
|
||||
@@ -184,11 +81,13 @@ def mirror_repo(
|
||||
workdir: Path,
|
||||
*,
|
||||
git_timeout: float = DEFAULT_GIT_TIMEOUT,
|
||||
git_exec=_real_exec,
|
||||
) -> dict[str, object]:
|
||||
"""Mirror a repo's git data (and LFS) from source to target.
|
||||
|
||||
Returns a small report dict. ``workdir`` is created if missing; the bare
|
||||
clone is left there (useful for inspection / re-push).
|
||||
clone is left there (useful for inspection / re-push). ``git_exec`` is the
|
||||
test seam — production leaves it at the real subprocess adapter.
|
||||
"""
|
||||
workdir.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
@@ -197,69 +96,51 @@ def mirror_repo(
|
||||
pass
|
||||
bare = workdir / (Path(source_url).name.removesuffix(".git") + ".git")
|
||||
|
||||
src = _authed(source_url, source_token)
|
||||
tgt = _authed(target_url, target_token)
|
||||
source = Forge(source_url, source_token)
|
||||
target = Forge(target_url, target_token)
|
||||
runner = GitRunner(timeout=git_timeout, exec=git_exec)
|
||||
|
||||
# All git ops run under try/finally so the tokenized remote URLs git writes
|
||||
# into .git/config are always scrubbed — even on a timeout/failure (the
|
||||
# timeout this diff added makes early abort more frequent, so this matters).
|
||||
try:
|
||||
if bare.exists():
|
||||
# Re-fetch source refs into an existing mirror (idempotent re-run).
|
||||
_run(
|
||||
["git", "--git-dir", str(bare), "remote", "set-url", "origin", src],
|
||||
timeout=git_timeout,
|
||||
)
|
||||
_run(
|
||||
["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"],
|
||||
timeout=git_timeout,
|
||||
)
|
||||
else:
|
||||
_run(["git", "clone", "--mirror", src, str(bare)], timeout=git_timeout)
|
||||
if bare.exists():
|
||||
# Re-fetch source refs into an existing mirror (idempotent re-run).
|
||||
runner.run(["git", "--git-dir", str(bare), "remote", "set-url", "origin", source.url])
|
||||
runner.run(
|
||||
["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"], auth=source
|
||||
)
|
||||
else:
|
||||
runner.run(["git", "clone", "--mirror", source.url, str(bare)], auth=source)
|
||||
|
||||
# Forgejo/Gitea expose refs/pull/<n>/head (and /merge) as fetchable refs;
|
||||
# `clone --mirror` grabs them, but the target declines pushes to refs/pull/*
|
||||
# (it manages those itself). First capture each PR's head SHA so we can
|
||||
# recreate the PR on the target (a deleted-branch PR has no other branch),
|
||||
# then drop the namespace so the mirror push doesn't trip on it.
|
||||
pull_heads = _capture_pull_heads(bare)
|
||||
_prune_internal_refs(bare)
|
||||
# clone --mirror grabs refs/pull/<n>/head, but the target declines pushes to
|
||||
# refs/pull/* (it manages those). Capture each PR's head first so a
|
||||
# deleted-branch PR can be recreated, then drop the namespace so the mirror
|
||||
# push doesn't trip on it.
|
||||
pull_heads = _capture_pull_heads(runner, bare)
|
||||
_prune_internal_refs(runner, bare)
|
||||
|
||||
# push --mirror replaces all target refs with source refs.
|
||||
_run(["git", "--git-dir", str(bare), "push", "--mirror", tgt], timeout=git_timeout)
|
||||
# push --mirror replaces all target refs with source refs.
|
||||
runner.run(["git", "--git-dir", str(bare), "push", "--mirror", target.url], auth=target)
|
||||
|
||||
# Recreate each PR head on the target as a real branch refs/heads/_pr/<n>,
|
||||
# used as the PR's head when the original branch is gone. (Pushed after the
|
||||
# mirror so --mirror doesn't wipe them.) Batched into one push so one
|
||||
# process + one connection handles all deleted-branch PRs.
|
||||
if pull_heads:
|
||||
refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
|
||||
_run(["git", "--git-dir", str(bare), "push", tgt, *refspecs], timeout=git_timeout)
|
||||
# Recreate each PR head on the target as refs/heads/_pr/<n> (used as the PR's
|
||||
# head when the original branch is gone). Pushed after the mirror so --mirror
|
||||
# doesn't wipe them; batched into one push.
|
||||
if pull_heads:
|
||||
refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
|
||||
runner.run(["git", "--git-dir", str(bare), "push", target.url, *refspecs], auth=target)
|
||||
|
||||
lfs_pushed = False
|
||||
if runner.ok(["git", "lfs", "version"]):
|
||||
# Fetch every LFS object the source history references, then push them.
|
||||
# A bare mirror has `origin` → source; LFS needs the target URL reachable
|
||||
# as a named remote.
|
||||
# ponytail: assumes git-lfs honours http.<host>.extraHeader. If a forge
|
||||
# proves it does not, swap to a credential helper scoped to LFS behind
|
||||
# this same seam — an internal knob, not an architectural change.
|
||||
runner.run(["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"], auth=source)
|
||||
# Ensure the target remote exists (add-or-set-url): the bare mirror is
|
||||
# left on disk across idempotent re-runs, so `remote add target` fails if
|
||||
# it's already registered — fall back to set-url rather than crash.
|
||||
if not runner.ok(["git", "--git-dir", str(bare), "remote", "add", "target", target.url]):
|
||||
runner.run(["git", "--git-dir", str(bare), "remote", "set-url", "target", target.url])
|
||||
runner.run(["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"], auth=target)
|
||||
lfs_pushed = True
|
||||
|
||||
lfs_pushed = False
|
||||
if _lfs_installed():
|
||||
# Fetch every LFS object the source history references.
|
||||
_run(
|
||||
["git", "--git-dir", str(bare), "lfs", "fetch", "--all", "origin"],
|
||||
timeout=git_timeout,
|
||||
)
|
||||
# Push LFS objects to the target via a named remote (a bare mirror has
|
||||
# `origin` → source; LFS needs the target URL reachable as a remote).
|
||||
_ensure_remote(bare, "target", tgt)
|
||||
_run(
|
||||
["git", "--git-dir", str(bare), "lfs", "push", "--all", "target"],
|
||||
timeout=git_timeout,
|
||||
)
|
||||
lfs_pushed = True
|
||||
finally:
|
||||
_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 + 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)
|
||||
Reference in new issue
Block a user