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

+4 -3
View File
@@ -24,7 +24,8 @@ Console script: `codeberg-to-gitea`.
## Module map
- `clients.py` — `ApiClient`: bearer auth, transparent pagination (`page`/`limit`), retry on 429/5xx with full jitter, `get/post/patch/delete`, `raw_get_stream` (binary download streamed to a spooled temp file), `post_multipart` (asset upload). Thread-safe (one underlying `httpx.Client` per thread via a thread-local), so a single client serves concurrent requests; circuit breaker (`CircuitOpenError`) trips after N consecutive exhausted-retry failures; `_path` helper + `parallel(items, fn, workers=, executor=)` live here.
- `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`. Every network git op runs under a per-op timeout (`DEFAULT_GIT_TIMEOUT`, `--git-timeout`); PR-head pushes and `refs/pull/*` pruning are batched into a single `git push` / `update-ref --stdin`.
- `git.py` — the git-op seam (`GitRunner`): the *only* way git is invoked. Owns subprocess execution, per-op timeout (`DEFAULT_GIT_TIMEOUT`), error redaction (`redact` — known-secret first, legacy `oauth2:` fallback), and auth delivery (`Forge`, a frozen value type binding a token-free URL + token). Auth is a non-persisted per-op `git -c http.<scheme>://<host>.extraHeader=Authorization: token <T>`, so the token never enters a remote URL, the command line, or `.git/config` (closes audit HIGH A09 + MEDIUM A02 at the root). `run`/`capture`/`ok` verbs; an injectable exec callable is the test seam (recording fake).
- `mirror.py` — the git-mirror *procedure*: drives a `GitRunner` (clone/fetch → capture `refs/pull/<n>/head` → prune forge-internal refs → `push --mirror` → recreate deleted-branch PR heads as `refs/heads/_pr/<n>` → LFS fetch+push). Owns the workdir lifecycle (per-user `0700`); its value is the ordering invariants, which its tests lock. `DEFAULT_GIT_TIMEOUT`/`GitError` are re-exported here so `cli.py`/`migrate.py` import them unchanged.
- `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. Pass A (creation) is serial (ordered); labels/milestones and Pass B (ref rewrite + comments) overlap via `parallel`. Issues carry their milestone in the create body; PRs still PATCH it (pull-create has no milestone field).
- `releases.py` — non-draft releases + asset re-upload. Assets stream through `raw_get_stream` (bounded memory) and upload concurrently within a release. Treats a 404 releases endpoint (feature disabled) as "none".
@@ -39,12 +40,12 @@ 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.
- Forge API tokens are secrets: git auth goes through the `git.GitRunner` seam as a non-persisted `http.<host>.extraHeader`, so tokens never reach logs, exceptions, the command line, or the persisted `/tmp/cb2gitea-<uid>/.git/config`. Don't reintroduce bare tokens into error messages or stored URLs, and don't invoke git outside `GitRunner` (an AST regression guard fails the suite otherwise).
- Execution model: a single `ApiClient` is thread-safe (per-thread underlying `httpx.Client`), so the migration overlaps independent writes via `parallel(..., workers=concurrency)`. Pass A issue/PR creation stays serial — entities are created in source-number order so the number map can rewrite forward cross-references. `--concurrency` sizes the pool (default 8); `--git-timeout` bounds network git ops (default 1800s). Tune `--concurrency` down if the target forge rate-limits hard — the jittered 429 backoff + circuit breaker handle it, but lower concurrency is gentler.
## Verification
- `pytest` (testpaths = `tests`) — refs rewriting, number map, client pagination (mock transport, no network).
- `pytest` (testpaths = `tests`) — refs rewriting, number map, client pagination (mock transport); the `GitRunner` seam (recording exec fake) + mirror-procedure ordering invariants; an AST guard that git is invoked only through `GitRunner`. 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.
+130
View File
@@ -0,0 +1,130 @@
"""The git-op seam: the *only* way git is invoked.
Owns subprocess execution, per-op timeout, error redaction, and auth delivery.
Auth is delivered via a non-persisted per-op git config override
(``http.<scheme>://<host>.extraHeader = "Authorization: token <T>"``) so the
token never enters a remote URL, the persisted command line, or ``.git/config``
— the structural fix for audit findings A09 (HIGH) and A02 (MEDIUM).
The runner is forge-agnostic: it holds only a timeout and an exec hook. Which
forge an op authenticates against is declared per call via :class:`Forge`.
"""
from __future__ import annotations
import logging
import re
import subprocess
from dataclasses import dataclass
from urllib.parse import urlsplit
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
#: Legacy ``oauth2:<token>@`` form, for when a secret reached a URL percent-encoded.
_LEGACY_TOKEN_RE = re.compile(r"(oauth2:)[^@]+(@)")
class GitError(RuntimeError):
"""A git invocation failed or timed out; message is token-redacted."""
@dataclass(frozen=True)
class Forge:
"""A forge endpoint: a token-free URL bound to its bearer token.
Binding the two means "push to the target URL with the source token" cannot
be expressed — same-forge is an invariant, not two free parameters.
"""
url: str
token: str
def redact(text: str, *secrets: str) -> str:
"""Scrub known secrets, then the legacy ``oauth2:<tok>@`` form.
Uses the *known secret* (not a blind regex) so a future auth pattern is still
caught: every literal secret is replaced first. The legacy regex only covers
the case where the secret reached a URL percent-encoded (and so is not a
literal match). The ``Authorization: token`` label is kept visible for
diagnostics; only the value is masked.
"""
for secret in secrets:
if secret:
text = text.replace(secret, "***")
return _LEGACY_TOKEN_RE.sub(r"\1***\2", text)
def _auth_args(forge: Forge) -> list[str]:
"""The non-persisted per-op config that carries the token into git.
One header matches every repo on the host (longest-prefix match), so it
applies to clone/fetch/push alike. Matches the REST client's ``token <T>``
scheme (:func:`clients.ApiClient`). Auth is composed *inside* the adapter, so
the recording test fake never sees a token.
"""
parts = urlsplit(forge.url)
section = f"{parts.scheme}://{parts.netloc}" # e.g. https://git.babylondreams.de
return ["-c", f"http.{section}.extraHeader=Authorization: token {forge.token}"]
def _real_exec(cmd, *, timeout, stdin, auth):
"""Run git via subprocess, composing auth inside so callers stay token-free.
Raises :class:`GitError` (redacted) on non-zero exit or timeout; otherwise
returns the completed process. This is the one real adapter — a second real
backend (e.g. dry-run) is the trigger to promote the exec callable to a
formal Protocol/port.
"""
argv = [cmd[0], *(_auth_args(auth) if auth else []), *cmd[1:]]
secret = auth.token if auth else ""
try:
proc = subprocess.run( # noqa: S603 - argv list, no shell
argv, capture_output=True, text=True, timeout=timeout, input=stdin
)
except subprocess.TimeoutExpired as exc:
raise GitError(f"git timed out after {timeout}s: {redact(' '.join(argv), secret)}") from exc
if proc.returncode != 0:
raise GitError(
f"git failed ({proc.returncode}): {redact(' '.join(argv), secret)}"
f"\n{redact(proc.stderr.strip(), secret)}"
)
return proc
class GitRunner:
"""The sole git-op seam: run / capture / ok, auth declared per call."""
def __init__(self, *, timeout: float = DEFAULT_GIT_TIMEOUT, exec=_real_exec):
self._timeout = timeout
self._exec = exec
def run(self, cmd, *, auth: Forge | None = None, stdin: str | None = None) -> None:
"""Fire-and-forget; raise :class:`GitError` on non-zero/timeout."""
self._exec(cmd, timeout=self._timeout, stdin=stdin, auth=auth)
def capture(self, cmd, *, auth: Forge | None = None) -> str:
"""Return stdout; raise :class:`GitError` on non-zero/timeout."""
return self._exec(cmd, timeout=self._timeout, stdin=None, auth=auth).stdout
def ok(self, cmd) -> bool:
"""Success probe — returns a bool, never raises (used to detect ``git lfs``)."""
try:
self._exec(cmd, timeout=self._timeout, stdin=None, auth=None)
except GitError:
return False
return True
if __name__ == "__main__": # self-check — auth args + redaction, no network
assert _auth_args(SRC := Forge("https://codeberg.org/o/r.git", "t ok@en")) == [
"-c",
"http.https://codeberg.org.extraHeader=Authorization: token t ok@en",
], _auth_args(SRC)
assert redact("Authorization: token t ok@en", "t ok@en") == "Authorization: token ***"
assert redact("https://oauth2:s3cr3t@h/o.git", "other") == "https://oauth2:***@h/o.git"
print("git self-check ok")
+78 -197
View File
@@ -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)