GitRunner: sole git-op seam (closes audit HIGH + MEDIUM token findings) #1

Closed
opened 2026-08-11 14:22:38 +02:00 by AlexKucera · 0 comments
Owner

Problem Statement

As the operator/maintainer of the Codeberg → Gitea migrator, I run a one-shot
cutover that drives git (clone --mirror, push --mirror, ref pruning, LFS) while
holding two live forge API tokens. Today the git-mirror layer invokes git from
five separate subprocess call sites, and only one of them carries the
per-op timeout and token-redaction discipline — the other four bypass it. That
makes the token-safety rules a partial bolt-on rather than a property of running
git, and it leaves the whole mirror procedure (the ordering of pull-head
capture, ref pruning, mirror push, deleted-branch PR restoration, and LFS) with
no test surface at all. Concretely, the 2026-08-11 security audit logged this as
two findings — a HIGH (live token embedded in a GitError that reaches
logs/tracebacks) and a MEDIUM (token persisted in plaintext in the mirror
clone's .git/config) — that share a single architectural root cause: there is
no single seam through which git is invoked, so token hygiene cannot be enforced
in one place.

Solution

Introduce a single deep module — GitRunner, the git-op seam — that is the
only way git is invoked. It owns subprocess execution, per-op timeout, error
redaction, and auth delivery. Authentication moves off the remote URL entirely:
the bearer token is delivered via a non-persisted per-op git config override, so
the token never enters a remote URL, the command line's persisted form, or
.git/config. The mirror procedure is rewritten to drive a GitRunner, the old
URL-token machinery is deleted (its reason to exist vanishes), and the procedure's
ordering invariants become testable for the first time through one injected fake.
This closes the audit's HIGH and MEDIUM at their shared root in one structural
change.

User Stories

  1. As an operator, I want forge tokens to never appear in error messages or
    tracebacks, so that pasting a migration failure into a bug report or chat does
    not leak a credential.
  2. As an operator, I want tokens to never be persisted to disk after a run, so a
    shared or hosted machine does not retain my tokens in a mirror clone's git
    config.
  3. As an operator, I want a stalled git clone/fetch/push to abort with a clear
    error after a timeout, not hang the migration indefinitely.
  4. As an operator, I want a missing git-lfs binary to be detected and skipped
    gracefully, not crash an otherwise-successful run.
  5. As an operator, I want the migration's observable behaviour and report output
    to be unchanged by this refactor.
  6. As a maintainer, I want one place that controls how git is invoked, so I never
    have to audit five separate subprocess call sites for consistent timeout and
    redaction.
  7. As a maintainer, I want the git-mirror procedure's ordering invariants locked
    by tests, so a future edit cannot silently reorder pull-head capture, prune,
    mirror push, deleted-branch PR restoration, and LFS.
  8. As a maintainer, I want to add a new git operation without re-implementing
    auth, timeout, or redaction.
  9. As a maintainer, I want the two forge identities (source and target) to be
    bound objects, so a "push to the target URL while authenticating with the
    source token" mismatch is impossible to express.
  10. As a maintainer, I want retiring the old token-in-URL machinery to delete
    code, not leave dead helpers behind.
  11. As a maintainer, I want the refactor confined to the mirror layer, so the
    REST-client, ref-rewriting, issue/release, and orchestration layers are
    untouched.
  12. As a new contributor, I want the mirror procedure to read top-to-bottom as a
    flat list of one-liners, so I can follow the git flow without bouncing between
    helpers.
  13. As a new contributor, I want a single module that documents "this is how we
    run git," so I know exactly where to look and where to add a git operation.
  14. As a security auditor, I want the HIGH (token in error text) and MEDIUM
    (token in git config) findings from the 2026-08-11 report closed at a single
    root cause, so the fix is verifiable in one place.
  15. As a security auditor, I want redaction to scrub the token using the known
    secret, not a blind regex, so a future auth pattern cannot slip through
    unmasked.
  16. As CI, I want the mirror procedure testable without the git binary or any
    network, so the suite stays fast and hermetic.
  17. As CI, I want the recording fake to capture command intent without ever
    holding a token, so test fixtures cannot leak credentials.
  18. As CI, I want a regression guard that fails if any git operation bypasses the
    seam (no direct subprocess calls to git outside GitRunner).
  19. As CI, I want the existing ruff and pytest gates to keep passing.
  20. As a future maintainer, I want a clean seam so an eventual dry-run mode or a
    second git backend is an additive change, not a rewrite.
  21. As a future maintainer, I want per-operation auth to be explicit at each call
    site, so reading the procedure tells me which forge each step touches.
  22. As a future maintainer, I want the path to a formal credential-helper /
    askpass upgrade documented, so process-list hardening is a later swap, not a
    redesign.

Implementation Decisions

  • New module — the git-op seam (GitRunner). It is the sole way git is
    invoked. It owns subprocess execution, per-op timeout, error redaction, and
    auth delivery. It is workdir-agnostic: every operation carries its own
    --git-dir; the seam never touches the mirror workdir.

  • Mirror procedure module rewritten to drive a GitRunner. The procedure
    (clone/fetch → capture pull-heads → prune forge-internal refs → mirror push →
    recreate deleted-branch PR heads → LFS fetch+push) keeps its ordering and keeps
    owning the workdir lifecycle (per-user 0700).

  • Auth delivery. The bearer token is delivered via a non-persisted per-op git
    config override (http.<host>.extraHeader = "Authorization: token <T>"),
    applied per invocation only. The token leaves the remote URL, the persisted
    command line, and .git/config. This is the structural fix for both audit
    findings.

  • Auth selection is per operation and explicit. Each call declares which forge
    it authenticates against: the source, the target, or neither (local ref
    operations such as update-ref). The two forges are represented by a frozen
    value type binding a token-free URL and its token together, so "same forge" is
    an invariant, not two free parameters a caller can drift.

  • Execution shapes map to small verbs, not flags. One verb for
    fire-and-forget (raise on non-zero/timeout); one verb that returns stdout; and
    one success-probe verb that returns a boolean and never raises (used only to
    detect git lfs). stdin input rides on the fire-and-forget verb. This encoding
    removes the footgun where forgetting a "don't raise" flag would turn
    "LFS not installed → skip" into "LFS not installed → crash".

  • The runner is forge-agnostic. It is constructed with only a timeout and an
    optional exec hook; the source/target forge handles live in the procedure and
    are passed per call. "Which two forges" is the migration's concern, not the
    seam's.

  • Retire the three URL-token helpers (URL-tokenization, token-stripping, and
    the on-exit config scrub) and the try/finally scrub block: with the token out
    of URLs there is nothing to scrub. Relocate and generalize the redactor into
    the seam so it scrubs both the legacy oauth2:<token>@ form and the new
    token <T> form (value only — keep "Authorization: token" visible for
    diagnostics).

  • Internal seam for testing. The dependency category is local-substitutable:
    the only external touch is the git binary, and the test stand-in is a
    recording fake of the exec callable. No formal Protocol/port is introduced —
    one real adapter (subprocess) plus one test fake does not yet clear the
    "two real adapters" threshold.

  • CLI error handling unchanged. The CLI already catches the git error type;
    after this change the catch and the redaction become pure defense-in-depth,
    because the token no longer reaches the command line's persisted form.

    Interface shape (from the design-it-twice prototype — decision-rich parts
    only, not a working demo):

    Forge(token-free url, token)                       # frozen value type
    GitRunner(*, timeout, exec = <real subprocess>)    # forge-agnostic
      run(cmd, *, auth=None, stdin=None) -> None       # fire-and-forget; raises GitError
      capture(cmd, *, auth=None) -> str                # returns stdout; raises GitError
      ok(cmd) -> bool                                  # success-probe; never raises
    Exec(cmd, timeout, stdin, auth) -> result          # auth composed INSIDE the adapter,
                                                       # so the recording fake never sees a token
    

Testing Decisions

  • One seam. The feature is tested through GitRunner's external interface,
    exercised via an injected recording fake of the exec callable. This is the
    highest practical seam and covers both the seam module itself (timeout,
    redaction, auth delivery, error contract) and the mirror procedure (which drives
    GitRunner), because the procedure's correctness is its command sequence. The
    ideal seam count — one — is met.
  • Prior art in the repo. test_clients.py injects an httpx.MockTransport
    handler to test the REST client with no network — the identical "inject a fake
    of the external dependency" pattern. The new tests follow that convention.
  • What makes a good test here. Tests assert external behaviour — the ordered
    command sequence, the stdin payloads, and which forge each step authenticated
    against — never internal state. They must survive an internal refactor of the
    seam (if a test has to change when the implementation changes, it is testing
    past the interface). Recording fakes capture command intent only and never hold
    a token.
  • Invariants to lock. (1) pull-heads captured before prune; (2) prune before
    mirror push; (3) mirror push before deleted-branch PR-head push; (4) LFS
    fetch+push run only when the LFS probe succeeds; plus the negative — no LFS
    command is issued when the probe fails. Auth-wiring is asserted: fetch
    authenticates as source, push authenticates as target, local ref ops carry no
    auth.
  • Replace, don't layer. The existing URL-tokenization/token-strip tests are
    deleted (the helpers are gone). The redactor tests move to the seam module's
    tests and are extended to cover the new token <T> pattern.
  • Regression guard. A check (ruff/AST or test) that fails if any git
    operation is invoked outside the seam.
  • Gates. pytest, ruff check ., and ruff format --check . remain green.

Out of Scope

  • The other three architecture-review candidates: the migration-context handle,
    naming the deleted-branch PR-head (_pr/<n>) contract, and collapsing the
    target-repo lifecycle helpers.
  • Promoting the injected exec callable to a formal Protocol/port — only warranted
    if a second real adapter appears (e.g. a dry-run mode); noted as an upgrade
    trigger, not built now.
  • Process-list hardening via a credential helper / GIT_ASKPASS — this closes
    the audit HIGH and MEDIUM; the residual LOW (token briefly visible in the
    process list, already tolerated via the existing token CLI flags) is a later
    swap behind the same seam, not part of this change.
  • Any change to the REST client, cross-reference rewriting, issue/release
    migration, orchestration, or the CLI surface.
  • Incremental/delta sync (already out of scope by existing decision).
  • Seeding the full triage-label vocabulary — only the two labels this issue needs
    are created.

Further Notes

  • Implements the architectural reading of audit/2026-08-11/security-report.md
    findings A09 (HIGH) and A02 (MEDIUM), which the report itself attributes to
    "one defect, three lines of root cause."
  • Top recommendation from the 2026-08-11 architecture review (candidate #2). The
    review report lives in the OS temp directory from that session.
  • Delivered as a single PR; target Python ≥ 3.11, ruff line-length 100.
  • The grilling for this candidate is recorded in the session that produced it
    (scope, auth, delivery, test injection, module split, helper fate, staging all
    settled). The chosen interface is Design C (optimize for the common caller)
    from the design-it-twice comparison.
  • Open implementation-time item: confirm git lfs honours the extraHeader
    override; if it does not, fall back to a credential helper scoped to LFS only —
    an internal knob behind the seam, not an architectural change.

[Generated by AI]

## Problem Statement As the operator/maintainer of the Codeberg → Gitea migrator, I run a one-shot cutover that drives `git` (clone --mirror, push --mirror, ref pruning, LFS) while holding two live forge API tokens. Today the git-mirror layer invokes `git` from **five** separate `subprocess` call sites, and only one of them carries the per-op timeout and token-redaction discipline — the other four bypass it. That makes the token-safety rules a partial bolt-on rather than a property of running git, and it leaves the whole mirror *procedure* (the ordering of pull-head capture, ref pruning, mirror push, deleted-branch PR restoration, and LFS) with no test surface at all. Concretely, the 2026-08-11 security audit logged this as two findings — a **HIGH** (live token embedded in a `GitError` that reaches logs/tracebacks) and a **MEDIUM** (token persisted in plaintext in the mirror clone's `.git/config`) — that share a single architectural root cause: there is no single seam through which git is invoked, so token hygiene cannot be enforced in one place. ## Solution Introduce a single deep module — **GitRunner**, the git-op seam — that is the *only* way `git` is invoked. It owns subprocess execution, per-op timeout, error redaction, and auth delivery. Authentication moves off the remote URL entirely: the bearer token is delivered via a non-persisted per-op git config override, so the token never enters a remote URL, the command line's persisted form, or `.git/config`. The mirror procedure is rewritten to drive a GitRunner, the old URL-token machinery is deleted (its reason to exist vanishes), and the procedure's ordering invariants become testable for the first time through one injected fake. This closes the audit's HIGH and MEDIUM at their shared root in one structural change. ## User Stories 1. As an operator, I want forge tokens to never appear in error messages or tracebacks, so that pasting a migration failure into a bug report or chat does not leak a credential. 2. As an operator, I want tokens to never be persisted to disk after a run, so a shared or hosted machine does not retain my tokens in a mirror clone's git config. 3. As an operator, I want a stalled git clone/fetch/push to abort with a clear error after a timeout, not hang the migration indefinitely. 4. As an operator, I want a missing `git-lfs` binary to be detected and skipped gracefully, not crash an otherwise-successful run. 5. As an operator, I want the migration's observable behaviour and report output to be unchanged by this refactor. 6. As a maintainer, I want one place that controls how git is invoked, so I never have to audit five separate subprocess call sites for consistent timeout and redaction. 7. As a maintainer, I want the git-mirror procedure's ordering invariants locked by tests, so a future edit cannot silently reorder pull-head capture, prune, mirror push, deleted-branch PR restoration, and LFS. 8. As a maintainer, I want to add a new git operation without re-implementing auth, timeout, or redaction. 9. As a maintainer, I want the two forge identities (source and target) to be bound objects, so a "push to the target URL while authenticating with the source token" mismatch is impossible to express. 10. As a maintainer, I want retiring the old token-in-URL machinery to *delete* code, not leave dead helpers behind. 11. As a maintainer, I want the refactor confined to the mirror layer, so the REST-client, ref-rewriting, issue/release, and orchestration layers are untouched. 12. As a new contributor, I want the mirror procedure to read top-to-bottom as a flat list of one-liners, so I can follow the git flow without bouncing between helpers. 13. As a new contributor, I want a single module that documents "this is how we run git," so I know exactly where to look and where to add a git operation. 14. As a security auditor, I want the HIGH (token in error text) and MEDIUM (token in git config) findings from the 2026-08-11 report closed at a single root cause, so the fix is verifiable in one place. 15. As a security auditor, I want redaction to scrub the token using the known secret, not a blind regex, so a future auth pattern cannot slip through unmasked. 16. As CI, I want the mirror procedure testable without the git binary or any network, so the suite stays fast and hermetic. 17. As CI, I want the recording fake to capture command intent without ever holding a token, so test fixtures cannot leak credentials. 18. As CI, I want a regression guard that fails if any git operation bypasses the seam (no direct subprocess calls to git outside GitRunner). 19. As CI, I want the existing ruff and pytest gates to keep passing. 20. As a future maintainer, I want a clean seam so an eventual dry-run mode or a second git backend is an additive change, not a rewrite. 21. As a future maintainer, I want per-operation auth to be explicit at each call site, so reading the procedure tells me which forge each step touches. 22. As a future maintainer, I want the path to a formal credential-helper / askpass upgrade documented, so process-list hardening is a later swap, not a redesign. ## Implementation Decisions - **New module — the git-op seam (GitRunner).** It is the sole way `git` is invoked. It owns subprocess execution, per-op timeout, error redaction, and auth delivery. It is workdir-agnostic: every operation carries its own `--git-dir`; the seam never touches the mirror workdir. - **Mirror procedure module rewritten** to drive a GitRunner. The procedure (clone/fetch → capture pull-heads → prune forge-internal refs → mirror push → recreate deleted-branch PR heads → LFS fetch+push) keeps its ordering and keeps owning the workdir lifecycle (per-user `0700`). - **Auth delivery.** The bearer token is delivered via a non-persisted per-op git config override (`http.<host>.extraHeader = "Authorization: token <T>"`), applied per invocation only. The token leaves the remote URL, the persisted command line, and `.git/config`. This is the structural fix for both audit findings. - **Auth selection is per operation and explicit.** Each call declares which forge it authenticates against: the source, the target, or neither (local ref operations such as `update-ref`). The two forges are represented by a frozen value type binding a token-free URL and its token together, so "same forge" is an invariant, not two free parameters a caller can drift. - **Execution shapes map to small verbs**, not flags. One verb for fire-and-forget (raise on non-zero/timeout); one verb that returns stdout; and one success-probe verb that returns a boolean and never raises (used only to detect `git lfs`). stdin input rides on the fire-and-forget verb. This encoding removes the footgun where forgetting a "don't raise" flag would turn "LFS not installed → skip" into "LFS not installed → crash". - **The runner is forge-agnostic.** It is constructed with only a timeout and an optional exec hook; the source/target forge handles live in the procedure and are passed per call. "Which two forges" is the migration's concern, not the seam's. - **Retire** the three URL-token helpers (URL-tokenization, token-stripping, and the on-exit config scrub) and the `try/finally` scrub block: with the token out of URLs there is nothing to scrub. **Relocate and generalize** the redactor into the seam so it scrubs both the legacy `oauth2:<token>@` form and the new `token <T>` form (value only — keep "Authorization: token" visible for diagnostics). - **Internal seam for testing.** The dependency category is local-substitutable: the only external touch is the `git` binary, and the test stand-in is a recording fake of the exec callable. No formal Protocol/port is introduced — one real adapter (subprocess) plus one test fake does not yet clear the "two real adapters" threshold. - **CLI error handling unchanged.** The CLI already catches the git error type; after this change the catch and the redaction become pure defense-in-depth, because the token no longer reaches the command line's persisted form. *Interface shape (from the design-it-twice prototype — decision-rich parts only, not a working demo):* ``` Forge(token-free url, token) # frozen value type GitRunner(*, timeout, exec = <real subprocess>) # forge-agnostic run(cmd, *, auth=None, stdin=None) -> None # fire-and-forget; raises GitError capture(cmd, *, auth=None) -> str # returns stdout; raises GitError ok(cmd) -> bool # success-probe; never raises Exec(cmd, timeout, stdin, auth) -> result # auth composed INSIDE the adapter, # so the recording fake never sees a token ``` ## Testing Decisions - **One seam.** The feature is tested through GitRunner's external interface, exercised via an injected recording fake of the exec callable. This is the highest practical seam and covers both the seam module itself (timeout, redaction, auth delivery, error contract) and the mirror procedure (which drives GitRunner), because the procedure's correctness is its command *sequence*. The ideal seam count — one — is met. - **Prior art in the repo.** `test_clients.py` injects an `httpx.MockTransport` handler to test the REST client with no network — the identical "inject a fake of the external dependency" pattern. The new tests follow that convention. - **What makes a good test here.** Tests assert external behaviour — the ordered command sequence, the stdin payloads, and which forge each step authenticated against — never internal state. They must survive an internal refactor of the seam (if a test has to change when the implementation changes, it is testing past the interface). Recording fakes capture command intent only and never hold a token. - **Invariants to lock.** (1) pull-heads captured before prune; (2) prune before mirror push; (3) mirror push before deleted-branch PR-head push; (4) LFS fetch+push run only when the LFS probe succeeds; plus the negative — no LFS command is issued when the probe fails. Auth-wiring is asserted: fetch authenticates as source, push authenticates as target, local ref ops carry no auth. - **Replace, don't layer.** The existing URL-tokenization/token-strip tests are deleted (the helpers are gone). The redactor tests move to the seam module's tests and are extended to cover the new `token <T>` pattern. - **Regression guard.** A check (ruff/AST or test) that fails if any git operation is invoked outside the seam. - **Gates.** `pytest`, `ruff check .`, and `ruff format --check .` remain green. ## Out of Scope - The other three architecture-review candidates: the migration-context handle, naming the deleted-branch PR-head (`_pr/<n>`) contract, and collapsing the target-repo lifecycle helpers. - Promoting the injected exec callable to a formal Protocol/port — only warranted if a second *real* adapter appears (e.g. a dry-run mode); noted as an upgrade trigger, not built now. - Process-list hardening via a credential helper / `GIT_ASKPASS` — this closes the audit HIGH and MEDIUM; the residual LOW (token briefly visible in the process list, already tolerated via the existing token CLI flags) is a later swap behind the same seam, not part of this change. - Any change to the REST client, cross-reference rewriting, issue/release migration, orchestration, or the CLI surface. - Incremental/delta sync (already out of scope by existing decision). - Seeding the full triage-label vocabulary — only the two labels this issue needs are created. ## Further Notes - Implements the architectural reading of `audit/2026-08-11/security-report.md` findings A09 (HIGH) and A02 (MEDIUM), which the report itself attributes to "one defect, three lines of root cause." - Top recommendation from the 2026-08-11 architecture review (candidate #2). The review report lives in the OS temp directory from that session. - Delivered as a single PR; target Python ≥ 3.11, ruff line-length 100. - The grilling for this candidate is recorded in the session that produced it (scope, auth, delivery, test injection, module split, helper fate, staging all settled). The chosen interface is Design C (optimize for the common caller) from the design-it-twice comparison. - Open implementation-time item: confirm `git lfs` honours the extraHeader override; if it does not, fall back to a credential helper scoped to LFS only — an internal knob behind the seam, not an architectural change. [Generated by AI]
AlexKucera added the ready-for-agentPRD labels 2026-08-11 14:22:38 +02:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: AlexKucera/codeberg-to-gitea-migrator#1