Skip to content

worktree: add git worktree support for VFSForGit - #1

Closed
tyrielv wants to merge 11 commits into
tyrielv/faster-mountfrom
tyrielv/gvfs-worktree
Closed

tyrielv wants to merge 11 commits into
tyrielv/faster-mountfrom
tyrielv/gvfs-worktree

Conversation

@tyrielv

@tyrielv tyrielv commented Mar 5, 2026

Copy link
Copy Markdown
Owner

Enable 'git worktree add/remove' on VFSForGit enlistments by running a separate GVFS mount per worktree. Each worktree gets its own ProjFS virtualization instance, named pipe, index projection, and metadata.

Git changes (microsoft/git):

  • Add GVFS_SUPPORTS_WORKTREES (1<<8) to core.gvfs bitmask
  • Conditionally allow worktree when the bit is set
  • Force --no-checkout when VFS is active

VFSForGit changes:

  • Detect worktrees via .git file (not directory) in MountVerb, UnmountVerb, GVFSEnlistment.CreateFromDirectory
  • Override DotGitRoot to SharedGitDir for worktree enlistments
  • Worktree-aware named pipe resolution in native and managed hooks
  • Auto-mount in post-command hook: checkout -f to create index, then gvfs mount for ProjFS projection
  • Auto-unmount in pre-command hook before worktree remove
  • Worktree-specific .gvfs metadata with SaveCloneMetadata
  • Absolute paths for core.hookspath and core.virtualfilesystem
  • Skip hook installation for worktree mounts (shared via hookspath)
  • SupportsWorktrees flag in InProcessMount's GitCoreGVFSFlags
  • Fix all .git directory assumptions for worktree paths (alternates, LocalObjectsRoot, index path, hooks path)

tyrielv and others added 5 commits January 30, 2026 10:29
Replace the heavyweight SafeDirectoryOwnershipTests functional test
(which required elevation, P/Invoke for SeRestorePrivilege, directory
ownership changes, and global git config manipulation) with two layers
of lightweight unit tests:

Layer 1: NormalizePathForSafeDirectoryComparison - pure string tests
covering backslash/forward-slash conversion, case normalization,
trailing slash trimming, and null/empty safety.

Layer 2: Constructor control-flow tests using a mock subclass that
overrides the native calls (InitNative, TryOpenRepo, GetLastNativeError,
GetSafeDirectoryConfigEntries) to verify the safe.directory case-
sensitivity workaround logic without touching libgit2 or real config.

To support testability, extract virtual methods from LibGit2Repo for
native interactions and make CheckSafeDirectoryConfigForCaseSensitivity-
Issue protected. The NormalizePath helper is renamed to
NormalizePathForSafeDirectoryComparison and scoped as internal.

Co-authored-by: Copilot <[email protected]>
The previous check required exactly version 0.2.173.2, which is the
hard-coded default in Version.props. Relax this to treat any version
with major version 0 as a development build. This is useful when
working with Copilot to build and install local versions, as it allows
Copilot to detect whether the currently installed version matches its
latest build by comparing version strings, without needing to use the
one specific hard-coded version number.

Co-authored-by: Copilot <[email protected]>
Change the default 'gvfs dehydrate' behavior from full-enlistment
dehydration (unmount, backup entire src, recreate virtualization root)
to per-folder dehydration of all root-level folders. This is faster
and does not require a full unmount/remount cycle.

The previous full-enlistment behavior is preserved via the new --full
flag for cases where a complete reset is needed.

Changes:
- Add --full option for legacy full-enlistment dehydrate
- When neither --folders nor --full is specified, enumerate all
  root-level directories from HEAD via 'git ls-tree' and dehydrate
  them individually
- Using the git tree (not filesystem) ensures deleted folders are
  restored by the dehydrate
- Reject combining --full with --folders
- Update confirmation messages to reflect new defaults
- Update functional tests: existing full-dehydrate tests now pass
  --full, add new FullDehydrate* tests, default-path test exercises
  the new all-root-folders behavior

Performance (2.8M file repo, 1000 dirs hydrated, ~5,600 files):
  Root-folders (default): 13.0s
  Full (--full):          51.1s

Co-authored-by: Copilot <[email protected]>
Relax IsDevelopmentVersion to accept any major version 0
@tyrielv
tyrielv force-pushed the tyrielv/gvfs-worktree branch 3 times, most recently from b5aeadf to f142420 Compare March 7, 2026 00:01
tyrielv added 3 commits March 9, 2026 09:23
…card-folders

