Files
codeberg-to-gitea-migrator/audit/2026-08-11/security-report.md
T
AlexKucera 299c061f26
CI / test (push) Canceled after 0s
fix(security): mask forge tokens in logs and disk
Close two token-leak paths in the git mirror and harden the supply
chain per the OWASP audit (audit/2026-08-11/security-report.md).

Runtime fixes:
- mirror GitError masks the embedded oauth2:<token> in both the
  failing command line and git's stderr before raising; cli now
  catches GitError with a clean message instead of an uncaught
  traceback that printed the live token.
- Scrub token-bearing remote URLs from the bare config at the end
  of each run so tokens aren't persisted in .git/config.
- Default mirror workdir is per-user 0700 (/tmp/cb2gitea-<uid>),
  not a world-readable /tmp/cb2gitea.

Supply chain:
- Commit uv.lock; CI installs via uv sync --frozen (hash-verified).
- Pin Gitea Actions to commit SHAs, not mutable @vN tags.
- Pin the ruff rule set and exclude audit/ for reproducible linting.

Adds tests/test_mirror.py for the redaction helpers.
2026-08-11 11:48:32 +02:00

18 KiB
Raw Blame History

Security Audit Report

Project: codeberg-to-gitea-migrator Date: 2026-08-11 Auditor: Claude — security-scanner skill Framework: OWASP Top 10:2025 Scope: src/codeberg_to_gitea_migrator/ (all 7 modules), tests/, pyproject.toml, .gitea/workflows/ci.yml Technology Stack: Python 3.11 CLI tool — httpx>=0.27 (REST client), typer>=0.12 (CLI), subprocess git calls (mirror/LFS). Bearer-token API auth. No DB, no web framework, no network listener.


Executive Summary

This is a local one-shot CLI run by a trusted operator to migrate one repo from Codeberg to a self-hosted Gitea. That shapes the whole posture: there is no unauthenticated remote attack surface — no HTTP listener, no multi-tenant input, no database. The classic OWASP web categories (SQLi, XSS, CSRF, IDOR, broken session auth) mostly do not apply, and the code is clean where they could (subprocess uses argv lists with no shell; no eval/exec/pickle/yaml.load; API calls use header auth, not URL auth).

Where this codebase does carry real risk is credential hygiene for the two forge API tokens (Codeberg + Gitea). The git-mirror path injects the raw token into HTTPS git URLs (oauth2:<token>@host), and three things follow from that:

  1. On any git failure the token lands in the raised GitError message, which is never caught → an uncaught traceback prints the live token to stderr/CI logs/wherever the operator pastes the error. This is the single most important fix.
  2. The authed URL is written into the bare mirror clone's .git/config on disk (in a tempdir that is shared/world-readable on Linux), persisting both tokens in plaintext after the run.
  3. Tokens are also accepted as plain CLI flags, exposing them in the process list and shell history (the env-var path is already the documented default, so this is defense-in-depth).

Supply-chain posture is typical for a small Python CLI: version ranges instead of a lock file, no hash pinning, and CI actions pinned to mutable @vN tags rather than commit SHAs.

No actively-exploitable remote vulnerability was found. The findings are credential-leak and supply-chain-integrity hardening.

Overall Risk Score: 17 (Moderate Risk)

Severity Count
Critical 0
High 1
Medium 1
Low 3
Info 1
Total 6

Findings

A01:2025 — Broken Access Control

No issues identified. Checked: there is no HTTP listener, no route/handler authorization surface, no session management, and no database. owner/name from the CLI flow only into authenticated API path segments (/repos/{owner}/{name}) and git HTTPS URLs — never into a shell or a query — and the caller is the trusted operator. No IDOR/CSRF/force-browsing patterns apply to a local CLI. (See A06 for a minor input-validation observation on owner/name.)


A02:2025 — Security Misconfiguration

