Skip to content

Verify cached checkouts against their commit objects - #4891

Merged
Daniel Meppiel (danielmeppiel) merged 24 commits into
mainfrom
danielmeppiel-perf-checkout-verify
Nov 23, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 24 commits into
mainfrom
danielmeppiel-perf-checkout-verify

Conversation

@danielmeppiel

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

Copy link
Copy Markdown
Collaborator

Description

Package checkouts are now verified against their commit before their bytes are hashed or deployed. This covers both the persistent git cache and the downloader's direct clones.

  • Owner: src/apm_cli/cache/checkout_verify.py
    • verify_checkout() / require_verified_checkout() read objects through one git cat-file --batch per checkout. Every object read is re-hashed against its id (sha1 or sha256): the commit, every reachable tree, and each blob it compares.
    • Every working-tree file outside .git must hold its blob's bytes.
    • Verification never runs a Git filter or driver: line endings come from the commit's own verified .gitattributes; paths with filter, ident or working-tree-encoding attributes must hold their exact blob.
    • File modes and sparse-cone membership are checked; consumers check the bytes they copy or read against what verification accepted, and a copy must be complete.
    • Tracked links must hold their resolved targets (the same _LinkResolver plan the materializer uses).
    • An untracked file in scope fails, and so does a missing one. Sparse checkouts are checked within their cone.
    • Positive verdicts are memoized in-process only, per (commit, resolved path, scope). Nothing is persisted.
  • GitCache.get_checkout covers hit, fill and read-only lookup. A checkout that fails is rebuilt once from a fresh fetch (its bare is discarded too), then refused (RuntimeError). Read-only lookups treat it as a miss (LookupError).
  • A modified cache checkout is now rebuilt from the commit, with a warning, instead of refused. The lifecycle cells that expected a refusal for a modified cache copy now assert the warning and the rebuilt bytes; the refusal cells moved to a commit that can no longer be fetched.
  • Stacked on Harden git invocations on cached repositories #4902 (lands after it).
  • GitHubPackageDownloader checks both direct-clone sites (subdirectory and whole-repo clones) and fails closed.
  • Guard: transport-platform-checkout-verified (owner record + MutationCase) requires the verification call at all three sites and the re-hash, untracked and missing checks in the owner.
  • Tests that build fake .git directories to drive hit, miss and evict mechanics now use tests/utils/checkout_trust.py to stub the verifier. The verifier itself is tested against real repositories.

Issue and approved scope

Issue: hardening follow-up; no separate public issue.

Fixes #4980 (attributes are resolved in priority order, so a later -macro line cancels the macro).

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

Does this PR complete the issue, or what remains? It completes the verification. Allowed follow-up (optimization only): share one cat-file --batch process per run across checkouts, keeping the verdict in-process only.

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/unit/cache/test_checkout_verify.py has 12 cells, all against real git:

  • A genuine checkout verifies.
  • A modified working file with HEAD intact fails.
  • A modified loose blob with a matching working file fails.
  • A modified tree object fails.
  • A modified commit object fails.
  • An untracked file fails, both for the whole checkout and inside a sparse scope.
  • A linked package checkout verifies.
  • The cache rebuilds a modified checkout with the true bytes and drops untracked files.
  • A read-only reader treats a modified checkout as a miss.
  • An empty cache yields a verified checkout.
  • A direct clone is refused on mismatch.
  • Only full object ids verify; an abbreviation resolves to HEAD.

Local runs (pytest -n 2, targeted):

Command scope Result
tests/unit/cache/test_checkout_verify.py 12 passed
cache + hermetic + coverage suites touching get_checkout 181 passed
downloader suites (tests/unit/deps/, shared clone, bare cache, sparse, eol pin, autocrlf, sparse-symlink repair, lockfile replay, ...) 2239 + 249 passed
tests/unit/scripts/test_architecture_runner.py + tests/integration/test_architecture_owner_rule_mutations.py 1314 passed
scripts/lint_architecture_boundaries.py --root . clean
scripts/check_complexity_ratchet.py --base-ref d4c1e627 clean
ruff check / ruff format --check on changed files clean

tests/unit/cache/test_git_env.py::test_clone_streams_git_progress_to_reporter fails when run in isolation on base d4c1e627 too. That is a GitPython import-order issue, unrelated to this change.

Cost (CI perf bench, base d4c1e627 vs new b7933814, tree-10, RTT 30 ms, 3 pairs, 0 errors)

Paired CPU new/base (user+sys including children):

journey Linux 45095507260 macOS 45095557534 Windows 45095509828
install-noop 0.995 1.003 1.011
install-locked-warm 1.030 1.115 1.032
install-warm 1.028 1.084 1.045
install-frozen-warm 1.023 1.025 1.052

The cost is one extra git process per dependency (spawns 23->33 on locked-warm and warm, 29->39 on frozen-warm), plus re-hashing what is read. Requests are unchanged and no-op is unaffected. This cost was accepted for a correctness fix.

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.