dehydrate: default to per-folder dehydration, add --full flag
Improve mount performance by moving validation to mount process and parallelizing I/O
…caseinsensitive

Workaround libgit2 safe.directory case mismatch bug
@tyrielv
tyrielv force-pushed the tyrielv/gvfs-worktree branch 4 times, most recently from d3fa24c to a3ef0d7 Compare March 9, 2026 23:23
Tyrie Vella and others added 2 commits March 11, 2026 13:42
Enable 'git worktree add/remove' on VFSForGit enlistments by running
a separate GVFS mount per worktree. Each worktree gets its own ProjFS
virtualization instance, named pipe, index projection, and metadata.

Git changes (microsoft/git):
- Add GVFS_SUPPORTS_WORKTREES (1<<8) to core.gvfs bitmask
- Conditionally allow worktree when the bit is set
- Force --no-checkout when VFS is active

VFSForGit changes:
- Detect worktrees via .git file (not directory) in MountVerb,
  UnmountVerb, GVFSEnlistment.CreateFromDirectory
- Override DotGitRoot to SharedGitDir for worktree enlistments
- Worktree-aware named pipe resolution in native and managed hooks
- Auto-mount in post-command hook: checkout -f to create index,
  then gvfs mount for ProjFS projection
- Auto-unmount in pre-command hook before worktree remove
- Worktree-specific .gvfs metadata with SaveCloneMetadata
- Absolute paths for core.hookspath and core.virtualfilesystem
- Skip hook installation for worktree mounts (shared via hookspath)
- SupportsWorktrees flag in InProcessMount's GitCoreGVFSFlags
- Fix all .git directory assumptions for worktree paths (alternates,
  LocalObjectsRoot, index path, hooks path)

Co-authored-by: Copilot <[email protected]>
Worktree mounts were registering and unregistering with the primary
enlistment root path. This caused 'gvfs unmount <worktree>' to
unregister the primary enlistment from the service, making it
disappear from 'gvfs service --list-mounted' even though the
primary mount was still running.

Fix by using the worktree's working directory path for service
registration instead of the primary enlistment root. Each worktree
now has its own entry in the service registry and can be listed,
mounted, and unmounted independently.

Co-authored-by: Copilot <[email protected]>
@tyrielv
tyrielv force-pushed the tyrielv/gvfs-worktree branch from 85da45b to 42a9161 Compare March 11, 2026 20:50
If git worktree remove fails (e.g., locked file) but the worktree
directory and .git file both still exist, the post-command hook
attempts to remount ProjFS so the worktree remains usable.

If the remove partially succeeded (directory or .git file gone),
no recovery is attempted — the user sees git's error messages.

Also fix worktrees directory path in CleanStaleWorktreeMetadata
to include the src/ component between enlistment root and .git/.

Co-authored-by: Copilot <[email protected]>
@tyrielv tyrielv closed this Apr 16, 2026
tyrielv added a commit that referenced this pull request Jun 4, 2026
The previous Authenticode check had two security bugs that combined
to make it ineffective:

1. X509Certificate.CreateFromSignedFile only extracts the signer
   certificate from a PE file — it does NOT verify that the signed
   digest matches the file's contents. X509Chain.Build then validates
   the certificate chain but not the file. An attacker could take any
   Microsoft-signed binary, modify arbitrary bytes in the PE, keep the
   signature blob attached, and this verifier would return success.

2. The signer check was a substring match on the certificate Subject:
   subject.Contains("CN=Microsoft Corporation"). This passes for
   surprising DNs such as CN="Microsoft Corporation Ltd" or DNs where
   the attacker's CN appears alongside "Microsoft Corporation" in
   another field (e.g. O="Microsoft Corporation, CN=Attacker").

Fix #1: Add a WinVerifyTrust P/Invoke and call it with
WINTRUST_ACTION_GENERIC_VERIFY_V2 before inspecting the cert. This is
the same code path Windows uses for SmartScreen / SRP / WDAC and is
the only supported way to verify Authenticode on Windows. Map the
common HRESULTs (TRUST_E_NOSIGNATURE, TRUST_E_BAD_DIGEST, etc.) to
specific error messages so users get actionable feedback. Fail closed
on non-Windows.