MEDIUM — Forge tokens persisted in plaintext in the mirror clone's git config

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 104–112 (_ensure_remote), 130–131, 135, 138, 149, 172
  • CWE: CWE-312: Cleartext Storage of Sensitive Information; CWE-522: Insufficiently Protected Credentials
  • Reachability: Local-only
  • Description: The git-mirror path authenticates by embedding the raw token in the remote URL (oauth2:<token>@host). Every git subcommand that registers a remote persists that URL verbatim into the bare clone's .git/config: clone --mirror, remote set-url origin, and remote add target. The mirror is left on disk by design ("useful for inspection / re-push"). The default workdir is tempfile.gettempdir() / "cb2gitea" (migrate.py:148) — on Linux that is /tmp, world-readable, so any local user can cat .../cb2gitea/<name>.git/config and read both forge tokens after a run.
  • Evidence:
    # mirror.py
    def _authed(url, token):
        ...
        userinfo = f"oauth2:{quote(token, safe='')}"
        return urlunsplit(parts._replace(netloc=f"{userinfo}@{parts.netloc}"))
    ...
    src = _authed(source_url, source_token)   # token embedded in URL
    tgt = _authed(target_url, target_token)
    ...
    _run(["git", "--git-dir", str(bare), "remote", "set-url", "origin", src])  # → .git/config
    _run(["git", "clone", "--mirror", src, str(bare)])                         # → .git/config
    _ensure_remote(bare, "target", tgt)                                        # → .git/config
    
  • Recommendation: Keep tokens out of stored URLs. Use git's credential helper / -c config that is not persisted, scrub the config after the run, or at minimum write the workdir to a per-user 0700 directory. Minimal fix — redact on cleanup and lock the workdir:
    # migrate.py — private workdir
    workdir = workdir or Path(tempfile.gettempdir()) / f"cb2gitea-{os.getuid()}"
    workdir.mkdir(parents=True, exist_ok=True)
    workdir.chmod(0o700)
    
    # mirror.py — don't persist token-bearing URLs: pass creds via -c http.https.<host>.extraHeader
    # and rewrite config remote URLs to their bare (unauthed) form before leaving them on disk.
    

A03:2025 — Software Supply Chain Failures

LOW — Dependencies are not lock-filed or hash-pinned

  • File: pyproject.toml
  • Line(s): 15 (dependencies = ["httpx>=0.27", "typer>=0.12"]); .gitea/workflows/ci.yml:16 (python -m pip install -e ".[dev]")
  • CWE: CWE-494: Download of Code Without Integrity Check
  • Reachability: Local-only / build-time
  • Description: Versions are lower-bound ranges (>=), there is no lock file (uv.lock / poetry.lock / pinned requirements.txt — none present), and CI installs without --require-hashes. Builds are non-reproducible and a compromised PyPI mirror or dependency could slip a malicious artifact into an install. Low impact for a local CLI, but it is the project's only integrity gap on the install side.
  • Evidence:
    # pyproject.toml
    dependencies = ["httpx>=0.27", "typer>=0.12"]
    
  • Recommendation: Generate and commit a lock file (uv lock or pip freeze > requirements.txt with hashes) and install from it in CI with --require-hashes. Pin to exact versions for reproducibility.

A04:2025 — Cryptographic Failures

No issues identified. Checked: the app performs no cryptography itself. TLS is delegated to httpx, which defaults to certificate verification on (clients.py:45 constructs httpx.Client(...) with no verify=False). No hardcoded keys, no password hashing (N/A — bearer tokens only), no weak RNG used for security purposes, no MD5/SHA1, no base64-as-encryption. (The token-in-URL pattern noted under A02 is a storage/logging problem, not a crypto-strength problem — the URL still travels over TLS.)


A05:2025 — Injection

No issues identified. Checked: command injection is correctly avoided — all git calls use argv lists with shell unset, explicitly annotated # noqa: S603 - argv list, no shell (mirror.py:34, 43, 98, 106). No SQL (no DB). No eval/exec/compile, no os.system/os.popen, no pickle/yaml.load, no template rendering, no HTML output (no XSS surface). Issue/PR bodies are rewritten with bounded regex (refs.py) and POSTed as JSON values to the Gitea API — any rendering is the server's responsibility. (follow_redirects=True on the ApiClient and operator-supplied forge URLs were reviewed; no exploitable SSRF under this tool's local-operator trust model — the operator points the tool only at forges they themselves chose.)


A06:2025 — Insecure Design

INFO — No validation of owner / name path segments

  • File: src/codeberg_to_gitea_migrator/cli.py
  • Line(s): 94–104 (_parse_repo); consumed by migrate.py and mirror.py:_git_url
  • CWE: CWE-20: Improper Input Validation (observation, not exploitable here)
  • Reachability: Local-only (operator-supplied)
  • Description: _parse_repo splits on the first / with no charset validation; owner/name then interpolate into API paths and a git URL. Because they are never passed to a shell and the target is the operator's own authenticated forge, this is not exploitable — an odd value just yields a 404. Noting it only as defense-in-depth: a future change that reused these values in a shell or filesystem path would inherit no validation.
  • Evidence:
    # cli.py
    def _parse_repo(repo, source_url, source_token):
        if "/" in repo:
            owner, name = repo.split("/", 1)   # no charset / length / shape check
            return owner, name
    
  • Recommendation: Optional — validate owner/name against ^[A-Za-z0-9._-]+$ before use, so the invariant is enforced at the boundary rather than relied upon by every downstream caller.