apm-spec-waiver: cache-integrity verification and test fixtures only; no OpenAPM manifest, lockfile or resolver semantics change

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

Critical verification gaps can admit tampered or unverified bytes into packages, while stale verdicts, cache-replacement races, and a missing test promise marker remain unresolved.

7 open issues
What changed in this PR

This PR adds commit-based verification before APM consumes cached or directly cloned package checkouts, aiming to prevent altered content from being hashed or deployed.

Changes:

  • Adds a shared verifier for Git objects, working-tree bytes, materialized links, and unexpected or missing files.
  • Integrates verification into cache retrieval and direct downloads, with cache rebuild or refusal on failure.
  • Adds regression tests, architecture enforcement, and a security changelog entry.
File Description
tests/​utils/​checkout_trust.py Adds a verifier stub for fake-checkout tests.
tests/​unit/​test_git_cache_branch_coverage.py Applies the stub to cache integrity tests.
tests/​unit/​scripts/​test_architecture_runner.py Registers the new guard in the expected inventory.
tests/​unit/​deps/​test_github_downloader.py Adapts mocked downloader tests.
tests/​unit/​deps/​test_github_downloader_package_download.py Adapts package-download and cache tests.
tests/​unit/​cache/​test_proxy_compat.py Stubs verification in URL-rewrite tests.
tests/​unit/​cache/​test_git_cache.py Stubs verification for cache-flow fixtures.
tests/​unit/​cache/​test_git_cache_hardening.py Adapts cache diagnostics tests.
tests/​unit/​cache/​test_checkout_verify.py Adds real-repository verification and tampering tests.
tests/​integration/​test_shared_clone_cache.py Adapts shared-clone downloader tests.
tests/​integration/​test_git_cache_hermetic.py Adapts fake-checkout cache tests.
tests/​integration/​test_cache_coverage.py Adapts cache hit, environment, and integrity tests.
tests/​integration/​test_architecture_owner_rule_mutations.py Adds a mutation case for bypassed verification.
src/​apm_cli/​deps/​github_downloader.py Verifies direct clones before consuming package content.
src/​apm_cli/​cache/​git_cache.py Adds verification, rebuild, and refusal handling.
src/​apm_cli/​cache/​checkout_verify.py Implements the shared checkout verifier and process-local memo.
scripts/​architecture_linter/​groups/​transport_platform.py Enables the checkout verification guard.
scripts/​architecture_linter/​checks/​transport_checkout_verify.py Checks required verification calls and safeguards.
changelog.d/​4891.security.md Documents the checkout verification change.
.apm/​architecture/​owners/​transport-auth-platform.json Declares the canonical verification owner and guard.

Review effort: Balanced

Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/git_cache.py Resolved
Comment thread src/apm_cli/deps/github_downloader.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved

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.

Comment thread src/apm_cli/deps/github_downloader.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved

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 findings include a failing architecture rule, a potential verifier hang, partial-manifest reuse that bypasses whole-repository verification, and incorrect handling of binary CRLF conversion and nested attribute macros.

1 open issue
4 previously missed issues

In code that hasn't changed since last review

High severity Avoid deadlock when rejecting large wrong-kind objects

src/​apm_cli/​cache/​checkout_verify.py:116

If a tree object is replaced with a blob larger than the pipe buffer, read() rejects its type without consuming the payload. This cleanup then waits indefinitely while cat-file blocks writing to stdout, preventing cache rebuilding or refusal. Terminate the batch reader and drain its pipes with bounded waits, and add a regression for a large wrong-kind object.

High severity Reject CRLF conversion for binary content under text=auto

src/​apm_cli/​cache/​checkout_verify.py:336

For text=auto eol=crlf, Git leaves binary content unchanged, but this branch accepts CRLF expansion even for NUL-containing blobs. Changing committed b'\x00\n' to b'\x00\r\n' therefore passes verification and becomes the trusted manifest although Git would not produce those bytes. Apply Git's automatic-conversion eligibility rules before allowing CRLF conversion, and cover modified binary content in the verifier tests.

High severity Require cached verification scope to cover the consumer's request

src/​apm_cli/​cache/​checkout_verify.py:542

This lookup reuses a manifest without checking its verification scope. After verify_checkout(repo, sha, paths=["pkg"]) accepts a checkout missing a committed root file, a whole-repository require_verified_copy(dest, repo, sha) can reuse that partial manifest and accept the same omission. Record each manifest's scope and require it to cover the consumer's requested scope, re-verifying otherwise.

Medium severity Expand nested attribute macros with cycle protection

src/​apm_cli/​cache/​checkout_verify.py:308