Fix #2: Replace the Subject.Contains match with an exact-string
comparison against certificate.GetNameInfo(X509NameType.SimpleName,
forIssuer: false). GetNameInfo parses the DN and returns just the CN
value, eliminating substring-collision attacks. Use the ordinal
comparer for the equality check.

Verified end-to-end on Windows:
  - Tampering one byte of a signed installer → rejected with
    "Installer Authenticode hash does not match — file has been
    tampered with" (was previously accepted)
  - Unsigned dev installer → rejected with "Installer is not signed"
  - notepad.exe (Microsoft-signed, ProductName mismatch) → still
    rejected by the ProductName check first
  - Real signed SetupGVFS.2.0.26147.6.exe → accepted, runs upgrade

Assisted-by: Claude Opus 4.7
Signed-off-by: Tyrie Vella <[email protected]>
tyrielv added a commit that referenced this pull request Aug 5, 2026
When a user process reads a virtualized placeholder whose stored
content-id is corrupt - specifically 40 NUL bytes instead of a hex SHA -
GVFS builds a loose-object path from it and Path.Combine throws
System.ArgumentException ("Illegal characters in path").

ArgumentException is not in RetryWrapper.IsHandlableException, so it
bypasses both the retry logic and the download fallback in
GVFSGitObjects.TryCopyBlobContentStream and propagates to the
virtualizer's outer catch, which returns FileNotAvailable to ProjFS. The
placeholder can never hydrate, so the failing read repeats forever - a
retry storm. This is the #1 blob-hydration failure cause on the LKG field
build 1.0.26014.1 (38 machines; ~61 machines / ~6.2K events across 30d;
one machine emitted ~2.49M error events).

This is a corrupt content-id, NOT GVFSConstants.AllZeroSha: AllZeroSha is
40 ASCII '0' characters, which yields directory "00" and does not throw.

Reject a malformed SHA before it is turned into a path:

- GitRepo.GetLooseBlobState returns LooseBlobState.Invalid (a clean,
  non-retryable miss) for a SHA that is not 40 hex characters, so
  Path.Combine can never throw here again.
- GitRepo.LooseObjectExists guards the same Path.Combine.
- GVFSGitObjects.TryCopyBlobContentStream short-circuits a malformed SHA
  before the retry loop, so a bogus SHA never triggers a doomed 404
  download or a retry storm.
- SHA1Util.IsValidShaFormat is now null-safe; SHA1Util.ToLoggableShaString
  renders the bad value with non-hex characters escaped so telemetry stays
  greppable and free of control characters.

All three guard sites emit the same greppable Warning event
(*_MalformedBlobSha) at Warning level with no unhandled exception. Per an
existing decision this case stays telemetry category "Unexpected"; no new
BlobHydrationFailureCategory is added.

Stacked on microsoft#2071 (tyrielv/split-hydration-enum-telemetry): this branch is
rebased onto it, so microsoft#2071's out BlobHydrationFailureCategory parameter is
honored - the malformed-SHA short-circuit sets failureCategory =
Unexpected, so the virtualizer's terminal telemetry tags the case exactly
as before (it no longer reaches the outer catch because it no longer
throws). This PR must NOT merge before microsoft#2071; after microsoft#2071 lands, rebase
onto master.

Unit tests assert that a 40-NUL-byte SHA, a 40-char SHA with an embedded
path-illegal character, and other malformed SHAs return false from both
GitRepo.TryCopyBlobContentStream and GVFSGitObjects.TryCopyBlobContentStream
with no ArgumentException (Assert.DoesNotThrow), that no download/retry is
attempted, and that the out category is Unexpected.

Assisted-by: Claude Opus 4.8
Signed-off-by: Tyrie Vella <[email protected]>
tyrielv added a commit that referenced this pull request Aug 5, 2026
When a user process reads a virtualized placeholder whose stored
content-id is corrupt - specifically 40 NUL bytes instead of a hex SHA -
GVFS builds a loose-object path from it and Path.Combine throws
System.ArgumentException ("Illegal characters in path").

ArgumentException is not in RetryWrapper.IsHandlableException, so it
bypasses both the retry logic and the download fallback in
GVFSGitObjects.TryCopyBlobContentStream and propagates to the
virtualizer's outer catch, which returns FileNotAvailable to ProjFS. The
placeholder can never hydrate, so the failing read repeats forever - a
retry storm. This is the #1 blob-hydration failure cause on the LKG field
build 1.0.26014.1 (38 machines; ~61 machines / ~6.2K events across 30d;
one machine emitted ~2.49M error events).

