Skip to content

Harden git invocations on cached repositories - #4902

Merged
Daniel Meppiel (danielmeppiel) merged 20 commits into
mainfrom
danielmeppiel-perf-cache-git-harden
Nov 23, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 20 commits into
mainfrom
danielmeppiel-perf-cache-git-harden

Conversation

@danielmeppiel

@danielmeppiel Daniel Meppiel (danielmeppiel) commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Git always reads a repository's own config. APM keeps some repositories between runs, so their config is now validated against an allow-list before any git run, and is never used otherwise.

Owner: src/apm_cli/cache/cached_repo.py

require_trusted_cached_repo() / cached_repo_is_trusted() parse config (and config.worktree) in-process; nothing is executed. A repository is accepted only when every key is one APM writes, with a value APM would write:

  • core.* repository basics and the line-ending and symlink pins
  • extensions.partialclone / worktreeconfig / objectformat
  • apm.* materialization pins
  • remote.origin.{fetch,tagopt,promisor,partialclonefilter}
  • remote.origin.url, which must name the repository the cache entry is keyed by (its shard, or the local bare a checkout was cloned from)
  • branch.<name>.{remote,merge}

Notes on the allowed keys:

  • apm.*: APM writes exactly two keys, apm.linkMaterialization=git-objects-checkout and apm.sparseMaterialization=complete. They are only compared for equality, in git_cache._checkout_config_values, and are never used as a command, path or URL. Git ignores the apm section, and the allow-list restricts their values to [a-z0-9-]+.
  • branch.<name>.merge: accepts Git's branch-name syntax (for example release+prod or team@main) but rejects whitespace, control characters, ~^:?*[\, .., // and @{. So it can never be read as a URL, a refspec, a path or a revision expression. APM never reads it, and it never chooses a fetch source; the allow-list only checks its shape.

Everything else is refused, including subsection forms ([http "<url>"], [credential "<url>"], [url "<x>"]), includes and anything unparseable.

The check also refuses:

  • commondir and info/attributes
  • active (non-.sample) hooks
  • objects/info/http-alternates
  • object alternates in a bare
  • object alternates in a checkout that point outside the git cache

Inert runs. inert_git_args() and cached_repo_env() apply to every git run in these repositories:

  • core.hooksPath=/dev/null and core.fsmonitor=false
  • GIT_TERMINAL_PROMPT=0
  • GIT_ASKPASS=echo unless APM already set it
  • GIT_ALLOW_PROTOCOL=file:http:https:ssh, so no ext, fd or plaintext git:// transports (git:// is already rejected as a dependency transport)

Global and system config keep their existing handling: network runs already freeze them via git_network_env.

What a refused repository does:

  • A cache bare or checkout is discarded and rebuilt.
  • A fetch into an untrusted bare is refused.
  • A read-only lookup treats it as a miss.
  • A native snapshot raises CodexNativeError.

Guard: transport-platform-cached-repo-git (owner record + MutationCases). It is an AST rule plus literal pins:

  • In each guarded file, every git runner's argv carries the inert args.
  • In the cache and snapshot files, env comes from cached_repo_env().
  • Only cache/git_cache.py may resolve the git cache buckets.
  • _bare_has_sha and _fetch_into_bare_locked must open with the bare trust check; a MutationCase removes each one.
  • The trust checks stay at every point a persisted repository is opened.
  • The unlocked cache-hit probe never evicts. An untrusted checkout is evicted only by _create_checkout's locked re-probe.
  • Refusal messages are redacted before they are logged.

Git runs inside APM-persisted state

Site Repository kind Routed through the owner
cache/git_cache.py _fetch_into_bare_locked (SHA fetch and fallback) git cache bare (db_v1) yes: trust check first (refuse), fenced env, inert args
cache/git_cache.py _bare_has_sha (cat-file) git cache bare yes: trust check (untrusted = missing), fenced env, inert args
cache/git_cache.py _ensure_bare_repo (reuse or clone) git cache bare yes: untrusted bare discarded before use; clone env fenced
cache/git_cache.py get_checkout hit, _create_checkout write-dedup and race re-probe git cache checkout (checkouts_v1) yes: untrusted checkout evicted and rebuilt
cache/git_cache.py _read_only_checkout git cache checkout yes: untrusted = miss (nothing written)
cache/git_cache.py _unmaterialized_paths (ls-files), _pin_sparse_completeness (config), checkout clone/config/checkout, apply_sparse_cone, materialize_tracked_symlinks git cache checkout yes: fenced env, inert args (all callers run after the trust check)
marketplace/client.py catalog fetch git cache (via GitCache.get_checkout) yes (same owner path)
codex_plugins/snapshot.py _git (hash-object, update-index, commit, rev-parse; repair_generation) native snapshot in apm_modules yes: trust check before every run after init, fenced env, inert args
core/legacy_lock_evidence.py git_permits_legacy_adoption (rev-parse, ls-files, status) the user's own repository enclosing a deployed file inert args (no config check: not an APM repository)