Macro expansion stops after one level, so valid nested macros such as [attr]dos text eol=crlf, [attr]docs dos, and pkg/*.md docs record only dos=True. Genuine CRLF checkouts are then rejected because _accepted() permits only the LF blob, and fetching again cannot repair them. Expand nested macros with cycle protection while preserving attribute precedence, and cover this case against a real Git checkout.

8 resolved since last review

Review effort: Balanced

GitCache.get_checkout and the downloader's direct clones now verify each
package checkout against its commit before its bytes are hashed or
deployed: the commit and every reachable tree are re-hashed, every
working-tree file must hold its blob's bytes (through Git's own checkout
filters), links must hold their resolved targets and nothing untracked may
sit beside them. A cached checkout that fails is evicted and rebuilt once,
then refused; read-only lookups treat it as a miss. Verdicts are memoized
in-process only.

Owner: cache/checkout_verify.py, guarded by transport-platform-checkout-verified.

Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Verification never runs a Git filter or driver: line endings come from the
commit's own verified .gitattributes, and paths with a filter, ident or
working-tree-encoding attribute must hold their exact blob. File modes are
checked, a sparse cone must hold exactly what the cone checks out, and the
object reader runs inert and offline through the cached-repo owner. A
checkout that fails is rebuilt once from a fresh fetch (its bare is
discarded too), with a warning, then refused. Consumers check the bytes
they copy or read against what verification accepted.

Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
The checkout gate lives in _get_checkout behind the verifying wrapper; the
rebuild notice is a [!] warning; mocked-checkout marketplace and download
routing tests opt out of byte checks they cannot exercise; the unhealable
refusal oracle accepts the error line that names the package.

Co-authored-by: Copilot App <[email protected]>
Cached and cloned package trees are copied entry by entry without following
links (robust_copy_entry), so a link swapped in after verification is copied
as a link, never read through, and the copy check then refuses it.

The checkout guard pins the sanitized reader environment. Two mocked-copy
download tests stub the copy check, a Windows test helper clears Git's
read-only bit before replacing an object, and two cells assert observable
outcomes.

Co-authored-by: Copilot App <[email protected]>
The copy check and the verified-file reader lstat each entry first, refuse
anything that is not a regular file, and open with O_NOFOLLOW and
O_NONBLOCK, so a link, pipe or device in a copy is never read through.

Co-authored-by: Copilot App <[email protected]>
apm-spec-waiver: cache-integrity verification and test fixtures only; no OpenAPM manifest, lockfile or resolver semantics change

Co-authored-by: Copilot App <[email protected]>
The opened file must be the one lstat checked (same device and inode on
POSIX), and its mode is taken from the open handle.

Co-authored-by: Copilot App <[email protected]>
…cell now holds

The object reader's environment names the checkout as its repository, so
Git never searches above it. The frozen-install cell that named the failed
fetch is a plain assertion now that main reports the failed download first.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel
Daniel Meppiel (danielmeppiel) force-pushed the danielmeppiel-perf-checkout-verify branch from 4cec580 to 21606bf Compare November 23, 2026 09:29

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

Critical cache-verification flaws allow unverified Git config or hooks into installed packages and can hang installation when cached objects have the wrong type.

3 open issues
1 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Comment thread src/apm_cli/cache/checkout_verify.py Resolved
…macros

- The cat-file reader now kills and reaps its process on close, so an
  unread object larger than the pipe can no longer block cleanup.
- A verified copy is refused when it holds a .git entry anywhere.
- Attribute macros that name other macros expand transitively, with a
  depth cap.

Co-authored-by: Copilot App <[email protected]>
A copy is also refused when an entry differs from .git only by case,
trailing dots or spaces, or is a short-name alias such as GIT~1.

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

A critical flaw still permits exponential attribute macro expansion, allowing a tiny committed attributes file to stall installation despite the depth limit.

1 open issue
3 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/cache/checkout_verify.py Resolved
Nested macros are expanded once each and memoized, so widely shared
macros cost linear work. A macro that names itself, directly or through
others, leaves the checkout unverified. The .git alias cell skips the
trailing-space name on Windows, which cannot create it.

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

Macro expansion is bounded only by recursion depth, allowing cyclic fan-out in a tiny repository to cause exponential work and effectively hang installation during checkout verification.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Attributes are now filled from the highest-priority assignment down,
each name set once, and a macro expands only when its own final state
is set. A later -macro line therefore cancels the macro, every macro
expands at most once per path, and self-naming macros resolve as in Git.

Fixes #4980

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 subtle Git-attribute handling errors and scope-insensitive manifest reuse can allow altered or unverified content to pass validation.

No open issues 🎉

Review effort: Balanced

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 27ede4c into main Nov 23, 2026
97 of 98 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-perf-checkout-verify branch November 23, 2026 11:21
Jason 'Jay' Jack (jasonjack-jay) pushed a commit to jasonjack-jay/Agent-Package-Manager that referenced this pull request Nov 24, 2026
…commit

The disk-or-cache rows of git-content_hash and approval-pins now expect the
heal microsoft#4891 introduced: install, --frozen and update exit 0, print the
rebuild warning and leave every copy with the locked bytes; audit --ci reads
the locked source and changes nothing. Deployed files stay unchanged.

Refs microsoft#5159

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.

[BUG] Checkout verification keeps a macro's attributes after a higher-priority line unsets the macro

2 participants