This is a corrupt content-id, NOT GVFSConstants.AllZeroSha: AllZeroSha is
40 ASCII '0' characters, which yields directory "00" and does not throw.

Reject a malformed SHA before it is turned into a path:

- GitRepo.GetLooseBlobState returns LooseBlobState.Invalid (a clean,
  non-retryable miss) for a SHA that is not 40 hex characters, so
  Path.Combine can never throw here again.
- GitRepo.LooseObjectExists guards the same Path.Combine.
- GVFSGitObjects.TryCopyBlobContentStream short-circuits a malformed SHA
  before the retry loop, so a bogus SHA never triggers a doomed 404
  download or a retry storm.
- SHA1Util.IsValidShaFormat is now null-safe; SHA1Util.ToLoggableShaString
  renders the bad value with non-hex characters escaped so telemetry stays
  greppable and free of control characters.
- WindowsFileSystemVirtualizer routes the request's logged sha through
  ToLoggableShaString, so a malformed content-id can no longer enter
  telemetry with raw NUL/control bytes at the terminal hydration-failure
  error either (a no-op for a valid hex SHA).

All three guard sites emit the same greppable Warning event
(*_MalformedBlobSha) at Warning level with no unhandled exception. Per an
existing decision this case stays telemetry category "Unexpected"; no new
BlobHydrationFailureCategory is added.

Stacked on microsoft#2071 (tyrielv/split-hydration-enum-telemetry): this branch is
rebased onto it, so microsoft#2071's out BlobHydrationFailureCategory parameter is
honored - the malformed-SHA short-circuit sets failureCategory =
Unexpected, so the virtualizer's terminal telemetry tags the case exactly
as before (it no longer reaches the outer catch because it no longer
throws). This PR must NOT merge before microsoft#2071; after microsoft#2071 lands, rebase
onto master.

Unit tests assert that a 40-NUL-byte SHA, a 40-char SHA with an embedded
path-illegal character, and other malformed SHAs return false from both
GitRepo.TryCopyBlobContentStream and GVFSGitObjects.TryCopyBlobContentStream
with no ArgumentException (Assert.DoesNotThrow), that no download/retry is
attempted, and that the out category is Unexpected.

Assisted-by: Claude Opus 4.8
Signed-off-by: Tyrie Vella <[email protected]>
tyrielv added a commit that referenced this pull request Aug 7, 2026
When a user process reads a virtualized placeholder whose stored
content-id is corrupt - specifically 40 NUL bytes instead of a hex SHA -
GVFS builds a loose-object path from it and Path.Combine throws
System.ArgumentException ("Illegal characters in path").

ArgumentException is not in RetryWrapper.IsHandlableException, so it
bypasses both the retry logic and the download fallback in
GVFSGitObjects.TryCopyBlobContentStream and propagates to the
virtualizer's outer catch, which returns FileNotAvailable to ProjFS. The
placeholder can never hydrate, so the failing read repeats forever - a
retry storm. This is the #1 blob-hydration failure cause on the LKG field
build 1.0.26014.1 (38 machines; ~61 machines / ~6.2K events across 30d;
one machine emitted ~2.49M error events).

This is a corrupt content-id, NOT GVFSConstants.AllZeroSha: AllZeroSha is
40 ASCII '0' characters, which yields directory "00" and does not throw.

Reject a malformed SHA before it is turned into a path:

- GitRepo.GetLooseBlobState returns LooseBlobState.Invalid (a clean,
  non-retryable miss) for a SHA that is not 40 hex characters, so
  Path.Combine can never throw here again.
- GitRepo.LooseObjectExists guards the same Path.Combine.
- GVFSGitObjects.TryCopyBlobContentStream short-circuits a malformed SHA
  before the retry loop, so a bogus SHA never triggers a doomed 404
  download or a retry storm.
- SHA1Util.IsValidShaFormat is now null-safe; SHA1Util.ToLoggableShaString
  renders the bad value with non-hex characters escaped so telemetry stays
  greppable and free of control characters.
- WindowsFileSystemVirtualizer routes the request's logged sha through
  ToLoggableShaString, so a malformed content-id can no longer enter
  telemetry with raw NUL/control bytes at the terminal hydration-failure
  error either (a no-op for a valid hex SHA).