legacy_lock_evidence runs status inside the user's own repository, so that repository's own filters apply by design; it is not cache-restorable.

Other git runs operate on fresh per-run temp repositories or on user-owned repositories, not on APM-persisted state: the shared clone cache in deps/bare_cache.py, the downloader temp clones, deps/git_file_transport.py, validation and ref-resolution temp repos, the local-marketplace git show, and policy/_remote.py / policy/ci_checks.py in the project root. policy_v1 and http_v1 hold files only.

Issue and approved scope

Issue: scope approved by the maintainers; see the linked ruling.

Human scope-approval comment: scope approved by the Quality & Lifecycle owner.

Does this PR complete the issue, or what remains? It completes the cached-repository hardening.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable)

tests/integration/test_cached_repo_config.py has 23 real-git cells:

  • Planted bare settings (12 cells). One APM-shaped cached bare per setting APM never writes: credential.helper (401 origin), http.proxy (407 proxy), URL-scoped http.<url>.proxy / credential.<url>.helper, include.path to a file outside the cache, core.fsmonitor, core.hooksPath, filter.*, core.sshCommand, core.gitProxy, http.sslVerify=false and url.<x>.insteadOf. Each drives GitCache.get_checkout for a commit the bare lacks, the path apm install --update takes, and asserts the entry is discarded and no configured command runs.
  • Active hook: an active hook in a cached bare is discarded.
  • Checkout: a cached checkout with an unexpected setting is rebuilt.
  • Side files (3 cells): info/attributes, commondir and out-of-cache alternates are refused.
  • Native snapshot: a snapshot with an unexpected setting is refused and nothing runs.
  • Control: an unmodified cached bare is reused as is, with no discard and no network.
  • User config: a local filter.lfs.* is refused even when the user's own global config defines the same driver. A local plus a URL-scoped credential.<url>.helper is refused alongside a user-global helper; the clone fails cleanly, as it does without them.
  • Lock order: an untrusted checkout is still present when the locked rebuild runs, so it is evicted only under its shard lock.
  • Redaction: a refused URL-scoped key never prints its credential.

Against main b8a12c29 the vector cells fail; the control passes. On this branch all 23 pass.

Tests that drive cache mechanics with fake (empty) repositories now use tests/utils/cached_repo_trust.py. Three real-git tests changed their expected outcome; each is now stricter:

  • A bare with a local URL rewrite is refused before fetching.
  • A bare with a sibling remote is refused. The fallback-refspec assertion still runs on an unmodified bare.
  • A checkout with core.autocrlf=true is refused rather than rematerialized.

Local runs (pytest -n 2, targeted):

Scope Result
tests/integration/test_cached_repo_config.py 23 passed
cache, hermetic, coverage, autocrlf, eol pin, hook isolation, sparse/symlink repair, materialization, shared clone, codex snapshot/registrar suites 574 + 166 passed
tests/unit/deps/, tests/unit/marketplace/, tests/unit/install/, downloader/sparse/lockfile-replay/Windows-symlink integration files 7738 passed
architecture runner + owner-rule mutations (-k inventory/registered/cached_repo) 89 passed
scripts/lint_architecture_boundaries.py --root . clean
scripts/check_complexity_ratchet.py --base-ref b8a12c29 clean
ruff check / ruff format --check on changed files clean