A07:2025 — Authentication Failures

LOW — API tokens accepted as plaintext CLI flags

  • File: src/codeberg_to_gitea_migrator/cli.py
  • Line(s): 37–42
  • CWE: CWE-214: Invocation of Process Using Visible Sensitive Data from Command Line; CWE-522: Insufficiently Protected Credentials
  • Reachability: Local-only
  • Description: --source-token / --target-token expose the forge tokens in the process list (ps/Activity Monitor), shell history, and any wrapper script args. The safer env-var path (CODEBERG_TOKEN / GITEA_TOKEN) is already supported and is the documented default, so this is defense-in-depth — but the flag remains the easy footgun.
  • Evidence:
    source_token: str = typer.Option("", "--source-token", envvar="CODEBERG_TOKEN", ...)
    target_token: str = typer.Option("", "--target-token", envvar="GITEA_TOKEN", ...)
    
  • Recommendation: Prefer the env vars. If the flags must stay, document the exposure prominently and consider hiding the value (typer.Option(..., show_default=False)) — though Typer/Click still receive it in argv. Simplest durable fix: keep env-var-only and drop the flags.

A08:2025 — Software or Data Integrity Failures

LOW — CI workflow actions pinned to mutable version tags

  • File: .gitea/workflows/ci.yml
  • Line(s): 12–13
  • CWE: CWE-345: Insufficient Verification of Data Authenticity; CWE-494: Download of Code Without Integrity Check
  • Reachability: Build-time (CI)
  • Description: actions/checkout@v4 and actions/setup-python@v5 pin to moving major-version tags, not immutable commit SHAs. If either tag were ever moved to a malicious commit (the classic actions supply-chain attack), this CI would run it. Low likelihood, standard hardening gap.
  • Evidence:
    - uses: actions/checkout@v4
    - uses: actions/setup-python@v5
    
  • Recommendation: Pin to full commit SHAs, e.g. actions/checkout@<sha>. Automate with Dependabot/Renovate so updates are deliberate PRs.

No deserialization integrity issues: the app only json()-parses responses from authenticated forge APIs (no pickle/marshal/yaml.load/readObject).


A09:2025 — Security Logging and Alerting Failures

HIGH — Live forge token leaked in uncaught GitError traceback

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 33–48 (_run/_run_capture raise at 38 and 47); unhandled in cli.py:66–84
  • CWE: CWE-532: Insertion of Sensitive Information into Log File; CWE-209: Generation of Error Message Containing Sensitive Information
  • Reachability: Local-only to trigger, but the leak propagates wherever the operator sends the error (bug reports, chat, CI logs)
  • Description: The git-mirror path authenticates via an oauth2:<token>@host URL (mirror.py:29). On any non-zero git exit, _run/_run_capture build the exception as f"git failed (...): {' '.join(cmd)}\n{stderr}" — and cmd contains the authed URL, so the live source and/or target token is embedded in the exception text. GitError is a RuntimeError that is never caught (cli.migrate handles only MigrationError and ApiError), so a failed clone/fetch/push surfaces as a raw Python traceback on stderr with the token in cleartext. Realistic outcome: the operator pastes the traceback into a Gitea/Codeberg issue or a chat, or it lands in a CI log visible to collaborators — and a forge token (broad repo read/write/delete scope) is disclosed. By the pure OWASP rubric "exposed credentials" trends Critical; rated High here because exploitation is gated on the operator propagating the message, not on a remote attacker. Either way it is the #1 fix.
  • Evidence:
    # mirror.py — token is in `cmd`
    def _run(cmd, cwd=None):
        proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
        if proc.returncode != 0:
            raise GitError(f"git failed ({proc.returncode}): {' '.join(cmd)}\n{proc.stderr.strip()}")
                                    # ^^^ cmd includes "https://oauth2:<TOKEN>@host/..."
    
    # cli.py — GitError is not in the caught types, so it escapes as a traceback
    try:
        report = migrate_repo(...)
    except MigrationError as exc: ...
    except ApiError as exc: ...        # GitError falls through → uncaught traceback on stderr
    
    Compounding factor: git itself echoes the failing remote URL in stderr on clone/push failure, so proc.stderr.strip() is a second copy of the token in the same message.
  • Recommendation: (a) never put the secret in cmd text — pass credentials via a non-persisted -c http.<url>.extraHeader="Authorization: token <tok>" or an env-passed credential helper, so the URL and the command line stay clean; (b) redact known-secret URLs from any error surfaced to the user; (c) catch GitError in cli.migrate and emit a clean message. Minimal patch for the exception text:
    # mirror.py
    import re
    _SECRET = re.compile(r"(oauth2:)[^@]+(@)")
    
    def _redact(s: str) -> str:
        return _SECRET.sub(r"\1***\2", s)
    
    def _run(cmd, cwd=None):
        proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
        if proc.returncode != 0:
            shown = [_redarg(a) for a in cmd]   # _redarg applies _redact to URL-shaped args
            raise GitError(f"git failed ({proc.returncode}): {' '.join(shown)}\n{_redact(proc.stderr.strip())}")
    
    And in cli.py add except GitError as exc: typer.echo(f"git error: {exc}", err=True); raise typer.Exit(1).

