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

+11 -1
View File
@@ -106,7 +106,7 @@ When the user requests a durable behavior change, record it here or in the relev
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **codeberg-to-gitea-migrator** (239 symbols, 448 relationships, 11 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. This project is indexed by GitNexus as **codeberg-to-gitea-migrator** (392 symbols, 767 relationships, 30 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -146,3 +146,13 @@ This project is indexed by GitNexus as **codeberg-to-gitea-migrator** (239 symbo
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | | Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
## Session Logs
Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent:
<!-- write-log: window-start -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-08-11 | issue | [20260811-issue1-gitrunner-sole-git-op-seam_log.md](docs/devlog/20260811-issue1-gitrunner-sole-git-op-seam_log.md) | Introduce `git.GitRunner` as the sole git-op seam; rewrite mirror to drive it; retire URL-token helpers; closes audit HIGH A09 + MEDIUM A02 at the root. |
<!-- write-log: window-end -->
+2 -1
View File
@@ -6,7 +6,7 @@ All notable changes to this project will be documented in this file. The format
### security ### security
- **migrator:** keep forge API tokens out of error text and on-disk git config. Git failures now surface a redacted `oauth2:***@` URL instead of the live token, and the CLI catches `GitError` with a clean message instead of dumping a traceback. The mirror's remote URLs are scrubbed to bare form after each run (no token persisted in `.git/config`), and the default workdir is per-user `0700` (`/tmp/cb2gitea-<uid>`) so it isn't world-readable on shared hosts. - **migrator:** keep forge API tokens out of error text, the command line, and on-disk git config. Git auth is delivered through a single `git.GitRunner` seam as a non-persisted per-op `http.<host>.extraHeader` (`Authorization: token <T>`), so the token never enters a remote URL or `.git/config`; failures raise a redacted `GitError` (known-secret + `oauth2:` fallback) and the CLI catches it cleanly. The default workdir stays per-user `0700`. Closes the 2026-08-11 audit's HIGH (token in error text) and MEDIUM (token in git config) at one structural root cause.
- **deps:** reproducible, hash-verified installs — commit `uv.lock` and install from it in CI (`uv sync --frozen`); pin Gitea Actions to commit SHAs instead of mutable `@vN` tags; pin the ruff rule set explicitly (`select = ["E4","E7","E9","F"]`) and exclude `audit/`. - **deps:** reproducible, hash-verified installs — commit `uv.lock` and install from it in CI (`uv sync --frozen`); pin Gitea Actions to commit SHAs instead of mutable `@vN` tags; pin the ruff rule set explicitly (`select = ["E4","E7","E9","F"]`) and exclude `audit/`.
### perf ### perf
@@ -27,6 +27,7 @@ All notable changes to this project will be documented in this file. The format
### refactor ### refactor
- **cli:** drop the `typer` dependency; the CLI now uses stdlib `argparse` (same `migrate`/`version` subcommands, flags, and `CODEBERG_TOKEN`/`GITEA_TOKEN` env vars). Removes `typer` and its transitive `rich`/`shellingham` from the install (3 fewer packages). - **cli:** drop the `typer` dependency; the CLI now uses stdlib `argparse` (same `migrate`/`version` subcommands, flags, and `CODEBERG_TOKEN`/`GITEA_TOKEN` env vars). Removes `typer` and its transitive `rich`/`shellingham` from the install (3 fewer packages).
- **migrator:** introduce `git.GitRunner` as the sole git-op seam — the only place git is invoked. The mirror procedure (`mirror.py`) is rewritten to drive it (`run`/`capture`/`ok` verbs; `Forge` value type for per-op auth), retiring the URL-tokenization, token-stripping, and on-exit config-scrub helpers (their reason to exist vanishes). The procedure's ordering invariants (pull-head capture → prune → mirror push → deleted-branch PR-head restore → LFS) are now locked by a recording-fake test; an AST guard fails the suite if any git op bypasses the seam.
- **migrator:** remove dead code surfaced by a whole-repo over-engineering audit — `has_lfs`/`LFS_MARKERS` (uncalled), the `name_map` return of `migrate_labels` (sole caller discarded it), the unused `owner_repo` rewrite param, and a stored-but-unread `_base_url`. - **migrator:** remove dead code surfaced by a whole-repo over-engineering audit — `has_lfs`/`LFS_MARKERS` (uncalled), the `name_map` return of `migrate_labels` (sole caller discarded it), the unused `owner_repo` rewrite param, and a stored-but-unread `_base_url`.
### feat ### feat
@@ -0,0 +1,96 @@
# GitRunner: sole git-op seam (closes audit HIGH + MEDIUM token findings)
> **Date:** 2026-08-11
> **Type:** issue
> **Reference:** Gitea issue #1 — `tea issues view 1`; audit `audit/2026-08-11/security-report.md` (A09 HIGH, A02 MEDIUM)
## Goal
Introduce a single deep module — `git.GitRunner` — as the *only* way git is
invoked, rewrite the mirror procedure to drive it, retire the URL-token
machinery (its reason to exist vanishes), and lock the procedure's ordering
invariants behind a recording-fake test. This closes the 2026-08-11 security
audit's HIGH (live token in an uncaught `GitError`) and MEDIUM (token
persisted in the mirror clone's `.git/config`) at one structural root cause.
## What Was Done
- **New `src/codeberg_to_gitea_migrator/git.py`** — the seam. `GitRunner`
(sole git-op site), `Forge` (frozen url+token value type), `GitError`,
`DEFAULT_GIT_TIMEOUT`, `redact()` (known-secret first, legacy `oauth2:`
regex fallback), `_auth_args()` (non-persisted per-op
`git -c http.<scheme>://<host>.extraHeader=Authorization: token <T>`),
`_real_exec` (subprocess adapter that composes auth *inside*, so callers and
test fakes never see a token), and the `run` / `capture` / `ok` verbs.
- **Rewrote `mirror.py`** — `mirror_repo` drives a `GitRunner`; deleted
`_authed`, `_bare`, `_redact`, `_scrub_remote_tokens`, `_run`, `_run_capture`,
`_ensure_remote`, and the `try/finally` scrub block. `mirror_repo`'s
signature and report dict are unchanged; `DEFAULT_GIT_TIMEOUT` / `GitError`
are re-exported so `cli.py` / `migrate.py` stay byte-identical.
- **Restored idempotent re-run for the LFS `target` remote** (add-or-set-url via
the seam's `ok` probe) — a regression the spec reviewer caught.
- **Tests** — new `test_git.py` (15 seam tests + an AST sole-caller guard);
rewrote `test_mirror.py` (ordering invariants, per-op auth wiring, LFS skip,
idempotent-rerun regression). Deleted the old URL-token redaction tests.
- **Docs** — `src/.../AGENTS.md` module map gains `git.py` and a rewritten
mirror entry; `tests/AGENTS.md` gains `test_git.py` / `test_mirror.py`;
`CHANGELOG.md` security + refactor entries. `CONTEXT.md` was already aligned
to the target state — left untouched.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Auth via non-persisted `git -c http.<host>.extraHeader` (not URL token, not credential helper) | Token leaves the remote URL, the persisted command line, and `.git/config` — closes both audit findings at the root. Credential-helper (process-list hardening) is a later swap behind the same seam. |
| `Forge` = frozen value type binding url + token | Makes "push the target URL with the source token" unexpressable — same-forge is an invariant, not two free parameters (story #9). |
| Three verbs `run` / `capture` / `ok` (not flags) | Removes the footgun where forgetting a "don't raise" flag turns "LFS not installed → skip" into a crash; `ok` never raises. |
| Re-export `DEFAULT_GIT_TIMEOUT` / `GitError` from `mirror.py` | Keeps `cli.py` / `migrate.py` byte-identical (story #11) and `mirror_repo`'s contract preserved (story #5). |
| `redact()` uses the known secret first, regex only as fallback | Story #15 — a future auth pattern still gets masked, not just the `oauth2:` shape. |
| One recording fake of the exec callable, no formal Protocol/port | Only one real adapter exists; the Protocol is deferred to the "second real backend" trigger (e.g. dry-run). |
| Refactor confined to the mirror layer | `cli` / `migrate` / `clients` / `refs` / `issues` / `releases` untouched — confirmed by `gitnexus detect_changes`. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `test_pushes_authenticate_as_target` and `test_refetch_path…` failed with impl-correct output | pytest's `tmp_path` embeds the test name — `…/test_pu**sh**es…/` and `…/test_re**fetch**…/` — and my command matcher used substring-of-joined, so the path token masqueraded as the `push`/`fetch` subcommand | Switched command identification to **exact argv-token** membership; substring-within-a-token only for the `_pr/<n>` refspec |
| `ruff F401` flagged `GitError` unused in `mirror.py` | Imported solely so `cli.py` can `from .mirror import GitError` | Added `__all__ = [...]` so ruff treats it as an intentional re-export |
| Spec review: `remote add target` (add-only) broke idempotent re-runs | Replacing `_ensure_remote`'s add-or-set-url with a bare `add` meant the persisted `target` remote makes `git remote add` fail on the 2nd run | Restored add-or-set-url through the seam's `ok` probe + `set-url` fallback; added `test_lfs_target_remote_is_idempotent_on_rerun` |
| Tautology test (`assert fake is not None`) | Didn't actually verify the per-runner timeout reaches exec | `_Fake` now records `timeouts`; test asserts `fake.timeouts == [42]` |
## Files Changed
| File | Change Summary |
|------|----------------|
| `src/codeberg_to_gitea_migrator/git.py` | NEW — the git-op seam: `GitRunner`, `Forge`, `redact`, `_auth_args`, `_real_exec`, `run`/`capture`/`ok` |
| `src/codeberg_to_gitea_migrator/mirror.py` | Rewritten to drive `GitRunner`; retired URL-token helpers; idempotent target-remote restore; re-exports |
| `tests/test_git.py` | NEW — seam tests (auth delivery, redaction, error/timeout contract, `ok` never raises) + AST sole-caller guard |
| `tests/test_mirror.py` | Rewritten — ordering invariants + per-op auth wiring + LFS skip + idempotent-rerun, via a recording exec fake |
| `src/codeberg_to_gitea_migrator/AGENTS.md` | DOX: module map gains `git.py`; mirror entry rewritten; Work Guidance + Verification updated |
| `tests/AGENTS.md` | DOX: test index gains `test_git.py` / `test_mirror.py` |
| `CHANGELOG.md` | `security` + `refactor` entries under `[Unreleased]` |
| `AGENTS.md` | Session Logs section added (this log) |
## Verification
- `pytest` → **44 passed**. `ruff check .` + `ruff format --check .` → clean.
- `gitnexus detect_changes` → only `mirror_repo` touched in production (signature
preserved); cli/migrate/clients/refs/issues/releases untouched.
- Two-axis `/code-review` → **Standards**: 0 hard violations; **Spec**: 1 medium
(idempotent re-run) found and fixed.
## Open Items & Next Steps
- [ ] **Runtime verify** `git-lfs` honours `http.<host>.extraHeader` against the
real forges; if not, swap to an LFS-scoped credential helper behind the
seam (open item carried from the issue; not hermetically testable).
- [ ] Residual audit **LOW** (token briefly visible in the process list via the
`--source-token` / `--target-token` flags) — later swap behind the seam.
- [ ] Issues **#2** (Migration context handle) and **#3** (`_pr/<n>` contract in
`refs.py`) remain open — explicitly out of scope here.
- [ ] Close Gitea issue **#1** (`tea issues close 1`) after merge — left to the
operator.
---
*Log written by write-log skill*
+8
View File
@@ -0,0 +1,8 @@
# Session Log Index
Complete history of session logs in this directory, newest first. One-line summaries — open a log for full detail.
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-08-11 | issue | [20260811-issue1-gitrunner-sole-git-op-seam_log.md](20260811-issue1-gitrunner-sole-git-op-seam_log.md) | Introduce `git.GitRunner` as the sole git-op seam; rewrite mirror to drive it; retire URL-token helpers; closes audit HIGH A09 + MEDIUM A02 at the root. |
+4 -3
View File
@@ -24,7 +24,8 @@ Console script: `codeberg-to-gitea`.
## Module map ## 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. - `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). - `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). - `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". - `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. - 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). - 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. - 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. - 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 ## 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 .`. - `ruff check .` and `ruff format --check .`.
- End-to-end: `CODEBERG_TOKEN=… GITEA_TOKEN=… codeberg-to-gitea migrate owner/name`. - 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. - 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 Drives git exclusively through :class:`git.GitRunner` — the sole git-op seam —
``git clone --mirror`` + ``git push --mirror``. LFS objects (if any) are so per-op timeout, error redaction, and auth delivery are properties of running
fetched and pushed separately — mirror push does not carry them. Both steps are git, not a per-call bolt-on. The token never reaches a remote URL or
no-ops when there's nothing LFS in the source, so this is safe to run on any ``.git/config``: auth is delivered per op via a non-persisted git config
repo. 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``, Every network git op runs under ``DEFAULT_GIT_TIMEOUT`` (``--git-timeout``) so a
overridable via ``--git-timeout``) so a stalled TCP connection aborts with a stalled connection aborts with a clear :class:`GitError` instead of hanging.
clear :class:`GitError` instead of hanging the migration forever.
""" """
from __future__ import annotations from __future__ import annotations
import logging import logging
import re
import subprocess
from pathlib import Path 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__) 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
def _capture_pull_heads(runner: GitRunner, bare: Path) -> dict[int, str]:
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]:
"""Map PR number → head SHA from refs/pull/<n>/head before they're pruned.""" """Map PR number → head SHA from refs/pull/<n>/head before they're pruned."""
listing = _run_capture( listing = runner.capture(
[ [
"git", "git",
"--git-dir", "--git-dir",
@@ -146,8 +45,7 @@ def _capture_pull_heads(bare: Path) -> dict[int, str]:
if len(parts) != 2: if len(parts) != 2:
continue continue
ref, sha = parts ref, sha = parts
# refs/pull/<n>/head only — skip /merge test refs. if not ref.endswith("/head"): # skip refs/pull/<n>/merge test refs
if not ref.endswith("/head"):
continue continue
try: try:
number = int(ref.split("/")[2]) number = int(ref.split("/")[2])
@@ -158,22 +56,21 @@ def _capture_pull_heads(bare: Path) -> dict[int, str]:
return heads return heads
def _lfs_installed() -> bool: def _prune_internal_refs(runner: GitRunner, bare: Path) -> None:
proc = subprocess.run( # noqa: S603 """Delete forge-managed refs (refs/pull/*) the target won't accept.
["git", "lfs", "version"], capture_output=True, text=True
)
return proc.returncode == 0
One ``update-ref --stdin`` prunes them all instead of a git process per ref.
def _ensure_remote(bare: Path, name: str, url: str) -> None: """
"""Create or update a git remote in a bare mirror.""" listing = runner.capture(
add = subprocess.run( # noqa: S603 ["git", "--git-dir", str(bare), "for-each-ref", "--format=%(refname)", "refs/pull/"]
["git", "--git-dir", str(bare), "remote", "add", name, url], )
capture_output=True, refs = listing.split()
text=True, 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( def mirror_repo(
@@ -184,11 +81,13 @@ def mirror_repo(
workdir: Path, workdir: Path,
*, *,
git_timeout: float = DEFAULT_GIT_TIMEOUT, git_timeout: float = DEFAULT_GIT_TIMEOUT,
git_exec=_real_exec,
) -> dict[str, object]: ) -> dict[str, object]:
"""Mirror a repo's git data (and LFS) from source to target. """Mirror a repo's git data (and LFS) from source to target.
Returns a small report dict. ``workdir`` is created if missing; the bare 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) workdir.mkdir(parents=True, exist_ok=True)
try: try:
@@ -197,69 +96,51 @@ def mirror_repo(
pass pass
bare = workdir / (Path(source_url).name.removesuffix(".git") + ".git") bare = workdir / (Path(source_url).name.removesuffix(".git") + ".git")
src = _authed(source_url, source_token) source = Forge(source_url, source_token)
tgt = _authed(target_url, target_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 if bare.exists():
# into .git/config are always scrubbed — even on a timeout/failure (the # Re-fetch source refs into an existing mirror (idempotent re-run).
# timeout this diff added makes early abort more frequent, so this matters). runner.run(["git", "--git-dir", str(bare), "remote", "set-url", "origin", source.url])
try: runner.run(
if bare.exists(): ["git", "--git-dir", str(bare), "fetch", "--prune", "origin", "*:*"], auth=source
# Re-fetch source refs into an existing mirror (idempotent re-run). )
_run( else:
["git", "--git-dir", str(bare), "remote", "set-url", "origin", src], runner.run(["git", "clone", "--mirror", source.url, str(bare)], auth=source)
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)
# Forgejo/Gitea expose refs/pull/<n>/head (and /merge) as fetchable refs; # clone --mirror grabs refs/pull/<n>/head, but the target declines pushes to
# `clone --mirror` grabs them, but the target declines pushes to refs/pull/* # refs/pull/* (it manages those). Capture each PR's head first so a
# (it manages those itself). First capture each PR's head SHA so we can # deleted-branch PR can be recreated, then drop the namespace so the mirror
# recreate the PR on the target (a deleted-branch PR has no other branch), # push doesn't trip on it.
# then drop the namespace so the mirror push doesn't trip on it. pull_heads = _capture_pull_heads(runner, bare)
pull_heads = _capture_pull_heads(bare) _prune_internal_refs(runner, bare)
_prune_internal_refs(bare)
# push --mirror replaces all target refs with source refs. # push --mirror replaces all target refs with source refs.
_run(["git", "--git-dir", str(bare), "push", "--mirror", tgt], timeout=git_timeout) 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>, # Recreate each PR head on the target as refs/heads/_pr/<n> (used as the PR's
# used as the PR's head when the original branch is gone. (Pushed after the # head when the original branch is gone). Pushed after the mirror so --mirror
# mirror so --mirror doesn't wipe them.) Batched into one push so one # doesn't wipe them; batched into one push.
# process + one connection handles all deleted-branch PRs. if pull_heads:
if pull_heads: refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
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)
_run(["git", "--git-dir", str(bare), "push", tgt, *refspecs], timeout=git_timeout)
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)} 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)
+2
View File
@@ -18,6 +18,8 @@ Project maintainer (Alexander Kucera).
- `test_smoke.py` — package imports + version. - `test_smoke.py` — package imports + version.
- `test_refs.py` — `#NNN`/URL cross-reference rewrite + `NumberMap`. - `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_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. - 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 ## 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, Driven through a recording fake of the GitRunner exec callable (no git binary,
``_redact`` masks it for logs/exceptions, and ``_bare`` strips it for the no network). The fake records command intent only — ``auth.url``, never
on-disk remote config scrub. ``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(): def _ok(stdout: str = "") -> subprocess.CompletedProcess:
url = _authed("https://codeberg.org/o/r.git", "s3cr3t") return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout, stderr="")
assert "s3cr3t" not in _redact(url)
assert _redact(url) == "https://oauth2:***@codeberg.org/o/r.git"
def test_bare_strips_userinfo_entirely(): class FakeExec:
url = _authed("https://codeberg.org/o/r.git", "s3cr3t") """Recording exec: (cmd, stdin, auth_url). Synthesizes for-each-ref output."""
assert _bare(url) == "https://codeberg.org/o/r.git"
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(): def _index(cmds, *tokens) -> int:
# A token with a space and '@' is percent-encoded by _authed; both helpers for i, c in enumerate(cmds):
# must still match the encoded form up to the literal '@' delimiter. if all(t in c for t in tokens): # exact argv-token membership
url = _authed("https://codeberg.org/o/r.git", "a b@c") return i
assert "a%20b%40c" not in _redact(url) raise AssertionError(f"no call with tokens {tokens}; got {cmds}")
assert _bare(url) == "https://codeberg.org/o/r.git"
def test_no_token_untouched(): def _index_sub(cmds, needle: str) -> int:
assert _redact("https://codeberg.org/o/r.git") == "https://codeberg.org/o/r.git" for i, c in enumerate(cmds):
assert _bare("https://codeberg.org/o/r.git") == "https://codeberg.org/o/r.git" 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