Changelog

  • One fragment per section, changelog.d/<pr>.<section>.md, holding
    one line: user-visible effect first, 25 words or fewer, ending with
    (#PR); breaking changes only under upgrade notes; no Highlights; no
    new lines under ## [Unreleased]. See changelog.d/README.md and
    .github/instructions/changelog.instructions.md.
  • N/A -- internal-only change (CI, tests, refactor).

Spec conformance (OpenAPM v0.1)

  • Spec edit
  • Manifest edit
  • Test edit
  • CONFORMANCE.{md,json} regenerated
  • N/A -- this PR does not change OpenAPM-observable behaviour.

Repositories APM keeps between runs (git cache bares and checkouts, native
snapshots) are now checked before any git run: their config is parsed
in-process and accepted only when every key is one APM writes, with a value
APM would write. Includes, side config files, active hooks and object
alternates that leave the cache are refused. A refused cache entry is
discarded and rebuilt. Every git run there is also inert: no hooks, no
fsmonitor, no terminal prompt, a fixed askpass and no ext/fd transports.

Owner: cache/cached_repo.py, guarded by transport-platform-cached-repo-git.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 02:24
Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical findings allow checkout deletion outside its lock, leave trust-check removal undetected by the architecture guard, and make the new test module violate the taxonomy ratchet.

5 open issues
What changed in this PR

This PR centralizes trust checks for Git repositories APM retains between runs, aiming to prevent cached repository settings from activating unexpected Git behavior.

Changes:

  • Adds config allow-list validation, side-file checks, and restricted Git invocation settings.
  • Applies the checks to cached repositories and native snapshots, with inert arguments for legacy-lock probes.
  • Adds security regression tests, an architecture guard, and a changelog entry.
File Description
tests/​utils/​cached_repo_trust.py Adds a trust-check patch helper for fake repositories.
tests/​unit/​test_git_cache_branch_coverage.py Applies the helper to cache branch tests.
tests/​unit/​scripts/​test_architecture_runner.py Registers the guard in the expected rule inventory.
tests/​unit/​cache/​test_git_cache_hardening.py Adapts mocked fetch tests to trust validation.
tests/​integration/​test_git_hook_env_isolation.py Updates expectations for rejected repository settings.
tests/​integration/​test_git_cache_hermetic.py Adapts cache mechanics tests to trust validation.
tests/​integration/​test_git_cache_autocrlf.py Updates the expected checkout-repair failure.
tests/​integration/​test_cached_repo_config.py Adds rejection and legitimate-cache reuse coverage.
tests/​integration/​test_cache_coverage.py Applies the helper to fake cache repositories.
tests/​integration/​test_architecture_owner_rule_mutations.py Adds an environment-fence removal mutation.
src/​apm_cli/​core/​legacy_lock_evidence.py Adds inert Git arguments to legacy-adoption probes.
src/​apm_cli/​codex_plugins/​snapshot.py Validates persisted snapshots before Git operations.
src/​apm_cli/​cache/​git_cache.py Integrates trust checks, eviction, and restricted environments.
src/​apm_cli/​cache/​cached_repo.py Defines the shared trust validator and invocation settings.
scripts/​architecture_linter/​groups/​transport_platform.py Includes the cached-repository guard.
scripts/​architecture_linter/​checks/​transport_cached_repo_git.py Adds checks for guarded Git calls and trust entrypoints.
changelog.d/​4902.security.md Documents cached-repository validation.
.apm/​architecture/​owners/​transport-auth-platform.json Registers the canonical cached-repository owner.

Review effort: Balanced

Comment thread src/apm_cli/cache/git_cache.py Resolved
Comment thread src/apm_cli/cache/cached_repo.py Resolved
Comment thread src/apm_cli/cache/cached_repo.py Resolved
git:// is already rejected as an insecure dependency transport, so cached
repository runs no longer allow it. Two cells show a repository-local filter
or credential helper is refused even when the user's own global config
defines a driver or helper of the same kind.

Co-authored-by: Copilot App <[email protected]>
The guard now requires the object probe and the fetch into a cached bare to
open with the owner's trust check, with a mutation for each. The unlocked
cache-hit probe no longer evicts; the locked re-probe does. Branch names
follow Git's own syntax, and a refusal message is redacted before it is
logged.

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Recursive alternates can escape the cache boundary, and persisted-cache Git callers bypass required protections without being detected by the architecture guards.

4 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Accept escaped quotes in Git branch headers

src/​apm_cli/​cache/​cached_repo.py:34

A valid default branch such as release"prod makes Git write [branch "release\"prod"], which this regex rejects because it forbids backslash escapes. Subsequent cache hits therefore rebuild the legitimate checkout, and read-only lookups miss. Accept Git's escaped quote/backslash syntax in subsection headers and add a reuse regression for a quoted default branch.

5 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/cache/cached_repo.py Resolved
The L2 ref lookup asks GitCache.bare_ref_sha instead of opening a bare
itself, cached checkouts are link-checked through the owner, chained object
alternates are refused, and the guard checks each bare and checkout entry
point (one mutation case per guard).

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Cache-path validation gaps allow Git to access object databases outside the cache, while removal of _rev_parse leaves five existing tests failing before their assertions.