A10:2025 — Mishandling of Exceptional Conditions

Cross-reference — the same GitError-escapes-uncaught defect described under A09 is also an A10 instance of CWE-209 (sensitive info in an error message) and CWE-755 (improper handling of an exceptional condition: a known, expected failure mode — git failing — has no handler and surfaces internals). Scored once under A09; listed here so the A10 category reflects it. No other A10 issues: there are no empty/swallowing except blocks (the one broad-ish catch in issues.py:_merge_pr:135 is intentional best-effort with a debug log), error paths fail closed (an invalid token → 401 → ApiError → exit 1), and ApiClient resources are released via context managers.


Risk Score Breakdown

Scoring: Critical = 10, High = 7, Medium = 4, Low = 2, Info = 0.

Category Critical High Medium Low Info Points
A01 — Broken Access Control 0 0 0 0 0 0
A02 — Security Misconfiguration 0 0 1 0 0 4
A03 — Supply Chain Failures 0 0 0 1 0 2
A04 — Cryptographic Failures 0 0 0 0 0 0
A05 — Injection 0 0 0 0 0 0
A06 — Insecure Design 0 0 0 0 1 0
A07 — Authentication Failures 0 0 0 1 0 2
A08 — Data Integrity Failures 0 0 0 1 0 2
A09 — Logging & Alerting Failures 0 1 0 0 0 7
A10 — Exceptional Conditions 0 0 0 0 0 0
Total 0 1 1 3 1 17

Risk Rating: 17 → Moderate (0–10 Low | 11–30 Moderate | 31–60 High | 61+ Critical)


Remediation Priority

Ordered by exploitability × impact, not by severity label.

  1. (A09, High) Stop putting forge tokens in git command lines / error text. Highest impact: a leaked token grants full repo read/write/delete on the forge account. Move auth to a non-persisted git -c http.<url>.extraHeader=... (or a credential helper), redact oauth2: URLs from any surfaced error, and add an explicit except GitError in cli.migrate. One defect, three lines of root cause.
  2. (A02, Medium) Stop persisting tokens in the mirror clone's .git/config. Same root cause as #1 (token in URL). Either rewrite stored remote URLs to their bare form after the run, or write the workdir to a 0700 per-user directory so the plaintext config isn't world-readable on /tmp.
  3. (A08/A03, Low) Pin CI actions to commit SHAs and add a locked, hash-pinned dependency file. Standard supply-chain hardening; closes the only integrity gaps on the build/install side.
  4. (A07, Low) Deprecate the --source-token / --target-token CLI flags in favor of the already-supported env vars, to remove process-list/history exposure.

Methodology

Static analysis against OWASP Top 10:2025. Each category was evaluated using the security-scanner reference patterns (pattern detection via grep/AST, localized 5–10 line reads for confirmation), dependency-manifest and CI inspection, and configuration review. The intended specialist-agent-per-category fan-out was unavailable in this environment (runs.all not supported), so a single auditor with full read of the codebase (all 7 source modules, ~700 LOC) applied each category's reference directly; findings were then confirmed with targeted greps (GitError/catch sites, secret handling, dangerous-call scan, lock-file presence). Analysis covered src/codeberg_to_gitea_migrator/, tests/, pyproject.toml, and .gitea/workflows/ci.yml.

Trust model note: the project is a local CLI run by a trusted operator with no network listener. Severity was calibrated to reachability throughout — there is no remote-unauthenticated attack surface, so most findings are credential-hygiene and supply-chain-integrity rather than remotely exploitable vulns.

Limitations: Static analysis only — no dynamic/runtime testing, no dependency CVE database scan (run pip-audit / osv-scanner against a resolved lock file for live CVE coverage), no network-level analysis. Dependency versions were assessed for pinning posture, not for current known CVEs.