From 0bac37b6844e07cc92e6ade9a48f9470cb367353 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Fri, 13 Nov 2026 15:53:02 -0800 Subject: [PATCH 1/6] Allow PrjFlt on Dev Drives through GVFS.Service A Dev Drive can reject PrjFlt with 0x800701DE when no applicable allowance includes it. An unelevated mount cannot update that policy. Route unelevated ReFS attachment checks through GVFS.Service. After the volume rejects attachment, append PrjFlt to that volume's list. Keep inherited allowances separate and leave machine-wide lists unchanged. Recheck before replacement and verify the saved result. External edits to the same volume still require coordination. Gate updates behind gvfs.auto-allow-devdrive-filter, default on. Read fresh booleans through Git, including system includes and conditional client includes. Either scope can veto a write. Unreadable or invalid configuration prevents automatic updates. Separate the policy lock from driver-health work. Bound fsutil waits with a shared process budget and observe child exit during cleanup. Disable further automatic updates if child cleanup cannot complete. Record policy changes independently of the attachment outcome. If a busy volume retains its old policy, report that it needs a remount or restart. Never force-dismount the volume. Add unit tests for veto precedence, configuration errors, nullable wire compatibility, per-volume preservation, busy-write readback, recovery outcomes, and typed attachment decisions. Assisted-by: GitHub Copilot (Auto) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Tyrie Vella --- GVFS/GVFS.Common/DevDriveFilterConfig.cs | 36 ++ GVFS/GVFS.Common/GVFSConstants.cs | 8 + GVFS/GVFS.Common/Git/GitProcess.cs | 16 + .../NamedPipes/NamedPipeMessages.cs | 12 + .../DevDriveFilterPolicy.cs | 343 ++++++++++++++++++ GVFS/GVFS.Platform.Windows/ProjFSFilter.cs | 124 ++++++- .../Handlers/DevDriveFilterRecovery.cs | 75 ++++ .../Handlers/EnableAndAttachProjFSHandler.cs | 58 ++- GVFS/GVFS.Service/InternalsVisibleTo.cs | 3 + .../Common/DevDriveFilterConfigTests.cs | 110 ++++++ .../Service/DevDriveFilterRecoveryTests.cs | 95 +++++ .../Platform/DevDriveFilterPolicyTests.cs | 199 ++++++++++ .../Windows/Platform/ProjFSFilterTests.cs | 57 +++ GVFS/GVFS/CommandLine/GVFSVerb.cs | 19 +- GVFS/GVFS/CommandLine/MountVerb.cs | 2 +- 15 files changed, 1139 insertions(+), 18 deletions(-) create mode 100644 GVFS/GVFS.Common/DevDriveFilterConfig.cs create mode 100644 GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs create mode 100644 GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs create mode 100644 GVFS/GVFS.Service/InternalsVisibleTo.cs create mode 100644 GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs create mode 100644 GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs create mode 100644 GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs diff --git a/GVFS/GVFS.Common/DevDriveFilterConfig.cs b/GVFS/GVFS.Common/DevDriveFilterConfig.cs new file mode 100644 index 0000000000..30d6f55734 --- /dev/null +++ b/GVFS/GVFS.Common/DevDriveFilterConfig.cs @@ -0,0 +1,36 @@ +using GVFS.Common.Git; +using GVFS.Common.Tracing; + +namespace GVFS.Common +{ + public static class DevDriveFilterConfig + { + public static bool IsEnabled( + LibGit2Repo.TryReadConfigBoolWithGit readConfig, + bool? clientValue, + string source, + ITracer tracer, + out string disabledReason) + { + disabledReason = null; + bool? value = null; + string error = "Git is unavailable."; + if (readConfig == null + || !readConfig(GVFSConstants.GitConfig.AutoAllowDevDriveFilter, out value, out error)) + { + disabledReason = $"Automatic filter allowance changes are disabled because the {source} configuration read failed. {error}"; + tracer.RelatedWarning(disabledReason); + return false; + } + + if (!(value ?? GVFSConstants.GitConfig.AutoAllowDevDriveFilterDefault) || clientValue == false) + { + string disabledSource = value == false ? source : "enlistment"; + disabledReason = $"Automatic filter allowance changes are disabled by {GVFSConstants.GitConfig.AutoAllowDevDriveFilter} in the {disabledSource} configuration."; + return false; + } + + return true; + } + } +} diff --git a/GVFS/GVFS.Common/GVFSConstants.cs b/GVFS/GVFS.Common/GVFSConstants.cs index dba978467e..7939f17917 100644 --- a/GVFS/GVFS.Common/GVFSConstants.cs +++ b/GVFS/GVFS.Common/GVFSConstants.cs @@ -89,6 +89,14 @@ public static class GitConfig public const string PrefetchOffload = GVFSPrefix + "prefetch-offload"; public const bool PrefetchOffloadDefault = false; + + /* Permits GVFS.Service to allow PrjFlt on the enlistment's Dev Drive after attachment + * is rejected. Default on to repair that failure without a separate elevated command. + * The service reads its Git installation's system config (including includes) for each + * request. Either that value or the client's resolved value can veto a write. + * Disabling the flag does not remove a persisted allowance. */ + public const string AutoAllowDevDriveFilter = GVFSPrefix + "auto-allow-devdrive-filter"; + public const bool AutoAllowDevDriveFilterDefault = true; } public static class LocalGVFSConfig diff --git a/GVFS/GVFS.Common/Git/GitProcess.cs b/GVFS/GVFS.Common/Git/GitProcess.cs index 22a9a4c62b..a89f176315 100644 --- a/GVFS/GVFS.Common/Git/GitProcess.cs +++ b/GVFS/GVFS.Common/Git/GitProcess.cs @@ -201,6 +201,22 @@ public static ConfigResult GetFromSystemConfig(string gitBinPath, string setting settingName); } + public static bool TryGetBoolFromSystemConfig(string gitBinPath, string settingName, out bool? value, out string error) + { + GitProcess git = new GitProcess(gitBinPath, workingDirectoryRoot: null); + return TryGetBoolFromSystemConfig( + settingName, + arguments => git.InvokeConfigRead(settingName, () => git.InvokeGitOutsideEnlistment(arguments)), + out value, + out error); + } + + internal static bool TryGetBoolFromSystemConfig(string settingName, Func readConfig, out bool? value, out string error) + { + Result result = readConfig("config --system --includes --type=bool " + settingName); + return LibGit2Repo.TryParseConfigBoolOutput(settingName, result.ExitCode, result.Output, result.Errors, out value, out error); + } + public static ConfigResult GetFromFileConfig(string gitBinPath, string configFile, string settingName) { GitProcess git = new GitProcess(gitBinPath, workingDirectoryRoot: null); diff --git a/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs index 5d1e4794a4..79d0610b7a 100644 --- a/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs +++ b/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs @@ -482,6 +482,18 @@ public class EnableAndAttachProjFSRequest public string EnlistmentRoot { get; set; } + /// + /// The value of gvfs.auto-allow-devdrive-filter as resolved by the client against the + /// enlistment (system, global, and local git config). Null when the client did not + /// resolve a value, including requests from a client that predates this field. + /// + /// + /// The service also reads the system config of its selected Git installation. + /// A false system value vetoes the write regardless of this client value. + /// See GVFSConstants.GitConfig.AutoAllowDevDriveFilter for the configuration contract. + /// + public bool? AutoAllowDevDriveFilter { get; set; } + public static EnableAndAttachProjFSRequest FromMessage(Message message) { return GVFSJsonOptions.Deserialize(message.Body); diff --git a/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs b/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs new file mode 100644 index 0000000000..416ae1e923 --- /dev/null +++ b/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs @@ -0,0 +1,343 @@ +using GVFS.Common; +using GVFS.Common.Tracing; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace GVFS.Platform.Windows +{ + public static class DevDriveFilterPolicy + { + private const string VolumeHeader = "Filters allowed on this developer volume:"; + private const string MachineHeader = "Filters allowed on any developer volume:"; + private const string GroupPolicyHeader = "Filters allowed on any developer volume, by group policy:"; + private const string AttachedHeader = "Filters currently attached to this developer volume:"; + private static readonly Regex FilterNamePattern = new Regex(@"\A[A-Za-z0-9._-]+\z", RegexOptions.Compiled); + private static readonly TimeSpan UpdateTimeout = TimeSpan.FromSeconds(30); + private static readonly Lock PolicyLock = new Lock(); + private static volatile bool processCleanupFailed; + + public enum AllowFilterResult + { + AlreadyAllowed, + Added, + RemountRequired, + PolicyUnreadable, + Failed, + } + + public static AllowFilterResult TryAllowFilter(string volumeRoot, ITracer tracer, out string error) + { + if (!PolicyLock.TryEnter(UpdateTimeout)) + { + error = "Another Dev Drive policy update is in progress. Retry the mount."; + tracer.RelatedWarning(error); + return AllowFilterResult.Failed; + } + + try + { + if (processCleanupFailed) + { + error = "Automatic Dev Drive updates are disabled because a previous policy process did not stop. Restart GVFS.Service after that process exits."; + tracer.RelatedWarning(error); + return AllowFilterResult.Failed; + } + + Stopwatch elapsed = Stopwatch.StartNew(); + return TryAllowFilter( + volumeRoot, + arguments => RunFsUtil(arguments, UpdateTimeout - elapsed.Elapsed, tracer), + tracer, + out error); + } + catch (Exception e) when (e is Win32Exception || e is IOException || e is UnauthorizedAccessException || e is AggregateException) + { + error = $"Failed to update the Dev Drive filter allowance. The saved policy can already include the change. {e.Message}"; + tracer.RelatedWarning($"{nameof(TryAllowFilter)}: {e}"); + return AllowFilterResult.Failed; + } + finally + { + PolicyLock.Exit(); + } + } + + internal static AllowFilterResult TryAllowFilter( + string volumeRoot, + Func runFsUtil, + ITracer tracer, + out string error) + { + if (!TryQueryPolicy(volumeRoot, runFsUtil, tracer, out Allowances before, out error)) + { + return AllowFilterResult.PolicyUnreadable; + } + + if (before.AllowsProjFS) + { + return AllowFilterResult.AlreadyAllowed; + } + + // Recheck before replacement. External administrators do not share PolicyLock, + // so this detects an observed change but cannot provide compare-and-swap. + if (!TryQueryPolicy(volumeRoot, runFsUtil, tracer, out Allowances current, out error)) + { + return AllowFilterResult.PolicyUnreadable; + } + + if (current.AllowsProjFS) + { + return AllowFilterResult.AlreadyAllowed; + } + + if (!new HashSet(before.Volume, StringComparer.OrdinalIgnoreCase).SetEquals(current.Volume)) + { + error = "The volume filter allowance changed during the request. No update was attempted. Retry the mount."; + tracer.RelatedWarning(error); + return AllowFilterResult.Failed; + } + + List updated = new List(current.Volume) { ProjFSFilter.ServiceName }; + EventMetadata audit = new EventMetadata + { + { "VolumeRoot", volumeRoot }, + { "PreviousVolumeFilters", string.Join(",", current.Volume) }, + { "RequestedVolumeFilters", string.Join(",", updated) }, + }; + tracer.RelatedEvent(EventLevel.Informational, "DevDriveFilterPolicy_UpdateAttempt", audit, Keywords.Telemetry); + + string volumeArgument = CommandLineEscaping.EscapeArgument(volumeRoot); + ProcessResult write = runFsUtil($"devdrv setfiltersallowed /volume {volumeArgument} \"{string.Join(",", updated)}\""); + audit.Add("ExitCode", write.ExitCode); + tracer.RelatedEvent(EventLevel.Informational, "DevDriveFilterPolicy_UpdateResult", audit, Keywords.Telemetry); + + // On a busy volume fsutil can persist the allowance but fail to dismount. + // Read back even after a nonzero exit; do not report an unverified write as success. + if (!TryQueryPolicy(volumeRoot, runFsUtil, tracer, out Allowances verified, out string verifyError)) + { + error = $"The volume allowance update was attempted, but verification failed. {verifyError} {write.Output} {write.Errors}".Trim(); + tracer.RelatedWarning(error); + return AllowFilterResult.Failed; + } + + List missing = updated.Except(verified.Volume, StringComparer.OrdinalIgnoreCase).ToList(); + if (missing.Count != 0) + { + error = $"The saved volume allowance does not contain these expected filters: {string.Join(",", missing)}. {write.Output} {write.Errors}".Trim(); + tracer.RelatedWarning(error); + return AllowFilterResult.Failed; + } + + audit.Add("SavedVolumeFilters", string.Join(",", verified.Volume)); + tracer.RelatedEvent(EventLevel.Informational, "DevDriveFilterPolicy_UpdateVerified", audit, Keywords.Telemetry); + error = null; + if (write.ExitCode != 0) + { + tracer.RelatedWarning($"The volume allowance persists, but fsutil reported exit {write.ExitCode}: {write.Output} {write.Errors}"); + return AllowFilterResult.RemountRequired; + } + + return AllowFilterResult.Added; + } + + internal static bool TryParseAllowedFilters(string queryOutput, out Allowances allowances) + { + allowances = null; + if (string.IsNullOrWhiteSpace(queryOutput)) + { + return false; + } + + Dictionary> sections = new Dictionary>(StringComparer.Ordinal); + List currentSection = null; + bool developerVolume = false; + foreach (string rawLine in queryOutput.Split('\n')) + { + string line = rawLine.Trim(); + if (line.Length == 0) + { + currentSection = null; + continue; + } + + if (line == VolumeHeader || line == MachineHeader || line == GroupPolicyHeader || line == AttachedHeader) + { + if (sections.ContainsKey(line)) + { + return false; + } + + currentSection = new List(); + sections.Add(line, currentSection); + } + else if (currentSection != null) + { + string filterLine = line.EndsWith(",", StringComparison.Ordinal) ? line.Substring(0, line.Length - 1) : line; + foreach (string token in filterLine.Split(',')) + { + string name = token.Trim(); + if (!FilterNamePattern.IsMatch(name)) + { + return false; + } + + currentSection.Add(name); + } + } + else if (line == "This is a trusted developer volume." || line == "This is an untrusted developer volume.") + { + developerVolume = true; + } + else if (line != "Developer volumes are protected by antivirus filter, by group policy." + && line != "Developer volumes are protected by antivirus filter.") + { + return false; + } + } + + if (!developerVolume || sections.Any(section => section.Key != AttachedHeader && section.Value.Count == 0)) + { + return false; + } + + allowances = new Allowances( + sections.TryGetValue(VolumeHeader, out List volume) ? volume : new List(), + sections.Where(section => section.Key == MachineHeader || section.Key == GroupPolicyHeader).SelectMany(section => section.Value).ToList()); + return true; + } + + private static bool TryQueryPolicy( + string volumeRoot, + Func runFsUtil, + ITracer tracer, + out Allowances allowances, + out string error) + { + allowances = null; + ProcessResult result = runFsUtil("devdrv query " + CommandLineEscaping.EscapeArgument(volumeRoot)); + if (result.ExitCode != 0) + { + error = $"The Dev Drive query failed with exit {result.ExitCode}: {result.Output} {result.Errors}".Trim(); + } + else if (!TryParseAllowedFilters(result.Output, out allowances)) + { + error = "The Dev Drive query output was not recognized. No further policy changes were made."; + } + else + { + error = null; + return true; + } + + tracer.RelatedWarning(error); + return false; + } + + private static ProcessResult RunFsUtil(string arguments, TimeSpan timeout, ITracer tracer) + { + return RunProcess( + new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "fsutil.exe"), arguments) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }, + timeout, + tracer); + } + + internal static ProcessResult RunProcess(ProcessStartInfo startInfo, TimeSpan timeout, ITracer tracer) + { + if (timeout <= TimeSpan.Zero) + { + return new ProcessResult(string.Empty, "The Dev Drive policy update exceeded its 30-second budget.", -1); + } + + using (Process process = new Process()) + using (CancellationTokenSource deadline = new CancellationTokenSource(timeout)) + { + process.StartInfo = startInfo; + process.Start(); + using (deadline.Token.Register(() => + { + try + { + process.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) + { + // The child exited between cancellation and termination. + } + catch (Exception e) when (e is Win32Exception || e is AggregateException) + { + tracer.RelatedWarning($"Failed to stop the timed-out fsutil process: {e}"); + } + })) + { + try + { + Task output = process.StandardOutput.ReadToEndAsync(deadline.Token); + Task errors = process.StandardError.ReadToEndAsync(deadline.Token); + Task.WhenAll(output, errors, process.WaitForExitAsync(deadline.Token)).GetAwaiter().GetResult(); + return new ProcessResult(output.Result, errors.Result, process.ExitCode); + } + catch (OperationCanceledException) + { + return new ProcessResult(string.Empty, "The Dev Drive policy update timed out. The saved allowance can already include the change.", -1); + } + finally + { + // Cancellation can finish the waits before its termination callback runs. + // Stop and observe the child before disposal can unregister that callback. + try + { + if (!process.HasExited) + { + try + { + process.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) + { + // The child exited between the state check and termination. + } + + if (!process.WaitForExit(5000)) + { + throw new Win32Exception("The policy process did not stop within the cleanup deadline."); + } + } + } + catch (Exception e) when (e is Win32Exception || e is AggregateException) + { + processCleanupFailed = true; + tracer.RelatedWarning($"Further Dev Drive policy updates are disabled because child cleanup failed: {e}"); + throw; + } + } + } + } + } + + internal sealed class Allowances + { + public Allowances(List volume, List inherited) + { + this.Volume = volume; + this.Inherited = inherited; + } + + public List Volume { get; } + public List Inherited { get; } + public bool AllowsProjFS => this.Volume.Concat(this.Inherited).Contains(ProjFSFilter.ServiceName, StringComparer.OrdinalIgnoreCase); + } + } +} diff --git a/GVFS/GVFS.Platform.Windows/ProjFSFilter.cs b/GVFS/GVFS.Platform.Windows/ProjFSFilter.cs index 83ef1cd898..78a09bcbf4 100644 --- a/GVFS/GVFS.Platform.Windows/ProjFSFilter.cs +++ b/GVFS/GVFS.Platform.Windows/ProjFSFilter.cs @@ -72,9 +72,19 @@ public string LogsFolderPath } } - public static bool TryAttach(string enlistmentRoot, out string errorMessage) + /// + /// Attaches the ProjFS filter driver to the volume containing the enlistment, reporting the + /// raw FilterAttach result so that callers can react to a specific failure. + /// + /// + /// The value returned by FilterAttach, or when the attach did not get + /// far enough to call it. + /// + private static bool TryAttach(string enlistmentRoot, out string errorMessage, out uint attachResult, out string volumeRoot) { errorMessage = null; + attachResult = OkResult; + volumeRoot = null; try { StringBuilder volumePathName = new StringBuilder(GVFSConstants.MaxPath); @@ -84,7 +94,9 @@ public static bool TryAttach(string enlistmentRoot, out string errorMessage) return false; } - uint result = NativeMethods.FilterAttach(DriverName, volumePathName.ToString(), null); + volumeRoot = volumePathName.ToString(); + uint result = NativeMethods.FilterAttach(DriverName, volumeRoot, null); + attachResult = result; if (result != OkResult && result != NameCollisionErrorResult) { errorMessage = string.Format("Attaching the filter driver resulted in: {0}", result); @@ -102,32 +114,88 @@ public static bool TryAttach(string enlistmentRoot, out string errorMessage) /// /// Attempts to attach the ProjFS filter driver to the volume containing the enlistment. - /// If an unelevated caller gets ACCESS_DENIED but the ProjFS service is already running, - /// the filter is presumed to already be attached and the call succeeds. + /// On non-ReFS volumes, an unelevated caller can presume attachment when the driver runs. + /// ReFS callers must ask the service to verify attachment. /// public static bool TryAttachToVolume(string enlistmentRoot, ITracer tracer, out string errorMessage) { - if (TryAttach(enlistmentRoot, out errorMessage)) + return TryAttachToVolume(enlistmentRoot, tracer, out errorMessage, out bool _, out string _); + } + + /// + /// Attempts to attach the ProjFS filter driver to the volume containing the enlistment. + /// On non-ReFS volumes, an unelevated caller can presume attachment when the driver runs. + /// ReFS callers must ask the service to verify attachment. + /// + /// + /// True when the attach failed because the volume is a developer volume (Dev Drive) that + /// does not allow this filter. The filter can only attach after PrjFlt is added to the + /// volume's filter allow list. + /// + public static bool TryAttachToVolume(string enlistmentRoot, ITracer tracer, out string errorMessage, out bool devDriveFilterRejected, out string volumeRoot) + { + return TryAttachToVolume( + enlistmentRoot, + tracer, + TryAttach, + WindowsPlatform.IsElevatedImplementation, + () => IsServiceRunning(tracer), + TryGetVolumeFormat, + out errorMessage, + out devDriveFilterRejected, + out volumeRoot); + } + + internal delegate bool AttachFilter(string enlistmentRoot, out string error, out uint result, out string volumeRoot); + internal delegate bool GetVolumeFormat(string volumeRoot, out string format); + + internal static bool TryAttachToVolume( + string enlistmentRoot, + ITracer tracer, + AttachFilter attach, + Func isElevated, + Func isServiceRunning, + GetVolumeFormat getVolumeFormat, + out string errorMessage, + out bool devDriveFilterRejected, + out string volumeRoot) + { + devDriveFilterRejected = false; + + if (attach(enlistmentRoot, out errorMessage, out uint attachResult, out volumeRoot)) { return true; } - // FilterAttach requires SE_LOAD_DRIVER_PRIVILEGE, which is typically only - // granted to administrators. An UNELEVATED caller therefore always gets - // ACCESS_DENIED regardless of whether the filter is actually attached, so - // when the ProjFS service is confirmed running we presume the (already - // elevated) service attached the filter and treat this as success. + devDriveFilterRejected = attachResult == unchecked((uint)HResultExtensions.CantAttachToDevVolume); + + // Unelevated NTFS callers retain the existing assumption that a running driver is + // attached. ReFS needs the service to check: a Dev Drive can reject attachment even + // while the driver runs. Do not depend on the persistent Dev Drive flag here. // // We intentionally do NOT tolerate ACCESS_DENIED for an ELEVATED caller // (e.g. GVFS.Service, which runs as LocalSystem): an elevated caller holds // the privilege, so ACCESS_DENIED there is a genuine failure (AV/EDR lock, // Group Policy, or driver corruption) that must surface rather than be // silently swallowed and leave the mount in a broken state. - if (errorMessage != null - && errorMessage.Contains(AccessDeniedResult.ToString()) - && !WindowsPlatform.IsElevatedImplementation() - && IsServiceRunning(tracer)) + if (attachResult == AccessDeniedResult + && !isElevated() + && isServiceRunning()) { + if (!getVolumeFormat(volumeRoot, out string volumeFormat)) + { + errorMessage = "The volume format could not be read. GVFS.Service must verify ProjFS attachment."; + tracer.RelatedWarning(errorMessage); + return false; + } + + if (volumeFormat.Equals("ReFS", StringComparison.OrdinalIgnoreCase)) + { + errorMessage = "GVFS.Service must verify ProjFS attachment on ReFS."; + tracer.RelatedInfo(errorMessage); + return false; + } + tracer.RelatedInfo($"{nameof(TryAttachToVolume)}: FilterAttach returned ACCESS_DENIED to an unelevated caller, but ProjFS service is running. Proceeding."); errorMessage = null; return true; @@ -136,6 +204,22 @@ public static bool TryAttachToVolume(string enlistmentRoot, ITracer tracer, out return false; } + private static bool TryGetVolumeFormat(string volumeRoot, out string format) + { + StringBuilder buffer = new StringBuilder(GVFSConstants.MaxPath); + bool success = NativeMethods.GetVolumeInformation( + volumeRoot, + null, + 0, + out uint _, + out uint _, + out uint _, + buffer, + GVFSConstants.MaxPath); + format = success ? buffer.ToString() : null; + return success; + } + public static bool IsServiceRunning(ITracer tracer) { try @@ -662,6 +746,18 @@ private bool TryPrepareFolderForCallbacksImpl(string folderPath, out string erro private static class NativeMethods { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool GetVolumeInformation( + string rootPath, + StringBuilder volumeName, + uint volumeNameLength, + out uint serialNumber, + out uint maximumComponentLength, + out uint fileSystemFlags, + StringBuilder fileSystemName, + uint fileSystemNameLength); + [DllImport("fltlib.dll", CharSet = CharSet.Unicode)] public static extern uint FilterAttach( string filterName, diff --git a/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs b/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs new file mode 100644 index 0000000000..c6660dad3a --- /dev/null +++ b/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs @@ -0,0 +1,75 @@ +using GVFS.Common; +using GVFS.Common.Tracing; +using GVFS.Platform.Windows; +using System; + +namespace GVFS.Service.Handlers +{ + internal static class DevDriveFilterRecovery + { + internal static bool TryRecover( + string volumeRoot, + ITracer tracer, + Func<(bool Enabled, string Reason)> readFlag, + Func<(DevDriveFilterPolicy.AllowFilterResult Result, string Error)> allowFilter, + Func<(bool Success, bool Rejected, string Error)> attachFilter, + out string error) + { + EventMetadata metadata = new EventMetadata { { "VolumeRoot", volumeRoot } }; + try + { + (bool enabled, string reason) = readFlag(); + if (!enabled) + { + metadata.Add("Outcome", "Disabled"); + metadata.Add("DisabledReason", reason); + error = $"The mounted volume rejected PrjFlt. {reason} {GetManualInstructions(volumeRoot)}"; + return false; + } + + (DevDriveFilterPolicy.AllowFilterResult result, string policyError) = allowFilter(); + metadata.Add("PolicyResult", result.ToString()); + if (result != DevDriveFilterPolicy.AllowFilterResult.Added + && result != DevDriveFilterPolicy.AllowFilterResult.AlreadyAllowed + && result != DevDriveFilterPolicy.AllowFilterResult.RemountRequired) + { + metadata.Add("Outcome", "PolicyFailed"); + metadata.Add("PolicyError", policyError); + error = $"The mounted volume rejected PrjFlt. {policyError} {GetManualInstructions(volumeRoot)}"; + return false; + } + + (bool success, bool rejected, string attachError) = attachFilter(); + if (success) + { + metadata.Add("Outcome", "Attached"); + error = null; + return true; + } + + metadata.Add("AttachError", attachError); + metadata.Add("Outcome", rejected ? "RemountRequired" : "AttachFailed"); + if (!rejected) + { + error = attachError; + return false; + } + + error = $"PrjFlt is allowed on {volumeRoot}, but the mounted volume still uses its previous filter policy. " + + "Close applications that use the volume. Remount the volume or restart the computer, then retry gvfs mount. " + + "The allowance persists. GVFS did not force-dismount the volume."; + return false; + } + finally + { + tracer.RelatedEvent(EventLevel.Informational, "DevDriveFilterRecovery_Summary", metadata, Keywords.Telemetry); + } + } + + private static string GetManualInstructions(string volumeRoot) + { + return $"From an elevated command prompt, run 'fsutil devdrv query {CommandLineEscaping.EscapeArgument(volumeRoot)}' to inspect the saved allowances. " + + "After any required update, close applications that use the volume and remount it, or restart the computer."; + } + } +} diff --git a/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs b/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs index a1c7c04aed..3c49bde31d 100644 --- a/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs +++ b/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs @@ -1,5 +1,6 @@ using GVFS.Common; using GVFS.Common.FileSystem; +using GVFS.Common.Git; using GVFS.Common.NamedPipes; using GVFS.Common.Tracing; using GVFS.Platform.Windows; @@ -141,8 +142,14 @@ public void Run() if (state == NamedPipeMessages.CompletionState.Success && !string.IsNullOrEmpty(this.request.EnlistmentRoot)) { - string attachError; - if (!ProjFSFilter.TryAttachToVolume(this.request.EnlistmentRoot, this.tracer, out attachError)) + bool attached = ProjFSFilter.TryAttachToVolume( + this.request.EnlistmentRoot, this.tracer, out string attachError, out bool devDriveFilterRejected, out string volumeRoot); + if (!attached && devDriveFilterRejected) + { + attached = this.TryRecoverFilter(volumeRoot, out attachError); + } + + if (!attached) { state = NamedPipeMessages.CompletionState.Failure; errorMessage = attachError; @@ -157,5 +164,52 @@ public void Run() this.WriteToClient(response.ToMessage(), this.connection, this.tracer); } + + private bool TryRecoverFilter(string volumeRoot, out string error) + { + return DevDriveFilterRecovery.TryRecover( + volumeRoot, + this.tracer, + () => + { + bool enabled = this.IsAutoAllowDevDriveFilterEnabled(out string reason); + return (enabled, reason); + }, + () => + { + DevDriveFilterPolicy.AllowFilterResult result = DevDriveFilterPolicy.TryAllowFilter(volumeRoot, this.tracer, out string policyError); + return (result, policyError); + }, + () => + { + bool attached = ProjFSFilter.TryAttachToVolume( + this.request.EnlistmentRoot, this.tracer, out string attachError, out bool rejected, out string _); + return (attached, rejected, attachError); + }, + out error); + } + + /// + /// Reads gvfs.auto-allow-devdrive-filter fresh for this request. The value is deliberately + /// not cached: the service runs for the lifetime of the machine, so a cached value would + /// keep an operator's change from taking effect until the service restarted. + /// + /// + /// The service runs as LocalSystem and cannot see the user's global git config, so it reads + /// the system scope and combines it with the value the client resolved against the + /// enlistment. Either side can turn the feature off; neither can turn it on alone. + /// + private bool IsAutoAllowDevDriveFilterEnabled(out string disabledReason) + { + string gitBinPath = GVFSPlatform.Instance.GitInstallation.GetInstalledGitBinPath(); + LibGit2Repo.TryReadConfigBoolWithGit reader = null; + if (!string.IsNullOrEmpty(gitBinPath)) + { + reader = (string key, out bool? value, out string readError) => + GitProcess.TryGetBoolFromSystemConfig(gitBinPath, key, out value, out readError); + } + + return DevDriveFilterConfig.IsEnabled(reader, this.request.AutoAllowDevDriveFilter, "system", this.tracer, out disabledReason); + } } } diff --git a/GVFS/GVFS.Service/InternalsVisibleTo.cs b/GVFS/GVFS.Service/InternalsVisibleTo.cs new file mode 100644 index 0000000000..9fd1d13ff0 --- /dev/null +++ b/GVFS/GVFS.Service/InternalsVisibleTo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("GVFS.UnitTests")] diff --git a/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs b/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs new file mode 100644 index 0000000000..dabc4161ec --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs @@ -0,0 +1,110 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.NamedPipes; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common +{ + [TestFixture] + public class DevDriveFilterConfigTests + { + [TestCase(null, null, true)] + [TestCase(true, null, true)] + [TestCase(true, true, true)] + [TestCase(false, true, false)] + [TestCase(true, false, false)] + [TestCase(null, false, false)] + [TestCase(false, null, false)] + public void EitherVetoPreventsAnUpdateAndUnsetKeepsTheDefault(bool? system, bool? client, bool expected) + { + DevDriveFilterConfig.IsEnabled( + (string key, out bool? value, out string error) => + { + key.ShouldEqual("gvfs.auto-allow-devdrive-filter"); + value = system; + error = null; + return true; + }, + client, + "system", + new MockTracer(), + out string reason).ShouldEqual(expected); + if (expected) + { + reason.ShouldBeNull(); + } + else + { + reason.ShouldContain(system == false ? "system configuration" : "enlistment configuration"); + } + } + + [TestCase("system")] + [TestCase("enlistment")] + public void FailedReadsNeverSelectTheTrueDefault(string source) + { + MockTracer tracer = new MockTracer(); + DevDriveFilterConfig.IsEnabled( + (string key, out bool? value, out string error) => + { + value = null; + error = "read denied"; + return false; + }, + true, + source, + tracer, + out string reason).ShouldBeFalse(); + reason.ShouldContain("read denied"); + tracer.RelatedWarningEvents.Count.ShouldEqual(1); + } + + [TestCase] + public void MissingGitReaderPreventsAnUpdate() + { + DevDriveFilterConfig.IsEnabled(null, true, "system", new MockTracer(), out string reason).ShouldBeFalse(); + reason.ShouldContain("Git is unavailable"); + } + + [TestCase(0, "true\n", "", true, true)] + [TestCase(0, "false\n", "", true, false)] + [TestCase(1, "", "", true, null)] + [TestCase(1, "", "warning: read failed", false, null)] + [TestCase(2, "", "", false, null)] + [TestCase(128, "", "warning: read failed", false, null)] + [TestCase(-1073741502, "", "", false, null)] + [TestCase(0, "invalid", "", false, null)] + public void SystemBooleanReaderPinsIncludesAndStrictExitHandling( + int exit, string output, string errors, bool expectedSuccess, bool? expectedValue) + { + GitProcess.TryGetBoolFromSystemConfig( + "gvfs.auto-allow-devdrive-filter", + arguments => + { + arguments.ShouldEqual("config --system --includes --type=bool gvfs.auto-allow-devdrive-filter"); + return new GitProcess.Result(output, errors, exit); + }, + out bool? value, + out string error).ShouldEqual(expectedSuccess); + value.ShouldEqual(expectedValue); + if (!expectedSuccess) + { + error.ShouldNotBeNull(); + } + } + + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\"}", null)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":false}", false)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":true}", true)] + public void OldAndNewClientWireMessagesKeepTheNullableVeto(string json, bool? expected) + { + NamedPipeMessages.EnableAndAttachProjFSRequest request = NamedPipeMessages.EnableAndAttachProjFSRequest.FromMessage( + new NamedPipeMessages.Message("EnableAndAttachProjFSRequest", json)); + request.AutoAllowDevDriveFilter.ShouldEqual(expected); + NamedPipeMessages.EnableAndAttachProjFSRequest.FromMessage(request.ToMessage()).AutoAllowDevDriveFilter.ShouldEqual(expected); + request.ToMessage().Body.ShouldContain("\"AutoAllowDevDriveFilter\""); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs b/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs new file mode 100644 index 0000000000..62e3033ff1 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs @@ -0,0 +1,95 @@ +using GVFS.Platform.Windows; +using GVFS.Service.Handlers; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; +using System; + +namespace GVFS.UnitTests.Service +{ + [TestFixture] + public class DevDriveFilterRecoveryTests + { + [TestCase] + public void DisabledGateDoesNotQueryOrWritePolicy() + { + DevDriveFilterRecovery.TryRecover( + @"mock:\volume\", + new MockTracer(), + () => (false, "operator veto"), + () => throw new InvalidOperationException("Policy must not run."), + () => throw new InvalidOperationException("Attach must not run."), + out string error).ShouldBeFalse(); + error.ShouldContain("operator veto"); + error.ShouldNotContain(false, "not on that list"); + } + + [TestCase(DevDriveFilterPolicy.AllowFilterResult.Added)] + [TestCase(DevDriveFilterPolicy.AllowFilterResult.AlreadyAllowed)] + [TestCase(DevDriveFilterPolicy.AllowFilterResult.RemountRequired)] + public void AllowedPolicyRetriesExactlyOnceAndRetainsRemountGuidance(DevDriveFilterPolicy.AllowFilterResult result) + { + int calls = 0; + DevDriveFilterRecovery.TryRecover( + @"mock:\volume\", + new MockTracer(), + () => (true, null), + () => (result, null), + () => + { + ++calls; + return (false, true, "rejected"); + }, + out string error).ShouldBeFalse(); + calls.ShouldEqual(1); + error.ShouldContain("Remount the volume or restart the computer"); + error.ShouldContain("did not force-dismount"); + } + + [TestCase] + public void OtherAttachErrorsKeepTheCauseAndTheMutationSignal() + { + MockTracer tracer = new MockTracer(); + DevDriveFilterRecovery.TryRecover( + @"mock:\volume\", + tracer, + () => (true, null), + () => (DevDriveFilterPolicy.AllowFilterResult.Added, null), + () => (false, false, "specific attach error"), + out string error).ShouldBeFalse(); + error.ShouldEqual("specific attach error"); + tracer.RelatedEventNames.ShouldMatchInOrder("DevDriveFilterRecovery_Summary"); + tracer.RelatedEventMetadata[0]["PolicyResult"].ShouldEqual("Added"); + tracer.RelatedEventMetadata[0]["Outcome"].ShouldEqual("AttachFailed"); + } + + [TestCase(DevDriveFilterPolicy.AllowFilterResult.PolicyUnreadable)] + [TestCase(DevDriveFilterPolicy.AllowFilterResult.Failed)] + public void PolicyFailuresDoNotRetryAttachmentOrInventAnAbsentFilter(DevDriveFilterPolicy.AllowFilterResult result) + { + DevDriveFilterRecovery.TryRecover( + @"mock:\volume\", + new MockTracer(), + () => (true, null), + () => (result, "query or write error"), + () => throw new InvalidOperationException("Attach must not run."), + out string error).ShouldBeFalse(); + error.ShouldContain("query or write error"); + error.ShouldContain("fsutil devdrv query"); + error.ShouldNotContain(false, "not on that list"); + } + + [TestCase] + public void SuccessfulRetryReturnsSuccessWithoutAnError() + { + DevDriveFilterRecovery.TryRecover( + @"mock:\volume\", + new MockTracer(), + () => (true, null), + () => (DevDriveFilterPolicy.AllowFilterResult.Added, null), + () => (true, false, null), + out string error).ShouldBeTrue(); + error.ShouldBeNull(); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs b/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs new file mode 100644 index 0000000000..fc08be388f --- /dev/null +++ b/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs @@ -0,0 +1,199 @@ +using GVFS.Common; +using GVFS.Common.Tracing; +using GVFS.Platform.Windows; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; +using System.Collections.Generic; +using System.Linq; + +namespace GVFS.UnitTests.Windows.Platform +{ + [TestFixture] + public class DevDriveFilterPolicyTests + { + private const string Root = @"mock:\volume\"; + private const string Preamble = "This is a trusted developer volume.\r\n\r\n"; + private const string Enterprise = + "Developer volumes are protected by antivirus filter, by group policy.\r\n\r\n" + + "Filters allowed on any developer volume, by group policy:\r\n MsSecFlt\r\n\r\n"; + private const string Machine = "Filters allowed on any developer volume:\r\n DfmFlt\r\n\r\n"; + private const string VolumeHeader = "Filters allowed on this developer volume:\r\n"; + + [TestCase] + public void ParserSeparatesVolumeAllowancesFromInheritedAndAttachedFilters() + { + string output = Preamble + Enterprise + Machine + VolumeHeader + " bindflt\r\n\r\n" + + "Filters currently attached to this developer volume:\r\n WdFilter\r\n"; + DevDriveFilterPolicy.TryParseAllowedFilters(output, out DevDriveFilterPolicy.Allowances parsed).ShouldBeTrue(); + parsed.Volume.ShouldMatchInOrder("bindflt"); + parsed.Inherited.ShouldMatchInOrder("MsSecFlt", "DfmFlt"); + parsed.AllowsProjFS.ShouldBeFalse(); + } + + [TestCase] + public void ParserPreservesEveryLineOfVolumeAllowances() + { + DevDriveFilterPolicy.TryParseAllowedFilters( + Preamble + VolumeHeader + " bindflt,\r\n wcifs, DfmFlt\r\n", + out DevDriveFilterPolicy.Allowances parsed).ShouldBeTrue(); + parsed.Volume.ShouldMatchInOrder("bindflt", "wcifs", "DfmFlt"); + } + + [TestCase(null)] + [TestCase("")] + [TestCase(Preamble + VolumeHeader)] + [TestCase(Preamble + VolumeHeader + " DfmFlt,,wcifs\r\n")] + [TestCase(Preamble + VolumeHeader + " DfmFlt,,\r\n")] + [TestCase(Preamble + VolumeHeader + " PrjFlt DfmFlt\r\n")] + [TestCase(Preamble + VolumeHeader + " DfmFlt,\" /f\r\n")] + [TestCase(Preamble + VolumeHeader + " DfmFlt\r\n unrecognized continuation text\r\n")] + [TestCase(Preamble + VolumeHeader + " DfmFlt\r\n\r\n" + VolumeHeader + " wcifs\r\n")] + [TestCase(Preamble + VolumeHeader + " PrjFl\u0442\r\n")] + [TestCase("Developer volumes are enabled.\r\n")] + [TestCase("This is a trusted developer volume.\r" + VolumeHeader + " DfmFlt\r")] + public void ParserRejectsAmbiguousOrUnrecognizedOutput(string output) + { + DevDriveFilterPolicy.TryParseAllowedFilters(output, out DevDriveFilterPolicy.Allowances parsed).ShouldBeFalse(); + parsed.ShouldBeNull(); + } + + [TestCase(0, DevDriveFilterPolicy.AllowFilterResult.Added)] + [TestCase(5, DevDriveFilterPolicy.AllowFilterResult.RemountRequired)] + [TestCase(-1, DevDriveFilterPolicy.AllowFilterResult.RemountRequired)] + public void AllowFilterPreservesOnlyVolumeEntriesAndVerifiesBusyWrites(int writeExit, DevDriveFilterPolicy.AllowFilterResult expected) + { + string before = Preamble + Enterprise + Machine + VolumeHeader + " bindflt\r\n"; + Queue commands = new Queue(new[] + { + @"devdrv query mock:\volume\", + @"devdrv query mock:\volume\", + "devdrv setfiltersallowed /volume mock:\\volume\\ \"bindflt,PrjFlt\"", + @"devdrv query mock:\volume\", + }); + Queue results = new Queue(new[] + { + Query(before), + Query(before), + new ProcessResult("Volume is in use.", string.Empty, writeExit), + Query(Preamble + Enterprise + Machine + VolumeHeader + " bindflt,prjflt\r\n"), + }); + MockTracer tracer = new MockTracer(); + + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + command.ShouldEqual(commands.Dequeue()); + return results.Dequeue(); + }, + tracer, + out string error).ShouldEqual(expected); + error.ShouldBeNull(); + commands.Count.ShouldEqual(0); + tracer.RelatedEventNames.ShouldMatchInOrder( + "DevDriveFilterPolicy_UpdateAttempt", "DevDriveFilterPolicy_UpdateResult", "DevDriveFilterPolicy_UpdateVerified"); + tracer.RelatedEventMetadata.Last()["PreviousVolumeFilters"].ShouldEqual("bindflt"); + tracer.RelatedEventMetadata.Last()["SavedVolumeFilters"].ShouldEqual("bindflt,prjflt"); + tracer.RelatedWarningEvents.Count.ShouldEqual(writeExit == 0 ? 0 : 1); + } + + [TestCase(Preamble + Enterprise + "Filters allowed on any developer volume:\r\n PrjFlt,DfmFlt\r\n")] + [TestCase(Preamble + "Filters allowed on any developer volume, by group policy:\r\n PrjFlt\r\n")] + [TestCase(Preamble + VolumeHeader + " prjflt\r\n")] + public void AllowFilterDoesNotWriteWhenAnyApplicableListAlreadyAllowsFilter(string output) + { + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + command.ShouldEqual(@"devdrv query mock:\volume\"); + return Query(output); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.AlreadyAllowed); + error.ShouldBeNull(); + } + + [TestCase] + public void AllowFilterAddsOnlyPrjFltWhenVolumeListIsAbsent() + { + Queue results = new Queue(new[] + { + Query(Preamble + Enterprise + Machine), + Query(Preamble + Enterprise + Machine), + Query(string.Empty), + Query(Preamble + Enterprise + Machine + VolumeHeader + " PrjFlt\r\n"), + }); + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + if (results.Count == 2) + { + command.ShouldEqual("devdrv setfiltersallowed /volume mock:\\volume\\ \"PrjFlt\""); + } + + return results.Dequeue(); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Added); + results.Count.ShouldEqual(0); + error.ShouldBeNull(); + } + + [TestCase] + public void AllowFilterAbortsWhenThePreWriteRecheckObservesAChange() + { + int calls = 0; + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + command.ShouldEqual(@"devdrv query mock:\volume\"); + return Query(++calls == 1 ? Preamble : Preamble + VolumeHeader + " wcifs\r\n"); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Failed); + calls.ShouldEqual(2); + error.ShouldContain("changed during the request"); + } + + [TestCase(5, "Access denied.")] + [TestCase(-1, "Timed out.")] + [TestCase(0, "Unrecognized output.")] + public void AllowFilterDoesNotWriteWhenTheInitialQueryFails(int exitCode, string output) + { + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + command.ShouldEqual(@"devdrv query mock:\volume\"); + return new ProcessResult(output, string.Empty, exitCode); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.PolicyUnreadable); + error.ShouldNotBeNull(); + } + + [TestCase(5, "Access denied.", "verification failed")] + [TestCase(0, "Unrecognized output.", "verification failed")] + [TestCase(0, Preamble, "does not contain")] + public void AllowFilterDoesNotReportAnUnverifiedWriteAsSuccess(int verifyExit, string output, string message) + { + int calls = 0; + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => ++calls < 4 ? Query(Preamble) : new ProcessResult(output, string.Empty, verifyExit), + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Failed); + calls.ShouldEqual(4); + error.ShouldContain(message); + } + + private static ProcessResult Query(string output) + { + return new ProcessResult(output, string.Empty, 0); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Windows/Platform/ProjFSFilterTests.cs b/GVFS/GVFS.UnitTests/Windows/Platform/ProjFSFilterTests.cs index acf3a4d2b8..d09b30e6fe 100644 --- a/GVFS/GVFS.UnitTests/Windows/Platform/ProjFSFilterTests.cs +++ b/GVFS/GVFS.UnitTests/Windows/Platform/ProjFSFilterTests.cs @@ -62,6 +62,63 @@ public void IsNativeLibInstalled_ReturnsFalseWhenOnlyAppLocalLibExists() ProjFSFilter.IsNativeLibInstalled(this.mockTracer, this.mockFileSystem.Object).ShouldBeFalse(); } + [TestCase(0u, false, true, true, "NTFS", true, false)] + [TestCase(0x80070005u, false, true, true, "NTFS", true, false)] + [TestCase(0x80070005u, false, true, true, "ReFS", false, false)] + [TestCase(0x80070005u, false, true, false, null, false, false)] + [TestCase(0x80070005u, true, true, true, "NTFS", false, false)] + [TestCase(0x80070005u, false, false, true, "NTFS", false, false)] + [TestCase(0x800701DEu, true, true, true, "ReFS", false, true)] + public void AttachmentDecisionPreservesNtfsAndRequiresServiceVerificationForRefs( + uint result, + bool elevated, + bool running, + bool formatReadable, + string volumeFormat, + bool expected, + bool rejected) + { + int attachCalls = 0; + ProjFSFilter.TryAttachToVolume( + @"mock:\src", + this.mockTracer, + (string path, out string error, out uint nativeResult, out string root) => + { + ++attachCalls; + path.ShouldEqual(@"mock:\src"); + nativeResult = result; + error = result == 0 ? null : "native failure"; + root = @"mock:\volume\"; + return result == 0; + }, + () => elevated, + () => running, + (string root, out string format) => + { + root.ShouldEqual(@"mock:\volume\"); + format = volumeFormat; + return formatReadable; + }, + out string attachError, + out bool devDriveRejected, + out string volumeRoot).ShouldEqual(expected); + attachCalls.ShouldEqual(1); + devDriveRejected.ShouldEqual(rejected); + volumeRoot.ShouldEqual(@"mock:\volume\"); + if (expected) + { + attachError.ShouldBeNull(); + } + else if (result == 0x80070005u && !elevated && running) + { + attachError.ShouldContain("GVFS.Service"); + } + else + { + attachError.ShouldEqual("native failure"); + } + } + [TestCase] public void TryGetDisabledStartTypeError_ReturnsActionableMessageForDisabledService() { diff --git a/GVFS/GVFS/CommandLine/GVFSVerb.cs b/GVFS/GVFS/CommandLine/GVFSVerb.cs index 83ea85b3ae..cfb9d9617c 100644 --- a/GVFS/GVFS/CommandLine/GVFSVerb.cs +++ b/GVFS/GVFS/CommandLine/GVFSVerb.cs @@ -567,14 +567,31 @@ protected bool TryDownloadRootGitAttributes(GVFSEnlistment enlistment, GVFSGitOb /// /// Enlistment root. If string.Empty, PrjFlt will be enabled but not attached to any volumes /// Error meesage (in the case of failure) + /// Tracer used to read enlistment config. If null, the enlistment's config is not consulted /// True is successful and false otherwise - protected bool TryEnableAndAttachPrjFltThroughService(string enlistmentRoot, out string errorMessage) + protected bool TryEnableAndAttachPrjFltThroughService(string enlistmentRoot, out string errorMessage, ITracer tracer = null) { errorMessage = string.Empty; NamedPipeMessages.EnableAndAttachProjFSRequest request = new NamedPipeMessages.EnableAndAttachProjFSRequest(); request.EnlistmentRoot = enlistmentRoot; + // The service runs as LocalSystem and cannot read the user's global git config, so + // resolve the flag here against the enlistment and let the service combine it with the + // system-scoped value. Reading it per request keeps a config change from needing a + // service restart to take effect. + if (tracer != null && !string.IsNullOrEmpty(enlistmentRoot)) + { + string gitBinPath = GVFSPlatform.Instance.GitInstallation.GetInstalledGitBinPath(); + GitProcess git = string.IsNullOrEmpty(gitBinPath) ? null : new GitProcess(gitBinPath, enlistmentRoot); + request.AutoAllowDevDriveFilter = DevDriveFilterConfig.IsEnabled( + git == null ? null : git.TryGetBoolFromConfig, + clientValue: null, + source: "enlistment", + tracer, + out string _); + } + using (NamedPipeClient client = new NamedPipeClient(this.ServicePipeName)) { if (!client.Connect()) diff --git a/GVFS/GVFS/CommandLine/MountVerb.cs b/GVFS/GVFS/CommandLine/MountVerb.cs index 6433dddb73..ae212aa4fc 100644 --- a/GVFS/GVFS/CommandLine/MountVerb.cs +++ b/GVFS/GVFS/CommandLine/MountVerb.cs @@ -198,7 +198,7 @@ protected override void Execute(GVFSEnlistment enlistment) }); if (!this.ShowStatusWhileRunning( - () => { return this.TryEnableAndAttachPrjFltThroughService(enlistment.WorkingDirectoryRoot, out errorMessage); }, + () => { return this.TryEnableAndAttachPrjFltThroughService(enlistment.WorkingDirectoryRoot, out errorMessage, tracer); }, $"Attaching ProjFS to volume")) { this.ReportErrorAndExit(tracer, ReturnCode.FilterError, errorMessage); From 6f8604721d5f940d2485a1d8a0af64a2f6499fef Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Tue, 17 Nov 2026 08:34:21 -0800 Subject: [PATCH 2/6] Use bounded shared readers for Dev Drive configuration Read both the client and system boolean through the shared Git config reader. Keep system includes and conditional client includes. Use one deadline across attempts and pass the caller's tracer to the retry policy. Treat timeouts, truncated output, process failures, and unavailable enlistments as read failures. Do not select the default on failure. Wait for a cancelled child to exit before its process handle closes. Add isolated unit tests for scope, strict results, retry telemetry, timeouts, and process-start errors. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- GVFS/GVFS.Common/DevDriveFilterConfig.cs | 3 + GVFS/GVFS.Common/Git/GitProcess.cs | 59 +++++-- .../GVFS.Common/Git/GitProcessConfigReader.cs | 62 ++++++++ .../Handlers/EnableAndAttachProjFSHandler.cs | 3 +- .../Common/DevDriveFilterConfigTests.cs | 149 +++++++++++++++++- GVFS/GVFS/CommandLine/GVFSVerb.cs | 6 +- 6 files changed, 262 insertions(+), 20 deletions(-) diff --git a/GVFS/GVFS.Common/DevDriveFilterConfig.cs b/GVFS/GVFS.Common/DevDriveFilterConfig.cs index 30d6f55734..138358fd0b 100644 --- a/GVFS/GVFS.Common/DevDriveFilterConfig.cs +++ b/GVFS/GVFS.Common/DevDriveFilterConfig.cs @@ -1,10 +1,13 @@ using GVFS.Common.Git; using GVFS.Common.Tracing; +using System; namespace GVFS.Common { public static class DevDriveFilterConfig { + public static readonly TimeSpan ReadTimeout = TimeSpan.FromSeconds(5); + public static bool IsEnabled( LibGit2Repo.TryReadConfigBoolWithGit readConfig, bool? clientValue, diff --git a/GVFS/GVFS.Common/Git/GitProcess.cs b/GVFS/GVFS.Common/Git/GitProcess.cs index a89f176315..559d951f47 100644 --- a/GVFS/GVFS.Common/Git/GitProcess.cs +++ b/GVFS/GVFS.Common/Git/GitProcess.cs @@ -201,22 +201,6 @@ public static ConfigResult GetFromSystemConfig(string gitBinPath, string setting settingName); } - public static bool TryGetBoolFromSystemConfig(string gitBinPath, string settingName, out bool? value, out string error) - { - GitProcess git = new GitProcess(gitBinPath, workingDirectoryRoot: null); - return TryGetBoolFromSystemConfig( - settingName, - arguments => git.InvokeConfigRead(settingName, () => git.InvokeGitOutsideEnlistment(arguments)), - out value, - out error); - } - - internal static bool TryGetBoolFromSystemConfig(string settingName, Func readConfig, out bool? value, out string error) - { - Result result = readConfig("config --system --includes --type=bool " + settingName); - return LibGit2Repo.TryParseConfigBoolOutput(settingName, result.ExitCode, result.Output, result.Errors, out value, out error); - } - public static ConfigResult GetFromFileConfig(string gitBinPath, string configFile, string settingName) { GitProcess git = new GitProcess(gitBinPath, workingDirectoryRoot: null); @@ -672,6 +656,49 @@ public bool TryGetBoolFromConfig(string settingName, out bool? value, out string return LibGit2Repo.TryParseConfigBoolOutput(settingName, result.ExitCode, result.Output, result.Errors, out value, out error); } + /// + /// Reads a boolean with Git within one deadline for all attempts and retry delays. + /// Returns null for an unset key and reports read errors without choosing a default. + /// + public bool TryGetBoolFromConfig( + string settingName, + GitConfigBoolScope scope, + TimeSpan timeout, + ITracer tracer, + out bool? value, + out string error) + { + tracer = tracer ?? NullTracer.Instance; + bool useRepository = scope == GitConfigBoolScope.Merged && this.workingDirectoryRoot != null; + if (useRepository && !Directory.Exists(this.workingDirectoryRoot)) + { + value = null; + error = $"Cannot read '{settingName}': the enlistment directory is unavailable."; + tracer.RelatedWarning(error); + return false; + } + + return GitProcessConfigReader.TryReadBool( + settingName, + scope, + (arguments, cancellation) => GitProcessConfigReader.ReadRaw( + settingName, + () => this.GetGitProcess( + arguments, + Environment.SystemDirectory, + useRepository ? this.gitDirPath : null, + useReadObjectHook: false, + gitObjectsDirectory: null, + usePreCommandHook: !useRepository), + string.Empty, + cancellation, + tracer), + timeout, + tracer, + out value, + out error); + } + public ConfigResult GetFromLocalConfig(string settingName) { // See GetFromConfig above for why pre-command hook is disabled here. diff --git a/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs b/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs index 2f143e8bf6..94175a5572 100644 --- a/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs +++ b/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs @@ -11,11 +11,72 @@ namespace GVFS.Common.Git { + public enum GitConfigBoolScope + { + Merged, + System, + } + internal static class GitProcessConfigReader { private const int MaxOutput = 65536; private const int MaxErrors = 4096; + internal static bool TryReadBool( + string key, + GitConfigBoolScope scope, + Func readConfig, + TimeSpan timeout, + ITracer tracer, + out bool? value, + out string error) + { + value = null; + error = null; + tracer = tracer ?? NullTracer.Instance; + if (scope != GitConfigBoolScope.System && scope != GitConfigBoolScope.Merged) + { + throw new ArgumentOutOfRangeException(nameof(scope)); + } + + string arguments = scope == GitConfigBoolScope.System + ? "config --system --includes --type=bool " + key + : LibGit2Repo.GetConfigBoolArguments(key); + + using (CancellationTokenSource deadline = new CancellationTokenSource(timeout)) + { + try + { + GitProcess.Result result = readConfig(arguments, deadline.Token); + if (result.OutputTruncated || result.ErrorsTruncated) + { + error = $"Error while reading '{key}' from config: output was truncated."; + return false; + } + + if (result.ExitCode == 1 && !string.IsNullOrWhiteSpace(result.Output)) + { + error = $"Error while reading '{key}' from config: unexpected output for an unset value."; + return false; + } + + return LibGit2Repo.TryParseConfigBoolOutput(key, result.ExitCode, result.Output, result.Errors, out value, out error); + } + catch (OperationCanceledException) when (deadline.IsCancellationRequested) + { + error = $"The Git configuration read for '{key}' timed out."; + tracer.RelatedWarning(error); + return false; + } + catch (Exception e) when (e is GitConfigProcessException || e is Win32Exception || e is IOException || e is UnauthorizedAccessException) + { + error = $"The Git configuration read for '{key}' failed: {e.Message}"; + tracer.RelatedWarning($"{error} {e}"); + return false; + } + } + } + // If the caller runs Git and returns a result, use Read for retries. internal static GitProcess.Result Read( string configName, @@ -160,6 +221,7 @@ internal static GitProcess.Result ReadRaw( { killTree(); } + } catch (Exception cleanupFailure) when (failure != null || readFailure != null) { diff --git a/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs b/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs index 3c49bde31d..9f3b1d6811 100644 --- a/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs +++ b/GVFS/GVFS.Service/Handlers/EnableAndAttachProjFSHandler.cs @@ -205,8 +205,9 @@ private bool IsAutoAllowDevDriveFilterEnabled(out string disabledReason) LibGit2Repo.TryReadConfigBoolWithGit reader = null; if (!string.IsNullOrEmpty(gitBinPath)) { + GitProcess git = new GitProcess(gitBinPath, workingDirectoryRoot: null); reader = (string key, out bool? value, out string readError) => - GitProcess.TryGetBoolFromSystemConfig(gitBinPath, key, out value, out readError); + git.TryGetBoolFromConfig(key, GitConfigBoolScope.System, DevDriveFilterConfig.ReadTimeout, this.tracer, out value, out readError); } return DevDriveFilterConfig.IsEnabled(reader, this.request.AutoAllowDevDriveFilter, "system", this.tracer, out disabledReason); diff --git a/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs b/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs index dabc4161ec..3020c75e80 100644 --- a/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs +++ b/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs @@ -3,7 +3,10 @@ using GVFS.Common.NamedPipes; using GVFS.Tests.Should; using GVFS.UnitTests.Mock.Common; +using GVFS.UnitTests.Category; using NUnit.Framework; +using System; +using System.ComponentModel; namespace GVFS.UnitTests.Common { @@ -79,13 +82,16 @@ public void MissingGitReaderPreventsAnUpdate() public void SystemBooleanReaderPinsIncludesAndStrictExitHandling( int exit, string output, string errors, bool expectedSuccess, bool? expectedValue) { - GitProcess.TryGetBoolFromSystemConfig( + GitProcessConfigReader.TryReadBool( "gvfs.auto-allow-devdrive-filter", - arguments => + GitConfigBoolScope.System, + (arguments, cancellation) => { arguments.ShouldEqual("config --system --includes --type=bool gvfs.auto-allow-devdrive-filter"); return new GitProcess.Result(output, errors, exit); }, + TimeSpan.FromSeconds(1), + new MockTracer(), out bool? value, out string error).ShouldEqual(expectedSuccess); value.ShouldEqual(expectedValue); @@ -95,6 +101,145 @@ public void SystemBooleanReaderPinsIncludesAndStrictExitHandling( } } + [TestCase(false, "config --type=bool gvfs.auto-allow-devdrive-filter")] + [TestCase(true, "config --system --includes --type=bool gvfs.auto-allow-devdrive-filter")] + public void BooleanReaderSelectsTheRequestedScope(bool systemScope, string expectedArguments) + { + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + systemScope ? GitConfigBoolScope.System : GitConfigBoolScope.Merged, + (arguments, cancellation) => + { + arguments.ShouldEqual(expectedArguments); + return new GitProcess.Result("false\n", string.Empty, 0); + }, + TimeSpan.FromSeconds(1), + new MockTracer(), + out bool? value, + out string error).ShouldBeTrue(); + value.ShouldEqual(false); + error.ShouldBeNull(); + } + + [TestCase(true, false)] + [TestCase(false, true)] + public void TruncatedBooleanOutputDoesNotEnableTheFeature(bool outputTruncated, bool errorsTruncated) + { + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + GitConfigBoolScope.Merged, + (arguments, cancellation) => new GitProcess.Result("true", string.Empty, 0, outputTruncated, errorsTruncated), + TimeSpan.FromSeconds(1), + new MockTracer(), + out bool? value, + out string error).ShouldBeFalse(); + value.HasValue.ShouldBeFalse(); + error.ShouldContain("truncated"); + } + + [TestCase] + [NUnit.Framework.Category(CategoryConstants.ExceptionExpected)] + public void TimedOutBooleanReadFailsClosedAndLogs() + { + MockTracer tracer = new MockTracer(); + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + GitConfigBoolScope.Merged, + (arguments, cancellation) => + { + if (!cancellation.WaitHandle.WaitOne(TimeSpan.FromSeconds(1))) + { + throw new InvalidOperationException("The timeout did not cancel the read."); + } + + cancellation.ThrowIfCancellationRequested(); + throw new InvalidOperationException("The timeout did not cancel the read."); + }, + TimeSpan.FromMilliseconds(20), + tracer, + out bool? value, + out string error).ShouldBeFalse(); + value.HasValue.ShouldBeFalse(); + error.ShouldContain("timed out"); + tracer.RelatedWarningEvents.Count.ShouldEqual(1); + } + + [TestCase] + [NUnit.Framework.Category(CategoryConstants.ExceptionExpected)] + public void FailedProcessStartReportsAnErrorAndLogs() + { + MockTracer tracer = new MockTracer(); + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + GitConfigBoolScope.Merged, + (arguments, cancellation) => throw new Win32Exception(2), + TimeSpan.FromSeconds(1), + tracer, + out bool? value, + out string error).ShouldBeFalse(); + value.HasValue.ShouldBeFalse(); + error.ShouldContain("failed"); + tracer.RelatedWarningEvents.Count.ShouldEqual(1); + } + + [TestCase] + [NUnit.Framework.Category(CategoryConstants.ExceptionExpected)] + public void TypedProcessFailureReportsAnErrorAndLogs() + { + MockTracer tracer = new MockTracer(); + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + GitConfigBoolScope.System, + (arguments, cancellation) => throw new GitConfigProcessException(new Win32Exception(2)), + TimeSpan.FromSeconds(1), + tracer, + out bool? value, + out string error).ShouldBeFalse(); + value.HasValue.ShouldBeFalse(); + error.ShouldContain("failed"); + tracer.RelatedWarningEvents.Count.ShouldEqual(1); + } + + [TestCase] + public void UnsetExitWithOutputIsNotTreatedAsAnAbsentFlag() + { + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + GitConfigBoolScope.System, + (arguments, cancellation) => new GitProcess.Result("false", string.Empty, 1), + TimeSpan.FromSeconds(1), + new MockTracer(), + out bool? value, + out string error).ShouldBeFalse(); + value.HasValue.ShouldBeFalse(); + error.ShouldContain("unexpected output"); + } + + [TestCase] + public void BooleanReadReportsSharedRetryTelemetry() + { + int calls = 0; + MockTracer tracer = new MockTracer(); + GitProcessConfigReader.TryReadBool( + "gvfs.auto-allow-devdrive-filter", + GitConfigBoolScope.System, + (arguments, cancellation) => GitProcessConfigReader.Read( + "gvfs.auto-allow-devdrive-filter", + () => ++calls == 1 + ? new GitProcess.Result(string.Empty, "warning: unable to access 'mock:\\config': Permission denied", 1) + : new GitProcess.Result("false\n", string.Empty, 0), + tracer, + delay => { }), + TimeSpan.FromSeconds(1), + tracer, + out bool? value, + out string error).ShouldBeTrue(); + calls.ShouldEqual(2); + value.ShouldEqual(false); + error.ShouldBeNull(); + tracer.TelemetryWarnings.Count.ShouldEqual(1); + } + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\"}", null)] [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":false}", false)] [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":true}", true)] diff --git a/GVFS/GVFS/CommandLine/GVFSVerb.cs b/GVFS/GVFS/CommandLine/GVFSVerb.cs index cfb9d9617c..88d7df3712 100644 --- a/GVFS/GVFS/CommandLine/GVFSVerb.cs +++ b/GVFS/GVFS/CommandLine/GVFSVerb.cs @@ -584,8 +584,12 @@ protected bool TryEnableAndAttachPrjFltThroughService(string enlistmentRoot, out { string gitBinPath = GVFSPlatform.Instance.GitInstallation.GetInstalledGitBinPath(); GitProcess git = string.IsNullOrEmpty(gitBinPath) ? null : new GitProcess(gitBinPath, enlistmentRoot); + LibGit2Repo.TryReadConfigBoolWithGit reader = git == null + ? null + : (string key, out bool? value, out string readError) => + git.TryGetBoolFromConfig(key, GitConfigBoolScope.Merged, DevDriveFilterConfig.ReadTimeout, tracer, out value, out readError); request.AutoAllowDevDriveFilter = DevDriveFilterConfig.IsEnabled( - git == null ? null : git.TryGetBoolFromConfig, + reader, clientValue: null, source: "enlistment", tracer, From b624d840e6390cb0e63f657ac96f681c926fa839 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Tue, 17 Nov 2026 08:53:03 -0800 Subject: [PATCH 3/6] Reject incomplete Dev Drive filter queries Require the observed final attached-filter section and a complete last line before the service interprets an omitted volume list. Reject unfinished filter-list continuations and query diagnostics. Add unit tests for truncated captured outputs, incomplete queries before writes, and failed readback after an attempted update. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../DevDriveFilterPolicy.cs | 35 +++++- .../Platform/DevDriveFilterPolicyTests.cs | 114 ++++++++++++++++-- 2 files changed, 131 insertions(+), 18 deletions(-) diff --git a/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs b/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs index 416ae1e923..9049b71997 100644 --- a/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs +++ b/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs @@ -150,7 +150,7 @@ internal static AllowFilterResult TryAllowFilter( internal static bool TryParseAllowedFilters(string queryOutput, out Allowances allowances) { allowances = null; - if (string.IsNullOrWhiteSpace(queryOutput)) + if (string.IsNullOrWhiteSpace(queryOutput) || !queryOutput.EndsWith("\n", StringComparison.Ordinal)) { return false; } @@ -158,28 +158,37 @@ internal static bool TryParseAllowedFilters(string queryOutput, out Allowances a Dictionary> sections = new Dictionary>(StringComparer.Ordinal); List currentSection = null; bool developerVolume = false; + bool awaitingContinuation = false; + bool attachedSectionStarted = false; foreach (string rawLine in queryOutput.Split('\n')) { string line = rawLine.Trim(); if (line.Length == 0) { + if (awaitingContinuation) + { + return false; + } + currentSection = null; continue; } if (line == VolumeHeader || line == MachineHeader || line == GroupPolicyHeader || line == AttachedHeader) { - if (sections.ContainsKey(line)) + if (!developerVolume || awaitingContinuation || attachedSectionStarted || sections.ContainsKey(line)) { return false; } currentSection = new List(); sections.Add(line, currentSection); + attachedSectionStarted = line == AttachedHeader; } else if (currentSection != null) { - string filterLine = line.EndsWith(",", StringComparison.Ordinal) ? line.Substring(0, line.Length - 1) : line; + awaitingContinuation = line.EndsWith(",", StringComparison.Ordinal); + string filterLine = awaitingContinuation ? line.Substring(0, line.Length - 1) : line; foreach (string token in filterLine.Split(',')) { string name = token.Trim(); @@ -193,16 +202,26 @@ internal static bool TryParseAllowedFilters(string queryOutput, out Allowances a } else if (line == "This is a trusted developer volume." || line == "This is an untrusted developer volume.") { + if (developerVolume || sections.Count != 0) + { + return false; + } + developerVolume = true; } - else if (line != "Developer volumes are protected by antivirus filter, by group policy." - && line != "Developer volumes are protected by antivirus filter.") + else if (!developerVolume || attachedSectionStarted + || (line != "Developer volumes are protected by antivirus filter, by group policy." + && line != "Developer volumes are protected by antivirus filter.")) { return false; } } - if (!developerVolume || sections.Any(section => section.Key != AttachedHeader && section.Value.Count == 0)) + // fsutil omits an empty volume allowance section. Require the final attached-filter + // section before treating that omission as empty; an early EOF is not an empty list. + // Text parsing cannot detect a missing middle section in otherwise complete output. + if (!developerVolume || !attachedSectionStarted || awaitingContinuation + || sections.Any(section => section.Value.Count == 0)) { return false; } @@ -226,6 +245,10 @@ private static bool TryQueryPolicy( { error = $"The Dev Drive query failed with exit {result.ExitCode}: {result.Output} {result.Errors}".Trim(); } + else if (!string.IsNullOrWhiteSpace(result.Errors)) + { + error = $"The Dev Drive query reported an error: {result.Errors.Trim()}"; + } else if (!TryParseAllowedFilters(result.Output, out allowances)) { error = "The Dev Drive query output was not recognized. No further policy changes were made."; diff --git a/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs b/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs index fc08be388f..11218ed211 100644 --- a/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs +++ b/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs @@ -19,6 +19,7 @@ public class DevDriveFilterPolicyTests "Filters allowed on any developer volume, by group policy:\r\n MsSecFlt\r\n\r\n"; private const string Machine = "Filters allowed on any developer volume:\r\n DfmFlt\r\n\r\n"; private const string VolumeHeader = "Filters allowed on this developer volume:\r\n"; + private const string Attached = "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt, WdFilter\r\n"; [TestCase] public void ParserSeparatesVolumeAllowancesFromInheritedAndAttachedFilters() @@ -35,7 +36,7 @@ public void ParserSeparatesVolumeAllowancesFromInheritedAndAttachedFilters() public void ParserPreservesEveryLineOfVolumeAllowances() { DevDriveFilterPolicy.TryParseAllowedFilters( - Preamble + VolumeHeader + " bindflt,\r\n wcifs, DfmFlt\r\n", + Preamble + VolumeHeader + " bindflt,\r\n wcifs, DfmFlt\r\n" + Attached, out DevDriveFilterPolicy.Allowances parsed).ShouldBeTrue(); parsed.Volume.ShouldMatchInOrder("bindflt", "wcifs", "DfmFlt"); } @@ -50,6 +51,15 @@ public void ParserPreservesEveryLineOfVolumeAllowances() [TestCase(Preamble + VolumeHeader + " DfmFlt\r\n unrecognized continuation text\r\n")] [TestCase(Preamble + VolumeHeader + " DfmFlt\r\n\r\n" + VolumeHeader + " wcifs\r\n")] [TestCase(Preamble + VolumeHeader + " PrjFl\u0442\r\n")] + [TestCase(Preamble)] + [TestCase(Preamble + VolumeHeader + " bindflt\r\n")] + [TestCase(Preamble + VolumeHeader + " bindflt,\r\n" + Attached)] + [TestCase(Preamble + VolumeHeader + " bindflt,\r\n\r\n wcifs\r\n" + Attached)] + [TestCase(Preamble + "\r\nFilters currently attached to this developer volume:\r\n")] + [TestCase(Preamble + "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt")] + [TestCase(Preamble + "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt,\r\n")] + [TestCase(Preamble + Attached + "\r\n" + VolumeHeader + " bindflt\r\n")] + [TestCase(Preamble + Preamble + Attached)] [TestCase("Developer volumes are enabled.\r\n")] [TestCase("This is a trusted developer volume.\r" + VolumeHeader + " DfmFlt\r")] public void ParserRejectsAmbiguousOrUnrecognizedOutput(string output) @@ -58,12 +68,91 @@ public void ParserRejectsAmbiguousOrUnrecognizedOutput(string output) parsed.ShouldBeNull(); } + [TestCase(false)] + [TestCase(true)] + public void ParserRejectsEveryTruncatedPrefixOfCapturedVolumeOutput(bool hasVolumeAllowance) + { + string volume = hasVolumeAllowance ? VolumeHeader + " bindflt\r\n" : string.Empty; + string complete = Preamble + Enterprise + Machine + volume + Attached; + DevDriveFilterPolicy.TryParseAllowedFilters(complete, out DevDriveFilterPolicy.Allowances parsed).ShouldBeTrue(); + if (hasVolumeAllowance) + { + parsed.Volume.ShouldMatchInOrder("bindflt"); + } + else + { + parsed.Volume.ShouldBeEmpty(); + } + + for (int length = 0; length < complete.Length; ++length) + { + bool accepted = DevDriveFilterPolicy.TryParseAllowedFilters(complete.Substring(0, length), out DevDriveFilterPolicy.Allowances _); + Assert.That(accepted, Is.False, $"Accepted output truncated at character {length}."); + } + } + + [TestCase(1)] + [TestCase(2)] + public void AllowFilterNeverWritesAfterAnIncompleteQuery(int incompleteQuery) + { + int calls = 0; + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + command.ShouldEqual(@"devdrv query mock:\volume\"); + ++calls; + return Query(calls == incompleteQuery + ? Preamble + Enterprise + Machine + : Preamble + Enterprise + Machine + VolumeHeader + " bindflt\r\n" + Attached); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.PolicyUnreadable); + calls.ShouldEqual(incompleteQuery); + error.ShouldContain("not recognized"); + } + + [TestCase] + public void AllowFilterDoesNotWriteWhenAQueryReportsAnErrorDespiteSuccessExit() + { + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + command.ShouldEqual(@"devdrv query mock:\volume\"); + return new ProcessResult(Preamble + Enterprise + Machine + Attached, "query warning", 0); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.PolicyUnreadable); + error.ShouldContain("query warning"); + } + + [TestCase] + public void AllowFilterReportsAnUnverifiedWriteWhenTheReadbackReportsAnError() + { + int calls = 0; + string output = Preamble + Enterprise + Machine + VolumeHeader + " bindflt\r\n" + Attached; + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + ++calls; + return calls == 4 + ? new ProcessResult(output, "readback warning", 0) + : Query(output); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Failed); + calls.ShouldEqual(4); + error.ShouldContain("update was attempted", "verification failed", "readback warning"); + } + [TestCase(0, DevDriveFilterPolicy.AllowFilterResult.Added)] [TestCase(5, DevDriveFilterPolicy.AllowFilterResult.RemountRequired)] [TestCase(-1, DevDriveFilterPolicy.AllowFilterResult.RemountRequired)] public void AllowFilterPreservesOnlyVolumeEntriesAndVerifiesBusyWrites(int writeExit, DevDriveFilterPolicy.AllowFilterResult expected) { - string before = Preamble + Enterprise + Machine + VolumeHeader + " bindflt\r\n"; + string before = Preamble + Enterprise + Machine + VolumeHeader + " bindflt\r\n" + Attached; Queue commands = new Queue(new[] { @"devdrv query mock:\volume\", @@ -76,7 +165,7 @@ public void AllowFilterPreservesOnlyVolumeEntriesAndVerifiesBusyWrites(int write Query(before), Query(before), new ProcessResult("Volume is in use.", string.Empty, writeExit), - Query(Preamble + Enterprise + Machine + VolumeHeader + " bindflt,prjflt\r\n"), + Query(Preamble + Enterprise + Machine + VolumeHeader + " bindflt,prjflt\r\n" + Attached), }); MockTracer tracer = new MockTracer(); @@ -98,9 +187,9 @@ public void AllowFilterPreservesOnlyVolumeEntriesAndVerifiesBusyWrites(int write tracer.RelatedWarningEvents.Count.ShouldEqual(writeExit == 0 ? 0 : 1); } - [TestCase(Preamble + Enterprise + "Filters allowed on any developer volume:\r\n PrjFlt,DfmFlt\r\n")] - [TestCase(Preamble + "Filters allowed on any developer volume, by group policy:\r\n PrjFlt\r\n")] - [TestCase(Preamble + VolumeHeader + " prjflt\r\n")] + [TestCase(Preamble + Enterprise + "Filters allowed on any developer volume:\r\n PrjFlt,DfmFlt\r\n" + Attached)] + [TestCase(Preamble + "Filters allowed on any developer volume, by group policy:\r\n PrjFlt\r\n" + Attached)] + [TestCase(Preamble + VolumeHeader + " prjflt\r\n" + Attached)] public void AllowFilterDoesNotWriteWhenAnyApplicableListAlreadyAllowsFilter(string output) { DevDriveFilterPolicy.TryAllowFilter( @@ -120,10 +209,10 @@ public void AllowFilterAddsOnlyPrjFltWhenVolumeListIsAbsent() { Queue results = new Queue(new[] { - Query(Preamble + Enterprise + Machine), - Query(Preamble + Enterprise + Machine), + Query(Preamble + Enterprise + Machine + Attached), + Query(Preamble + Enterprise + Machine + Attached), Query(string.Empty), - Query(Preamble + Enterprise + Machine + VolumeHeader + " PrjFlt\r\n"), + Query(Preamble + Enterprise + Machine + VolumeHeader + " PrjFlt\r\n" + Attached), }); DevDriveFilterPolicy.TryAllowFilter( Root, @@ -151,7 +240,7 @@ public void AllowFilterAbortsWhenThePreWriteRecheckObservesAChange() command => { command.ShouldEqual(@"devdrv query mock:\volume\"); - return Query(++calls == 1 ? Preamble : Preamble + VolumeHeader + " wcifs\r\n"); + return Query(++calls == 1 ? Preamble + Attached : Preamble + VolumeHeader + " wcifs\r\n" + Attached); }, NullTracer.Instance, out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Failed); @@ -178,13 +267,14 @@ public void AllowFilterDoesNotWriteWhenTheInitialQueryFails(int exitCode, string [TestCase(5, "Access denied.", "verification failed")] [TestCase(0, "Unrecognized output.", "verification failed")] - [TestCase(0, Preamble, "does not contain")] + [TestCase(0, Preamble + Enterprise + Machine, "verification failed")] + [TestCase(0, Preamble + Attached, "does not contain")] public void AllowFilterDoesNotReportAnUnverifiedWriteAsSuccess(int verifyExit, string output, string message) { int calls = 0; DevDriveFilterPolicy.TryAllowFilter( Root, - command => ++calls < 4 ? Query(Preamble) : new ProcessResult(output, string.Empty, verifyExit), + command => ++calls < 4 ? Query(Preamble + Attached) : new ProcessResult(output, string.Empty, verifyExit), NullTracer.Instance, out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Failed); calls.ShouldEqual(4); From 00cb56d7fc75a048ef8b268e248a8333f6862249 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Wed, 18 Nov 2026 08:33:18 -0800 Subject: [PATCH 4/6] fix: address Dev Drive parser and manual recovery feedback Accept the attached-filter list at EOF without a final newline. Recognize the explicit empty-attached-list message and the antivirus-protection-disabled status line. Keep the final-section and unfinished-continuation guards for allowance lists. Share the manual remedy between the service and virtualization failure paths. Name the target volume, preserve its existing entries, and show setFiltersAllowed /volume without /f. Add regression tests for the producer output forms and the shared manual remedy on disabled and failed-policy requests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../DevDriveFilterPolicy.cs | 26 ++++++-- .../ProjFsAttachRemedy.cs | 50 ++++++++++++++++ .../WindowsFileSystemVirtualizer.cs | 43 +------------ .../Handlers/DevDriveFilterRecovery.cs | 10 +--- .../Service/DevDriveFilterRecoveryTests.cs | 8 +++ .../Platform/DevDriveFilterPolicyTests.cs | 60 +++++++++++++++++-- .../Virtualization/ProjFsAttachRemedyTests.cs | 31 +++++++--- 7 files changed, 163 insertions(+), 65 deletions(-) create mode 100644 GVFS/GVFS.Platform.Windows/ProjFsAttachRemedy.cs diff --git a/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs b/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs index 9049b71997..88ac2b749d 100644 --- a/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs +++ b/GVFS/GVFS.Platform.Windows/DevDriveFilterPolicy.cs @@ -18,6 +18,7 @@ public static class DevDriveFilterPolicy private const string MachineHeader = "Filters allowed on any developer volume:"; private const string GroupPolicyHeader = "Filters allowed on any developer volume, by group policy:"; private const string AttachedHeader = "Filters currently attached to this developer volume:"; + private const string NoAttachedFilters = "No filters are currently attached to this developer volume."; private static readonly Regex FilterNamePattern = new Regex(@"\A[A-Za-z0-9._-]+\z", RegexOptions.Compiled); private static readonly TimeSpan UpdateTimeout = TimeSpan.FromSeconds(30); private static readonly Lock PolicyLock = new Lock(); @@ -150,7 +151,7 @@ internal static AllowFilterResult TryAllowFilter( internal static bool TryParseAllowedFilters(string queryOutput, out Allowances allowances) { allowances = null; - if (string.IsNullOrWhiteSpace(queryOutput) || !queryOutput.EndsWith("\n", StringComparison.Ordinal)) + if (string.IsNullOrWhiteSpace(queryOutput)) { return false; } @@ -160,6 +161,7 @@ internal static bool TryParseAllowedFilters(string queryOutput, out Allowances a bool developerVolume = false; bool awaitingContinuation = false; bool attachedSectionStarted = false; + bool emptyAttachedList = false; foreach (string rawLine in queryOutput.Split('\n')) { string line = rawLine.Trim(); @@ -174,7 +176,19 @@ internal static bool TryParseAllowedFilters(string queryOutput, out Allowances a continue; } - if (line == VolumeHeader || line == MachineHeader || line == GroupPolicyHeader || line == AttachedHeader) + if (line == NoAttachedFilters) + { + if (!developerVolume || awaitingContinuation || attachedSectionStarted) + { + return false; + } + + sections.Add(AttachedHeader, new List()); + attachedSectionStarted = true; + emptyAttachedList = true; + currentSection = null; + } + else if (line == VolumeHeader || line == MachineHeader || line == GroupPolicyHeader || line == AttachedHeader) { if (!developerVolume || awaitingContinuation || attachedSectionStarted || sections.ContainsKey(line)) { @@ -211,7 +225,8 @@ internal static bool TryParseAllowedFilters(string queryOutput, out Allowances a } else if (!developerVolume || attachedSectionStarted || (line != "Developer volumes are protected by antivirus filter, by group policy." - && line != "Developer volumes are protected by antivirus filter.")) + && line != "Developer volumes are protected by antivirus filter." + && line != "Developer volumes may not be protected by antivirus filter.")) { return false; } @@ -220,8 +235,11 @@ internal static bool TryParseAllowedFilters(string queryOutput, out Allowances a // fsutil omits an empty volume allowance section. Require the final attached-filter // section before treating that omission as empty; an early EOF is not an empty list. // Text parsing cannot detect a missing middle section in otherwise complete output. + // The attached-filter printer can end at EOF without a newline. Only the explicit + // no-filters message establishes an empty attached list. if (!developerVolume || !attachedSectionStarted || awaitingContinuation - || sections.Any(section => section.Value.Count == 0)) + || sections.Any(section => section.Value.Count == 0 + && (section.Key != AttachedHeader || !emptyAttachedList))) { return false; } diff --git a/GVFS/GVFS.Platform.Windows/ProjFsAttachRemedy.cs b/GVFS/GVFS.Platform.Windows/ProjFsAttachRemedy.cs new file mode 100644 index 0000000000..226c6f2137 --- /dev/null +++ b/GVFS/GVFS.Platform.Windows/ProjFsAttachRemedy.cs @@ -0,0 +1,50 @@ +using GVFS.Common; +using System; +using System.IO; + +namespace GVFS.Platform.Windows +{ + public static class ProjFsAttachRemedy + { + public static string BuildForVolume(string volumeRoot) + { + string volume = string.IsNullOrEmpty(volumeRoot) ? "" : volumeRoot; + if (volume.Length == 3 && volume[1] == ':' && volume[2] == '\\') + { + volume = volume.Substring(0, 2); + } + + string argument = CommandLineEscaping.EscapeArgument(volume); + return $"If {volume} is a Dev Drive, inspect its saved filter allowances from an elevated command prompt:" + + Environment.NewLine + + $" fsutil devdrv query {argument}" + + Environment.NewLine + + "If PrjFlt is already allowed, close applications that use the volume and remount it, or restart the computer." + + Environment.NewLine + + "Otherwise, retain every entry under 'Filters allowed on this developer volume' and add PrjFlt:" + + Environment.NewLine + + $" fsutil devdrv setFiltersAllowed /volume {argument} \",PrjFlt\"" + + Environment.NewLine + + "Replace the placeholder with those volume entries. If that section is absent, use \"PrjFlt\" as the list." + + Environment.NewLine + + "setFiltersAllowed replaces the volume list, so keep its existing entries. Do not omit /volume or add /f." + + Environment.NewLine + + "After the update, close applications that use the volume and remount it, or restart the computer. Retry gvfs mount."; + } + + internal static string BuildForEnlistment(string enlistmentRoot) + { + string volume; + try + { + volume = Path.GetPathRoot(enlistmentRoot); + } + catch (ArgumentException) + { + volume = null; + } + + return BuildForVolume(volume); + } + } +} diff --git a/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs b/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs index b4f0ee592a..2782a687c3 100644 --- a/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs +++ b/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs @@ -943,7 +943,7 @@ public override bool TryStart(out string error) if ((int)result == HResultExtensions.CantAttachToDevVolume) { - error += ". " + BuildProjFsAttachRemedy(this.Context.Enlistment.WorkingDirectoryRoot); + error += ". " + ProjFsAttachRemedy.BuildForEnlistment(this.Context.Enlistment.WorkingDirectoryRoot); } return false; @@ -957,47 +957,6 @@ protected override void OnPossibleTombstoneFolderCreated(string relativePath) this.FileSystemCallbacks.OnPossibleTombstoneFolderCreated(relativePath); } - /// - /// Builds the user-facing remedy for ERROR_CANT_ATTACH_TO_DEV_VOLUME, which a Dev - /// Drive returns when PrjFlt is not on its allowed-filter list. - /// - /// - /// "fsutil devdrv setFiltersAllowed" REPLACES the allowed list, and without - /// /volume it replaces the list for every developer volume on the machine. So the - /// message must tell the user to read the current list first and include it, or - /// following this advice would drop filters the machine already requires (an - /// anti-malware filter, for example). - /// - internal static string BuildProjFsAttachRemedy(string enlistmentRoot) - { - string volume; - try - { - volume = Path.GetPathRoot(enlistmentRoot)?.TrimEnd(Path.DirectorySeparatorChar); - } - catch (ArgumentException) - { - volume = null; - } - - if (string.IsNullOrEmpty(volume)) - { - volume = ""; - } - - return "The ProjFS filter (PrjFlt) cannot attach to this volume. " - + $"If {volume} is a Dev Drive, PrjFlt must be on its allowed-filter list. " - + "From an elevated command prompt, list the filters that are already allowed:" - + Environment.NewLine - + $" fsutil devdrv query {volume}" - + Environment.NewLine - + "then set the list again with PrjFlt added to it:" - + Environment.NewLine - + $" fsutil devdrv setFiltersAllowed /f /volume {volume} \",PrjFlt\"" - + Environment.NewLine - + "setFiltersAllowed replaces the list, so keep the existing entries"; - } - private static void StreamCopyBlockTo(Stream input, Stream destination, long numBytes, byte[] buffer) { int read; diff --git a/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs b/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs index c6660dad3a..f848fed8db 100644 --- a/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs +++ b/GVFS/GVFS.Service/Handlers/DevDriveFilterRecovery.cs @@ -23,7 +23,7 @@ internal static bool TryRecover( { metadata.Add("Outcome", "Disabled"); metadata.Add("DisabledReason", reason); - error = $"The mounted volume rejected PrjFlt. {reason} {GetManualInstructions(volumeRoot)}"; + error = $"The mounted volume rejected PrjFlt. {reason} {ProjFsAttachRemedy.BuildForVolume(volumeRoot)}"; return false; } @@ -35,7 +35,7 @@ internal static bool TryRecover( { metadata.Add("Outcome", "PolicyFailed"); metadata.Add("PolicyError", policyError); - error = $"The mounted volume rejected PrjFlt. {policyError} {GetManualInstructions(volumeRoot)}"; + error = $"The mounted volume rejected PrjFlt. {policyError} {ProjFsAttachRemedy.BuildForVolume(volumeRoot)}"; return false; } @@ -65,11 +65,5 @@ internal static bool TryRecover( tracer.RelatedEvent(EventLevel.Informational, "DevDriveFilterRecovery_Summary", metadata, Keywords.Telemetry); } } - - private static string GetManualInstructions(string volumeRoot) - { - return $"From an elevated command prompt, run 'fsutil devdrv query {CommandLineEscaping.EscapeArgument(volumeRoot)}' to inspect the saved allowances. " - + "After any required update, close applications that use the volume and remount it, or restart the computer."; - } } } diff --git a/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs b/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs index 62e3033ff1..7ac5041d93 100644 --- a/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs +++ b/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs @@ -21,6 +21,12 @@ public void DisabledGateDoesNotQueryOrWritePolicy() () => throw new InvalidOperationException("Attach must not run."), out string error).ShouldBeFalse(); error.ShouldContain("operator veto"); + error.ShouldContain( + "fsutil devdrv query mock:\\volume\\", + "setFiltersAllowed /volume mock:\\volume\\", + "replaces the volume list", + "keep its existing entries"); + error.ShouldNotContain(false, "setFiltersAllowed /f"); error.ShouldNotContain(false, "not on that list"); } @@ -76,6 +82,8 @@ public void PolicyFailuresDoNotRetryAttachmentOrInventAnAbsentFilter(DevDriveFil out string error).ShouldBeFalse(); error.ShouldContain("query or write error"); error.ShouldContain("fsutil devdrv query"); + error.ShouldContain("setFiltersAllowed /volume mock:\\volume\\", "keep its existing entries"); + error.ShouldNotContain(false, "setFiltersAllowed /f"); error.ShouldNotContain(false, "not on that list"); } diff --git a/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs b/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs index 11218ed211..82ed6357d0 100644 --- a/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs +++ b/GVFS/GVFS.UnitTests/Windows/Platform/DevDriveFilterPolicyTests.cs @@ -19,7 +19,8 @@ public class DevDriveFilterPolicyTests "Filters allowed on any developer volume, by group policy:\r\n MsSecFlt\r\n\r\n"; private const string Machine = "Filters allowed on any developer volume:\r\n DfmFlt\r\n\r\n"; private const string VolumeHeader = "Filters allowed on this developer volume:\r\n"; - private const string Attached = "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt, WdFilter\r\n"; + private const string Attached = "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt, WdFilter"; + private const string NoAttached = "\r\nNo filters are currently attached to this developer volume.\r\n"; [TestCase] public void ParserSeparatesVolumeAllowancesFromInheritedAndAttachedFilters() @@ -56,10 +57,13 @@ public void ParserPreservesEveryLineOfVolumeAllowances() [TestCase(Preamble + VolumeHeader + " bindflt,\r\n" + Attached)] [TestCase(Preamble + VolumeHeader + " bindflt,\r\n\r\n wcifs\r\n" + Attached)] [TestCase(Preamble + "\r\nFilters currently attached to this developer volume:\r\n")] - [TestCase(Preamble + "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt")] [TestCase(Preamble + "\r\nFilters currently attached to this developer volume:\r\n MsSecFlt,\r\n")] [TestCase(Preamble + Attached + "\r\n" + VolumeHeader + " bindflt\r\n")] [TestCase(Preamble + Preamble + Attached)] + [TestCase(Preamble + NoAttached + NoAttached)] + [TestCase(Preamble + Attached + "\r\n" + NoAttached)] + [TestCase(Preamble + NoAttached + VolumeHeader + " bindflt\r\n")] + [TestCase(Preamble + VolumeHeader + " bindflt,\r\n" + NoAttached)] [TestCase("Developer volumes are enabled.\r\n")] [TestCase("This is a trusted developer volume.\r" + VolumeHeader + " DfmFlt\r")] public void ParserRejectsAmbiguousOrUnrecognizedOutput(string output) @@ -70,7 +74,7 @@ public void ParserRejectsAmbiguousOrUnrecognizedOutput(string output) [TestCase(false)] [TestCase(true)] - public void ParserRejectsEveryTruncatedPrefixOfCapturedVolumeOutput(bool hasVolumeAllowance) + public void ParserRejectsIncompleteAllowanceSectionsBeforeTheAttachedList(bool hasVolumeAllowance) { string volume = hasVolumeAllowance ? VolumeHeader + " bindflt\r\n" : string.Empty; string complete = Preamble + Enterprise + Machine + volume + Attached; @@ -84,13 +88,61 @@ public void ParserRejectsEveryTruncatedPrefixOfCapturedVolumeOutput(bool hasVolu parsed.Volume.ShouldBeEmpty(); } - for (int length = 0; length < complete.Length; ++length) + int attachedNames = complete.IndexOf(" MsSecFlt, WdFilter", System.StringComparison.Ordinal); + for (int length = 0; length <= attachedNames; ++length) { bool accepted = DevDriveFilterPolicy.TryParseAllowedFilters(complete.Substring(0, length), out DevDriveFilterPolicy.Allowances _); Assert.That(accepted, Is.False, $"Accepted output truncated at character {length}."); } } + [TestCase(false, false)] + [TestCase(false, true)] + [TestCase(true, false)] + [TestCase(true, true)] + public void ParserAcceptsRealAttachedOutputWithoutAFinalNewline(bool noAttachedFilters, bool disallowAntivirus) + { + string status = disallowAntivirus ? "Developer volumes may not be protected by antivirus filter.\r\n\r\n" : Enterprise; + string output = Preamble + status + Machine + VolumeHeader + " bindflt\r\n" + + (noAttachedFilters ? NoAttached : Attached); + DevDriveFilterPolicy.TryParseAllowedFilters(output, out DevDriveFilterPolicy.Allowances parsed).ShouldBeTrue(); + parsed.Volume.ShouldMatchInOrder("bindflt"); + parsed.Inherited.Contains("DfmFlt").ShouldBeTrue(); + parsed.AllowsProjFS.ShouldBeFalse(); + } + + [TestCase(false)] + [TestCase(true)] + public void AllowFilterReachesTheWriteWithRealTerminalOutput(bool noAttachedFilters) + { + string ending = noAttachedFilters ? NoAttached : Attached; + Queue results = new Queue(new[] + { + Query(Preamble + Machine + VolumeHeader + " bindflt\r\n" + ending), + Query(Preamble + Machine + VolumeHeader + " bindflt\r\n" + ending), + Query(string.Empty), + Query(Preamble + Machine + VolumeHeader + " bindflt, PrjFlt\r\n" + ending), + }); + bool wrote = false; + DevDriveFilterPolicy.TryAllowFilter( + Root, + command => + { + if (results.Count == 2) + { + command.ShouldEqual("devdrv setfiltersallowed /volume mock:\\volume\\ \"bindflt,PrjFlt\""); + wrote = true; + } + + return results.Dequeue(); + }, + NullTracer.Instance, + out string error).ShouldEqual(DevDriveFilterPolicy.AllowFilterResult.Added); + wrote.ShouldBeTrue(); + results.Count.ShouldEqual(0); + error.ShouldBeNull(); + } + [TestCase(1)] [TestCase(2)] public void AllowFilterNeverWritesAfterAnIncompleteQuery(int incompleteQuery) diff --git a/GVFS/GVFS.UnitTests/Windows/Virtualization/ProjFsAttachRemedyTests.cs b/GVFS/GVFS.UnitTests/Windows/Virtualization/ProjFsAttachRemedyTests.cs index 43f7078b8a..263da2dc01 100644 --- a/GVFS/GVFS.UnitTests/Windows/Virtualization/ProjFsAttachRemedyTests.cs +++ b/GVFS/GVFS.UnitTests/Windows/Virtualization/ProjFsAttachRemedyTests.cs @@ -11,10 +11,10 @@ public class ProjFsAttachRemedyTests public void NamesTheVolumeTheEnlistmentIsOn() { // Only the drive root is read from the path. Nothing touches the file system. - string remedy = WindowsFileSystemVirtualizer.BuildProjFsAttachRemedy("X:\\mock\\enlistment"); + string remedy = ProjFsAttachRemedy.BuildForEnlistment("X:\\mock\\enlistment"); remedy.ShouldContain("fsutil devdrv query X:"); - remedy.ShouldContain("setFiltersAllowed /f /volume X:"); + remedy.ShouldContain("setFiltersAllowed /volume X:"); remedy.ShouldContain("If X: is a Dev Drive"); } @@ -23,11 +23,11 @@ public void TellsTheUserToKeepTheFiltersThatAreAlreadyAllowed() { // setFiltersAllowed replaces the list, so advising only "PrjFlt" would drop // filters the machine already requires. - string remedy = WindowsFileSystemVirtualizer.BuildProjFsAttachRemedy("X:\\mock\\enlistment"); + string remedy = ProjFsAttachRemedy.BuildForEnlistment("X:\\mock\\enlistment"); remedy.ShouldContain("PrjFlt"); - remedy.ShouldContain(",PrjFlt"); - remedy.ShouldContain("replaces the list"); + remedy.ShouldContain(",PrjFlt"); + remedy.ShouldContain("replaces the volume list"); } [TestCase] @@ -35,11 +35,28 @@ public void FallsBackToAPlaceholderWhenThereIsNoVolumeToName() { foreach (string enlistmentRoot in new string[] { null, string.Empty }) { - string remedy = WindowsFileSystemVirtualizer.BuildProjFsAttachRemedy(enlistmentRoot); + string remedy = ProjFsAttachRemedy.BuildForEnlistment(enlistmentRoot); remedy.ShouldContain("fsutil devdrv query "); - remedy.ShouldContain("setFiltersAllowed /f /volume "); + remedy.ShouldContain("setFiltersAllowed /volume "); } } + + [TestCase] + public void VolumeRemedyDoesNotForceDismountAndExplainsTheSavedVolumeList() + { + string remedy = ProjFsAttachRemedy.BuildForVolume(@"X:\"); + remedy.ShouldContain("Filters allowed on this developer volume", "keep its existing entries"); + remedy.ShouldContain("If that section is absent, use \"PrjFlt\"", "remount it, or restart the computer"); + remedy.ShouldNotContain(false, "setFiltersAllowed /f"); + } + + [TestCase] + public void VolumeRemedyPreservesAndQuotesAFolderMountPoint() + { + string remedy = ProjFsAttachRemedy.BuildForVolume("X:\\mock volume\\"); + remedy.ShouldContain("fsutil devdrv query \"X:\\mock volume\\\\\""); + remedy.ShouldContain("setFiltersAllowed /volume \"X:\\mock volume\\\\\""); + } } } From b48706878228338c237b1c31a81ff7260aff4346 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Thu, 19 Nov 2026 11:06:15 -0800 Subject: [PATCH 5/6] Default the Dev Drive filter update to off Require an explicit true value before the service updates a Dev Drive filter allowance. Preserve the client value as nullable so an unset key does not override an explicit system opt-in. A false value at either side still vetoes the update, and a client read failure fails closed. Keep ReFS attachment verification independent of the flag. Add unit tests for opt-in, both vetoes, read failures, and old-client requests through the recovery boundary. Signed-off-by: Tyrie Vella Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- GVFS/GVFS.Common/DevDriveFilterConfig.cs | 48 +++++++++++--- GVFS/GVFS.Common/GVFSConstants.cs | 4 +- .../NamedPipes/NamedPipeMessages.cs | 6 +- .../Common/DevDriveFilterConfigTests.cs | 62 ++++++++++++++++++- .../Service/DevDriveFilterRecoveryTests.cs | 47 ++++++++++++++ GVFS/GVFS/CommandLine/GVFSVerb.cs | 7 +-- 6 files changed, 154 insertions(+), 20 deletions(-) diff --git a/GVFS/GVFS.Common/DevDriveFilterConfig.cs b/GVFS/GVFS.Common/DevDriveFilterConfig.cs index 138358fd0b..ec2c8f9b58 100644 --- a/GVFS/GVFS.Common/DevDriveFilterConfig.cs +++ b/GVFS/GVFS.Common/DevDriveFilterConfig.cs @@ -8,6 +8,18 @@ public static class DevDriveFilterConfig { public static readonly TimeSpan ReadTimeout = TimeSpan.FromSeconds(5); + public static bool? ReadClientValue( + LibGit2Repo.TryReadConfigBoolWithGit readConfig, + ITracer tracer) + { + if (!TryReadValue(readConfig, "enlistment", tracer, out bool? value, out string _)) + { + return false; + } + + return value; + } + public static bool IsEnabled( LibGit2Repo.TryReadConfigBoolWithGit readConfig, bool? clientValue, @@ -16,23 +28,45 @@ public static bool IsEnabled( out string disabledReason) { disabledReason = null; - bool? value = null; - string error = "Git is unavailable."; - if (readConfig == null - || !readConfig(GVFSConstants.GitConfig.AutoAllowDevDriveFilter, out value, out error)) + if (!TryReadValue(readConfig, source, tracer, out bool? value, out disabledReason)) { - disabledReason = $"Automatic filter allowance changes are disabled because the {source} configuration read failed. {error}"; - tracer.RelatedWarning(disabledReason); return false; } - if (!(value ?? GVFSConstants.GitConfig.AutoAllowDevDriveFilterDefault) || clientValue == false) + if (value == false || clientValue == false) { string disabledSource = value == false ? source : "enlistment"; disabledReason = $"Automatic filter allowance changes are disabled by {GVFSConstants.GitConfig.AutoAllowDevDriveFilter} in the {disabledSource} configuration."; return false; } + if ((value ?? GVFSConstants.GitConfig.AutoAllowDevDriveFilterDefault) + || clientValue == true) + { + return true; + } + + disabledReason = $"Automatic filter allowance changes are not enabled. Set {GVFSConstants.GitConfig.AutoAllowDevDriveFilter} to true to opt in."; + return false; + } + + private static bool TryReadValue( + LibGit2Repo.TryReadConfigBoolWithGit readConfig, + string source, + ITracer tracer, + out bool? value, + out string error) + { + value = null; + error = "Git is unavailable."; + if (readConfig == null + || !readConfig(GVFSConstants.GitConfig.AutoAllowDevDriveFilter, out value, out error)) + { + error = $"Automatic filter allowance changes are disabled because the {source} configuration read failed. {error}"; + tracer.RelatedWarning(error); + return false; + } + return true; } } diff --git a/GVFS/GVFS.Common/GVFSConstants.cs b/GVFS/GVFS.Common/GVFSConstants.cs index 7939f17917..2bb57922ea 100644 --- a/GVFS/GVFS.Common/GVFSConstants.cs +++ b/GVFS/GVFS.Common/GVFSConstants.cs @@ -91,12 +91,12 @@ public static class GitConfig public const bool PrefetchOffloadDefault = false; /* Permits GVFS.Service to allow PrjFlt on the enlistment's Dev Drive after attachment - * is rejected. Default on to repair that failure without a separate elevated command. + * is rejected. Default off: an explicit true value opts in to the policy update. * The service reads its Git installation's system config (including includes) for each * request. Either that value or the client's resolved value can veto a write. * Disabling the flag does not remove a persisted allowance. */ public const string AutoAllowDevDriveFilter = GVFSPrefix + "auto-allow-devdrive-filter"; - public const bool AutoAllowDevDriveFilterDefault = true; + public const bool AutoAllowDevDriveFilterDefault = false; } public static class LocalGVFSConfig diff --git a/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs index 79d0610b7a..6408f7837d 100644 --- a/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs +++ b/GVFS/GVFS.Common/NamedPipes/NamedPipeMessages.cs @@ -484,12 +484,12 @@ public class EnableAndAttachProjFSRequest /// /// The value of gvfs.auto-allow-devdrive-filter as resolved by the client against the - /// enlistment (system, global, and local git config). Null when the client did not - /// resolve a value, including requests from a client that predates this field. + /// enlistment (system, global, and local git config). Null when the value is unset + /// or the client predates this field. A read failure is sent as false. /// /// /// The service also reads the system config of its selected Git installation. - /// A false system value vetoes the write regardless of this client value. + /// An explicit true value opts in. A false value at either side vetoes the write. /// See GVFSConstants.GitConfig.AutoAllowDevDriveFilter for the configuration contract. /// public bool? AutoAllowDevDriveFilter { get; set; } diff --git a/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs b/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs index 3020c75e80..b9ab6c6cea 100644 --- a/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs +++ b/GVFS/GVFS.UnitTests/Common/DevDriveFilterConfigTests.cs @@ -13,8 +13,9 @@ namespace GVFS.UnitTests.Common [TestFixture] public class DevDriveFilterConfigTests { - [TestCase(null, null, true)] + [TestCase(null, null, false)] [TestCase(true, null, true)] + [TestCase(null, true, true)] [TestCase(true, true, true)] [TestCase(false, true, false)] [TestCase(true, false, false)] @@ -40,10 +41,67 @@ public void EitherVetoPreventsAnUpdateAndUnsetKeepsTheDefault(bool? system, bool } else { - reason.ShouldContain(system == false ? "system configuration" : "enlistment configuration"); + if (system == null && client == null) + { + reason.ShouldContain("not enabled", "Set", "true"); + } + else + { + reason.ShouldContain(system == false ? "system configuration" : "enlistment configuration"); + } } } + [TestCase(null)] + [TestCase(false)] + [TestCase(true)] + public void ClientPreservesUnsetAndExplicitConfigurationValues(bool? configured) + { + DevDriveFilterConfig.ReadClientValue( + (string key, out bool? value, out string error) => + { + key.ShouldEqual("gvfs.auto-allow-devdrive-filter"); + value = configured; + error = null; + return true; + }, + new MockTracer()).ShouldEqual(configured); + } + + [TestCase] + public void ClientReadFailureVetoesEvenAnExplicitSystemOptIn() + { + MockTracer tracer = new MockTracer(); + bool? client = DevDriveFilterConfig.ReadClientValue( + (string key, out bool? value, out string error) => + { + value = null; + error = "read denied"; + return false; + }, + tracer); + client.ShouldEqual(false); + tracer.RelatedWarningEvents.Count.ShouldEqual(1); + DevDriveFilterConfig.IsEnabled( + (string key, out bool? value, out string error) => + { + value = true; + error = null; + return true; + }, + client, + "system", + tracer, + out string reason).ShouldBeFalse(); + reason.ShouldContain("enlistment configuration"); + } + + [TestCase] + public void MissingClientReaderVetoesAutomaticUpdates() + { + DevDriveFilterConfig.ReadClientValue(null, new MockTracer()).ShouldEqual(false); + } + [TestCase("system")] [TestCase("enlistment")] public void FailedReadsNeverSelectTheTrueDefault(string source) diff --git a/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs b/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs index 7ac5041d93..61811a783e 100644 --- a/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs +++ b/GVFS/GVFS.UnitTests/Service/DevDriveFilterRecoveryTests.cs @@ -1,3 +1,5 @@ +using GVFS.Common; +using GVFS.Common.NamedPipes; using GVFS.Platform.Windows; using GVFS.Service.Handlers; using GVFS.Tests.Should; @@ -10,6 +12,51 @@ namespace GVFS.UnitTests.Service [TestFixture] public class DevDriveFilterRecoveryTests { + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\"}", null, false)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":null}", null, false)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":true}", null, true)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\"}", true, true)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":false}", true, false)] + [TestCase("{\"EnlistmentRoot\":\"mock:\\\\src\",\"AutoAllowDevDriveFilter\":true}", false, false)] + public void WireAndSystemGateControlWhetherPolicyUpdateRuns(string json, bool? system, bool expectedWrite) + { + NamedPipeMessages.EnableAndAttachProjFSRequest request = NamedPipeMessages.EnableAndAttachProjFSRequest.FromMessage( + new NamedPipeMessages.Message("EnableAndAttachProjFSRequest", json)); + int policyCalls = 0; + bool result = DevDriveFilterRecovery.TryRecover( + @"mock:\volume\", + new MockTracer(), + () => + { + bool enabled = DevDriveFilterConfig.IsEnabled( + (string key, out bool? value, out string readError) => + { + value = system; + readError = null; + return true; + }, + request.AutoAllowDevDriveFilter, + "system", + new MockTracer(), + out string reason); + return (enabled, reason); + }, + () => + { + ++policyCalls; + return (DevDriveFilterPolicy.AllowFilterResult.Added, null); + }, + () => (true, false, null), + out string error); + + result.ShouldEqual(expectedWrite); + policyCalls.ShouldEqual(expectedWrite ? 1 : 0); + if (!expectedWrite) + { + error.ShouldContain("The mounted volume rejected PrjFlt"); + } + } + [TestCase] public void DisabledGateDoesNotQueryOrWritePolicy() { diff --git a/GVFS/GVFS/CommandLine/GVFSVerb.cs b/GVFS/GVFS/CommandLine/GVFSVerb.cs index 88d7df3712..e5abdae659 100644 --- a/GVFS/GVFS/CommandLine/GVFSVerb.cs +++ b/GVFS/GVFS/CommandLine/GVFSVerb.cs @@ -588,12 +588,7 @@ protected bool TryEnableAndAttachPrjFltThroughService(string enlistmentRoot, out ? null : (string key, out bool? value, out string readError) => git.TryGetBoolFromConfig(key, GitConfigBoolScope.Merged, DevDriveFilterConfig.ReadTimeout, tracer, out value, out readError); - request.AutoAllowDevDriveFilter = DevDriveFilterConfig.IsEnabled( - reader, - clientValue: null, - source: "enlistment", - tracer, - out string _); + request.AutoAllowDevDriveFilter = DevDriveFilterConfig.ReadClientValue(reader, tracer); } using (NamedPipeClient client = new NamedPipeClient(this.ServicePipeName)) From 1b5a4152ceb832ddefced7f5a963b7773844bd74 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Thu, 19 Nov 2026 11:58:30 -0800 Subject: [PATCH 6/6] Preserve bounded Git process cleanup after rebase Wait for an active Git configuration process to exit after the shared reader terminates it. Keep the upstream single-owner termination logic. Report a process error if the cleanup wait expires. Add tests that assert exit observation and prevent a second termination. Signed-off-by: Tyrie Vella Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../GVFS.Common/Git/GitProcessConfigReader.cs | 21 ++++++++- .../Common/Git/GitProcessConfigReaderTests.cs | 45 +++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs b/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs index 94175a5572..cd90e9525d 100644 --- a/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs +++ b/GVFS/GVFS.Common/Git/GitProcessConfigReader.cs @@ -145,7 +145,8 @@ internal static GitProcess.Result ReadRaw( ReadResultAsync, () => process.HasExited, () => process.Kill(entireProcessTree: true), - cancellation); + cancellation, + () => process.WaitForExit(5000)); async Task ReadResultAsync() { @@ -176,7 +177,8 @@ internal static GitProcess.Result ReadRaw( Func> read, Func hasExited, Action killTree, - CancellationToken cancellation) + CancellationToken cancellation, + Func waitForExit = null) { TaskCompletionSource cancellationKill = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); CancellationTokenRegistration registration = cancellation.Register(() => @@ -229,6 +231,21 @@ internal static GitProcess.Result ReadRaw( } } + if (waitForExit != null) + { + try + { + if (!hasExited() && !waitForExit()) + { + throw new Win32Exception("The Git configuration process did not exit within the cleanup deadline."); + } + } + catch (Exception cleanupFailure) when (failure != null || readFailure != null) + { + failure = failure == null ? cleanupFailure : new AggregateException(failure, cleanupFailure); + } + } + if (failure != null) { if (readFailure != null) diff --git a/GVFS/GVFS.UnitTests/Common/Git/GitProcessConfigReaderTests.cs b/GVFS/GVFS.UnitTests/Common/Git/GitProcessConfigReaderTests.cs index 617f6f2e67..59d6e8eece 100644 --- a/GVFS/GVFS.UnitTests/Common/Git/GitProcessConfigReaderTests.cs +++ b/GVFS/GVFS.UnitTests/Common/Git/GitProcessConfigReaderTests.cs @@ -151,6 +151,51 @@ public void CancellationBeforeRegistrationDoesNotKillTheTreeAgain() Assert.That(killAttempts, Is.EqualTo(1)); } + [Test] + public void CancellationObservesProcessExitWithoutASecondKill() + { + using CancellationTokenSource cancellation = new CancellationTokenSource(); + TaskCompletionSource read = new TaskCompletionSource(); + int killAttempts = 0; + int waitAttempts = 0; + Task result = GitProcessConfigReader.ReadWithProcessCleanupAsync( + () => read.Task, + () => false, + () => ++killAttempts, + cancellation.Token, + () => + { + ++waitAttempts; + return true; + }); + + cancellation.Cancel(); + read.SetCanceled(cancellation.Token); + + Assert.CatchAsync(async () => await result.WaitAsync(TimeSpan.FromSeconds(5))); + Assert.That(killAttempts, Is.EqualTo(1)); + Assert.That(waitAttempts, Is.EqualTo(1)); + } + + [Test] + public void FailedExitObservationReportsAProcessFailure() + { + using CancellationTokenSource cancellation = new CancellationTokenSource(); + TaskCompletionSource read = new TaskCompletionSource(); + Task result = GitProcessConfigReader.ReadWithProcessCleanupAsync( + () => read.Task, + () => false, + () => { }, + cancellation.Token, + () => false); + + cancellation.Cancel(); + read.SetCanceled(cancellation.Token); + + Win32Exception failure = Assert.ThrowsAsync(async () => await result.WaitAsync(TimeSpan.FromSeconds(5))); + Assert.That(failure.Message, Does.Contain("did not exit")); + } + [TestCase(false)] [TestCase(true)] public void CancellationReportsTheOriginalKillFailure(bool isTreeFailure)