All three guard sites emit the same greppable Warning event
(*_MalformedBlobSha) at Warning level with no unhandled exception. Per an
existing decision this case stays telemetry category "Unexpected"; no new
BlobHydrationFailureCategory is added.

Stacked on microsoft#2071 (tyrielv/split-hydration-enum-telemetry): this branch is
rebased onto it, so microsoft#2071's out BlobHydrationFailureCategory parameter is
honored - the malformed-SHA short-circuit sets failureCategory =
Unexpected, so the virtualizer's terminal telemetry tags the case exactly
as before (it no longer reaches the outer catch because it no longer
throws). This PR must NOT merge before microsoft#2071; after microsoft#2071 lands, rebase
onto master.

Unit tests assert that a 40-NUL-byte SHA, a 40-char SHA with an embedded
path-illegal character, and other malformed SHAs return false from both
GitRepo.TryCopyBlobContentStream and GVFSGitObjects.TryCopyBlobContentStream
with no ArgumentException (Assert.DoesNotThrow), that no download/retry is
attempted, and that the out category is Unexpected.

Assisted-by: Claude Opus 4.8
Signed-off-by: Tyrie Vella <[email protected]>
tyrielv added a commit that referenced this pull request Aug 7, 2026
When a user process reads a virtualized placeholder whose stored
content-id is corrupt - specifically 40 NUL bytes instead of a hex SHA -
GVFS builds a loose-object path from it and Path.Combine throws
System.ArgumentException ("Illegal characters in path").

ArgumentException is not in RetryWrapper.IsHandlableException, so it
bypasses both the retry logic and the download fallback in
GVFSGitObjects.TryCopyBlobContentStream and propagates to the
virtualizer's outer catch, which returns FileNotAvailable to ProjFS. The
placeholder can never hydrate, so the failing read repeats forever - a
retry storm. This is the #1 blob-hydration failure cause on the LKG field
build 1.0.26014.1 (38 machines; ~61 machines / ~6.2K events across 30d;
one machine emitted ~2.49M error events).

This is a corrupt content-id, NOT GVFSConstants.AllZeroSha: AllZeroSha is
40 ASCII '0' characters, which yields directory "00" and does not throw.

Reject a malformed SHA before it is turned into a path:

- GitRepo.GetLooseBlobState returns LooseBlobState.Invalid (a clean,
  non-retryable miss) for a SHA that is not 40 hex characters, so
  Path.Combine can never throw here again.
- GitRepo.LooseObjectExists guards the same Path.Combine.
- GVFSGitObjects.TryCopyBlobContentStream short-circuits a malformed SHA
  before the retry loop, so a bogus SHA never triggers a doomed 404
  download or a retry storm.
- SHA1Util.IsValidShaFormat is now null-safe; SHA1Util.ToLoggableShaString
  renders the bad value with non-hex characters escaped so telemetry stays
  greppable and free of control characters.
- WindowsFileSystemVirtualizer routes the request's logged sha through
  ToLoggableShaString, so a malformed content-id can no longer enter
  telemetry with raw NUL/control bytes at the terminal hydration-failure
  error either (a no-op for a valid hex SHA).

All three guard sites emit the same greppable Warning event
(*_MalformedBlobSha) at Warning level with no unhandled exception. Per an
existing decision this case stays telemetry category "Unexpected"; no new
BlobHydrationFailureCategory is added.

Stacked on microsoft#2071 (tyrielv/split-hydration-enum-telemetry): this branch is
rebased onto it, so microsoft#2071's out BlobHydrationFailureCategory parameter is
honored - the malformed-SHA short-circuit sets failureCategory =
Unexpected, so the virtualizer's terminal telemetry tags the case exactly
as before (it no longer reaches the outer catch because it no longer
throws). This PR must NOT merge before microsoft#2071; after microsoft#2071 lands, rebase
onto master.

Unit tests assert that a 40-NUL-byte SHA, a 40-char SHA with an embedded
path-illegal character, and other malformed SHAs return false from both
GitRepo.TryCopyBlobContentStream and GVFSGitObjects.TryCopyBlobContentStream
with no ArgumentException (Assert.DoesNotThrow), that no download/retry is
attempted, and that the out category is Unexpected.

Assisted-by: Claude Opus 4.8
Signed-off-by: Tyrie Vella <[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.

1 participant