1 open issue
3 previously missed issues

In code that hasn't changed since last review

High severity Preserve trailing spaces when validating alternates paths

src/​apm_cli/​cache/​cached_repo.py:166

Git preserves trailing spaces in unquoted alternates paths, but this check removes them. An alternate ending in /db_v1/<shard>/objects is therefore validated against objects, even if the distinct objects path links outside the cache, allowing Git to read external objects. Resolve and inspect the exact pathname Git uses rather than trimming it.

High severity Reject object directories that symlink outside the cache

src/​apm_cli/​cache/​cached_repo.py:204

Only the Git directory itself is checked for symlinks, so a repository whose objects directory links outside the cache passes when the target has no alternates. Git can then read or write that external database during cached fetches or native snapshot commits. Reject linked object-directory paths through the existing path-security helper and add regressions for both repository types.

Medium severity Accept escaped quotes in Git branch subsection headers

src/​apm_cli/​cache/​cached_repo.py:34

For a valid default branch such as release"prod, Git writes [branch "release\"prod"], which this regex rejects because it forbids backslashes in subsection headers. Subsequent installs rebuild the valid checkout, and read-only lookups miss it. Accept Git's escaped quote/backslash syntax and add a reuse regression for a quoted default branch.

4 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/deps/tiered_ref_resolver.py Resolved
The tiered resolver's bare lookup and the downloader's cached-checkout link
check now go through GitCache.bare_ref_sha and cached_repo.validate_cached_links;
the guards that pinned the old call sites follow them with the same strictness.
Tests patch the new downloader seam.

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Removing _rev_parse leaves existing resolver tests patching a nonexistent method, causing AttributeError before execution; their cache doubles and assertions must be migrated to bare_ref_sha(url, ref).

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because unpublished critical findings show bypassable alternate-path validation and unfenced cached-checkout Git reads that can trigger network fetches.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because alternate-path validation can disagree with Git’s parsing, allowing access to object databases outside the cache despite containment checks.

No open issues 🎉

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved containment flaws allow Git to access object databases outside the cache, and symlinked object directories can receive writes during repair.

5 open issues

Review effort: Balanced

Comment thread src/apm_cli/cache/cached_repo.py Resolved
Object alternates are read line by line as written, without trimming. Git
state is read only from regular files. A cached repository needs a
well-formed HEAD, and snapshot Git commands name their repository
explicitly. Branch sections with escaped quotes are accepted.

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The absolute --git-dir argument reintroduces Git’s directory-length limit, causing native snapshot creation and repair to fail in deep paths, particularly on Windows.

1 open issue
5 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/codex_plugins/snapshot.py Resolved
Snapshot Git commands pass a relative Git directory and work tree, which
keeps paths short. HEAD is accepted with the trailing whitespace Git
trims. Unit fixtures lay down a HEAD like the repositories they model.

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because cache validation can accept checkouts missing required Git directories, allowing sparse probes to target an enclosing user repository and modify its configuration.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved cache trust-gate flaws permit unchecked parent-repository execution, unsafe object symlink or FIFO handling, and external-file disclosure through symbolic HEAD traversal.

3 open issues

Review effort: Balanced

Comment thread src/apm_cli/cache/cached_repo.py Resolved
Comment thread src/apm_cli/cache/cached_repo.py Resolved
Comment thread src/apm_cli/cache/cached_repo.py Resolved
… inside it

Object payloads are checked like every other entry; objects/ and refs/ must
be present. Symbolic HEAD names follow Git's ref-name rules, and the HEAD
reader stays inside refs/ and returns only object ids. Config lines are
split only where Git splits them. Git runs on cached checkouts and
snapshots never look above the repository. An entry that Git's own
maintenance removes while it is listed is skipped.

Co-authored-by: Copilot App <[email protected]>
Comment thread src/apm_cli/cache/cached_repo.py Fixed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because cache-hit validation misses symlinks or FIFOs in alternate object databases, potentially allowing Git to read outside the cache or block.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because cache trust checks can miss tampered backing objects, potentially allowing external-file reads or blocked Git processes.

No open issues 🎉

Review effort: Balanced

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit a998d74 into main Nov 23, 2026
76 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-perf-cache-git-harden branch November 23, 2026 09:22
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 23, 2026
Owner registry and transport rule group take both sides: the deploy-store
owner and #4902's cached-repository git owner.

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants