From ad4e91caeba83619c6b3d6ec5877cf94b1da1b1a Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:05:52 -0800 Subject: [PATCH 1/7] Fix PowerShell cmdlets running winget.exe from the current directory --- .../1.31/powershell-winget-path-resolution.md | 5 ++ .../Helpers/WingetCLIWrapper.cs | 56 +++++++++++++- .../WingetCLIWrapperTests.cs | 76 +++++++++++++++++++ 3 files changed, 135 insertions(+), 2 deletions(-) create mode 100644 doc/release-notes/1.31/powershell-winget-path-resolution.md create mode 100644 src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs diff --git a/doc/release-notes/1.31/powershell-winget-path-resolution.md b/doc/release-notes/1.31/powershell-winget-path-resolution.md new file mode 100644 index 0000000000..9a88f6e022 --- /dev/null +++ b/doc/release-notes/1.31/powershell-winget-path-resolution.md @@ -0,0 +1,5 @@ +## Bug Fixes + +### Minor Bug Fixes + +* Fixed `Assert-WinGetPackageManager` and `Repair-WinGetPackageManager` running a `winget.exe` from the current directory instead of the one found in `PATH`. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs index d9c76a810c..c5743508a0 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs @@ -7,6 +7,7 @@ namespace Microsoft.WinGet.Client.Engine.Helpers { using System; + using System.ComponentModel; using System.Diagnostics; using System.IO; using Microsoft.WinGet.Client.Engine.Common; @@ -18,6 +19,8 @@ namespace Microsoft.WinGet.Client.Engine.Helpers /// internal class WingetCLIWrapper { + private const int ErrorFileNotFound = 2; + /// /// The file name to use in start info. /// @@ -31,7 +34,7 @@ internal class WingetCLIWrapper /// family name directory. /// For test, point to the wingetdev executable. /// - /// Use full path or not. + /// Use the full path, or resolve winget from PATH. public WingetCLIWrapper(bool fullPath = true) { if (Utilities.ExecutingAsSystem) @@ -45,7 +48,9 @@ public WingetCLIWrapper(bool fullPath = true) } else { - this.wingetPath = Constants.WinGetExe; + // Search PATH explicitly because Process.Start would also search the current directory. + this.wingetPath = FindInPath(Environment.GetEnvironmentVariable(Constants.PathEnvVar), Constants.WinGetExe) + ?? throw new Win32Exception(ErrorFileNotFound); } } @@ -63,6 +68,30 @@ public static string WinGetFullPath } } + /// + /// Finds a file in the fully qualified directories of a PATH value, never in the current directory. + /// + /// The PATH value. + /// The file name to find. + /// The full path of the first match, or null if there is none. + internal static string? FindInPath(string? envPath, string fileName) + { + foreach (string directory in (envPath ?? string.Empty).Split(Path.PathSeparator)) + { + // Path.Combine throws on invalid characters in .NET Framework. + if (IsFullyQualified(directory) && directory.IndexOfAny(Path.GetInvalidPathChars()) < 0) + { + string candidate = Path.Combine(directory, fileName); + if (File.Exists(candidate)) + { + return candidate; + } + } + } + + return null; + } + /// /// Runs winget command with parameters. /// @@ -99,5 +128,28 @@ internal WinGetCLICommandResult RunCommand(PowerShellCmdlet pwshCmdlet, WinGetCL throw new WinGetCLITimeoutException(builder.Command, builder.Parameters); } + + // Path.IsPathFullyQualified is not available in .NET Framework. + private static bool IsFullyQualified(string path) + { + if (path.Length < 3) + { + return false; + } + + if (IsDirectorySeparator(path[0])) + { + return IsDirectorySeparator(path[1]); + } + + char drive = path[0]; + bool isDriveLetter = (drive >= 'A' && drive <= 'Z') || (drive >= 'a' && drive <= 'z'); + return isDriveLetter && path[1] == ':' && IsDirectorySeparator(path[2]); + } + + private static bool IsDirectorySeparator(char c) + { + return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar; + } } } diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs new file mode 100644 index 0000000000..0447a873c0 --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs @@ -0,0 +1,76 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.UnitTests +{ + using System; + using System.IO; + using Microsoft.WinGet.Client.Engine.Helpers; + using Xunit; + + /// + /// Tests for . + /// + public class WingetCLIWrapperTests + { + private const string FileName = "winget.exe"; + + /// + /// Tests that the first PATH directory containing the file is returned. + /// + [Fact] + public void FindInPathReturnsFirstMatch() + { + string root = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; + + try + { + string empty = Directory.CreateDirectory(Path.Combine(root, "empty")).FullName; + string first = Directory.CreateDirectory(Path.Combine(root, "first")).FullName; + string second = Directory.CreateDirectory(Path.Combine(root, "second")).FullName; + File.WriteAllText(Path.Combine(first, FileName), string.Empty); + File.WriteAllText(Path.Combine(second, FileName), string.Empty); + + string envPath = string.Join(Path.PathSeparator, empty, first, second); + + Assert.Equal(Path.Combine(first, FileName), WingetCLIWrapper.FindInPath(envPath, FileName)); + } + finally + { + Directory.Delete(root, true); + } + } + + /// + /// Tests that PATH entries that resolve to the current directory are ignored. + /// + [Fact] + public void FindInPathIgnoresCurrentDirectory() + { + string fileName = $"{Guid.NewGuid()}.exe"; + string currentDirectory = Environment.CurrentDirectory; + string plantedFile = Path.Combine(currentDirectory, fileName); + File.WriteAllText(plantedFile, string.Empty); + + try + { + string envPath = string.Join( + Path.PathSeparator, + string.Empty, + ".", + ".\\", + currentDirectory.Substring(0, 2), + currentDirectory.Substring(2)); + + Assert.Null(WingetCLIWrapper.FindInPath(envPath, fileName)); + } + finally + { + File.Delete(plantedFile); + } + } + } +} From c7bad746f5bcd9604252163b61f6e09bb33f04b4 Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:36:15 -0800 Subject: [PATCH 2/7] Ignore relative PATH entries when diagnosing winget failures --- .../Common/WinGetIntegrity.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs index e647db1049..ccf91660d2 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs @@ -103,8 +103,13 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) // ApplicationFailedException then is most likely that the license is not there. try { - var ps = PowerShell.Create(RunspaceMode.CurrentRunspace); - ps.AddCommand("winget").Invoke(); + // Avoid PowerShell command lookup, which also searches relative PATH entries such as '.'. + string? wingetPath = WingetCLIWrapper.FindInPath(Environment.GetEnvironmentVariable(Constants.PathEnvVar), Constants.WinGetExe); + if (wingetPath != null) + { + var ps = PowerShell.Create(RunspaceMode.CurrentRunspace); + ps.AddCommand(wingetPath).Invoke(); + } } catch (ApplicationFailedException e) { From d7f5cc732b952d89d0a1939ae86880c3647e0438 Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:09:06 -0800 Subject: [PATCH 3/7] Resolve winget from the trusted App Installer package --- .../1.31/powershell-winget-path-resolution.md | 2 +- .../Common/WinGetIntegrity.cs | 26 +++++-- .../Helpers/AppxModuleHelper.cs | 41 ++++++++-- .../Helpers/WinGetVersion.cs | 6 +- .../Helpers/WingetCLIWrapper.cs | 65 +--------------- .../AppxModuleHelperTests.cs | 39 ++++++++++ .../WingetCLIWrapperTests.cs | 76 ------------------- 7 files changed, 99 insertions(+), 156 deletions(-) create mode 100644 src/PowerShell/Microsoft.WinGet.UnitTests/AppxModuleHelperTests.cs delete mode 100644 src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs diff --git a/doc/release-notes/1.31/powershell-winget-path-resolution.md b/doc/release-notes/1.31/powershell-winget-path-resolution.md index 9a88f6e022..9f47f756f2 100644 --- a/doc/release-notes/1.31/powershell-winget-path-resolution.md +++ b/doc/release-notes/1.31/powershell-winget-path-resolution.md @@ -2,4 +2,4 @@ ### Minor Bug Fixes -* Fixed `Assert-WinGetPackageManager` and `Repair-WinGetPackageManager` running a `winget.exe` from the current directory instead of the one found in `PATH`. +* Fixed `Assert-WinGetPackageManager` and `Repair-WinGetPackageManager` running a `winget.exe` from the current directory. They now only run `winget.exe` from the installed App Installer package. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs index ccf91660d2..703ea90afa 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs @@ -20,6 +20,8 @@ namespace Microsoft.WinGet.Client.Engine.Common /// internal static class WinGetIntegrity { + private const int ErrorFileNotFound = 2; + /// /// Verifies winget runs correctly. If it doesn't, tries to find the reason why it failed. /// @@ -40,18 +42,19 @@ public static void AssertWinGet(PowerShellCmdlet pwshCmdlet, string expectedVers } WinGetCLICommandResult? versionResult = null; + string? wingetPath = null; try { - // Start by calling winget without its WindowsApp PFN path. - // If it succeeds and the exit code is 0 then we are good. - versionResult = WinGetVersion.RunWinGetVersionFromCLI(pwshCmdlet, false); + // Use the installed package's winget instead of searching CWD or PATH. + wingetPath = GetWinGetPath(pwshCmdlet) ?? throw new Win32Exception(ErrorFileNotFound); + versionResult = WinGetVersion.RunWinGetVersionFromCLI(pwshCmdlet, wingetPath); versionResult.VerifyExitCode(); } catch (Win32Exception e) { pwshCmdlet.Write(StreamType.Verbose, $"'winget.exe' Win32Exception {e.Message}"); - throw new WinGetIntegrityException(GetReason(pwshCmdlet)); + throw new WinGetIntegrityException(GetReason(pwshCmdlet, wingetPath)); } catch (Exception e) when (e is WinGetCLIException || e is WinGetCLITimeoutException) { @@ -90,7 +93,7 @@ public static void AssertWinGet(PowerShellCmdlet pwshCmdlet, string expectedVers } } - private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) + private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet, string? wingetPath) { // Ok, so you are here because calling winget --version failed. Lets try to figure out why. var category = IntegrityCategory.Unknown; @@ -103,8 +106,6 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) // ApplicationFailedException then is most likely that the license is not there. try { - // Avoid PowerShell command lookup, which also searches relative PATH entries such as '.'. - string? wingetPath = WingetCLIWrapper.FindInPath(Environment.GetEnvironmentVariable(Constants.PathEnvVar), Constants.WinGetExe); if (wingetPath != null) { var ps = PowerShell.Create(RunspaceMode.CurrentRunspace); @@ -179,6 +180,17 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) return IntegrityCategory.AppInstallerNotRegistered; } + private static string? GetWinGetPath(PowerShellCmdlet pwshCmdlet) + { +#if USE_PROD_CLSIDS + string? location = new AppxModuleHelper(pwshCmdlet).GetStoreSignedAppInstallerLocation(); + return location is null ? null : Path.Combine(location, Constants.WinGetExe); +#else + // Development packages are not Store signed. + return WingetCLIWrapper.WinGetFullPath; +#endif + } + private static bool IsSupportedOSVersion() { // Windows version has to be equal or newer than 10.0.17763.0 diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs index 3fb91246be..67d0ca45c6 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs @@ -66,6 +66,11 @@ internal class AppxModuleHelper private const string AppxManifest = "AppxManifest.xml"; private const string PackageFullName = "PackageFullName"; private const string Version = "Version"; + private const string InstallLocation = "InstallLocation"; + private const string PublisherId = "PublisherId"; + private const string SignatureKind = "SignatureKind"; + private const string MicrosoftPublisherId = "8wekyb3d8bbwe"; + private const string StoreSignatureKind = "Store"; private const string DependencyArchitectureEnvironmentVariable = "WINGET_PACKAGE_MANAGER_REPAIR_DEPENDENCY_ARCHITECTURES"; @@ -115,13 +120,14 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) } /// - /// Calls Get-AppxPackage Microsoft.DesktopAppInstaller. + /// Gets the Microsoft-published, Store-signed AppInstaller package. /// /// Whether to get for all users. /// Result of Get-AppxPackage. public PSObject? GetAppInstallerObject(bool allUsers = false) { - return this.GetAppxObject(AppInstallerName, allUsers); + return this.GetAppxObjects(AppInstallerName, allUsers) + .FirstOrDefault(p => IsStoreSignedMicrosoftPackage(p.Properties[PublisherId]?.Value, p.Properties[SignatureKind]?.Value)); } /// @@ -130,7 +136,7 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) /// Result of Get-AppxPackage. public PSObject? GetWinGetSourceObject() { - return this.GetAppxObject(WinGetSourceName); + return this.GetAppxObjects(WinGetSourceName).FirstOrDefault(); } /// @@ -155,6 +161,16 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) return result; } + /// + /// Gets the install location of the AppInstaller package, if it is published by Microsoft and signed by the Store. + /// + /// The install location, or null if there is no such package. + public string? GetStoreSignedAppInstallerLocation() + { + string? location = this.GetAppInstallerPropertyValue(InstallLocation); + return string.IsNullOrEmpty(location) ? null : location; + } + /// /// Checks if winget source is installed. /// @@ -245,6 +261,18 @@ public async Task InstallWinGetSourceAsync() await this.DownloadPackageAndAddAsync(WinGetSourceUrl, WinGetSourceMsixName, options: null); } + /// + /// Checks if a package is published by Microsoft and signed by the Store. + /// + /// The PublisherId of the package. + /// The SignatureKind of the package. + /// True if the package is published by Microsoft and signed by the Store. + internal static bool IsStoreSignedMicrosoftPackage(object? publisherId, object? signatureKind) + { + // SignatureKind is an enum, or a string when the Appx module is loaded with -UseWindowsPowerShell. + return publisherId?.ToString() == MicrosoftPublisherId && signatureKind?.ToString() == StoreSignatureKind; + } + /// /// Gets the Xaml dependency package name and release tag based on the provided WinGet release tag. /// @@ -338,7 +366,7 @@ private async Task AddAppInstallerBundleAsync(string releaseTag, bool downgrade, } } - private PSObject? GetAppxObject(string packageName, bool allUsers = false) + private Collection GetAppxObjects(string packageName, bool allUsers = false) { var options = new List(); if (allUsers) @@ -352,8 +380,7 @@ private async Task AddAppInstallerBundleAsync(string releaseTag, bool downgrade, { { Name, packageName }, }, - options) - .FirstOrDefault(); + options); } private async Task InstallDependenciesAsync(string releaseTag) @@ -664,7 +691,7 @@ private async Task InstallUiXamlAsync(string releaseTag) string xamlAssetX86 = string.Format("{0}.x86.appx", xamlPackageName); string xamlAssetArm64 = string.Format("{0}.arm64.appx", xamlPackageName); - var uiXamlObjs = this.GetAppxObject(xamlPackageName); + var uiXamlObjs = this.GetAppxObjects(xamlPackageName).FirstOrDefault(); if (uiXamlObjs is null) { var githubRelease = new GitHubClient(RepositoryOwner.Microsoft, RepositoryName.UiXaml, this.pwshCmdlet); diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs index 90290f453b..28e5d5285f 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs @@ -74,11 +74,11 @@ public WinGetVersion(string version) /// Runs the winget version command. /// /// PowerShell cmdlet. - /// Use full path or not. + /// The full path of winget, or null to use the default. /// The command result. - public static WinGetCLICommandResult RunWinGetVersionFromCLI(PowerShellCmdlet pwshCmdlet, bool fullPath = true) + public static WinGetCLICommandResult RunWinGetVersionFromCLI(PowerShellCmdlet pwshCmdlet, string? wingetPath = null) { - var wingetCliWrapper = new WingetCLIWrapper(fullPath); + var wingetCliWrapper = new WingetCLIWrapper(wingetPath); return wingetCliWrapper.RunCommand(pwshCmdlet, new WinGetCLICommandBuilder().AppendSwitch("--version")); } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs index c5743508a0..6e8b11b3a6 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs @@ -7,7 +7,6 @@ namespace Microsoft.WinGet.Client.Engine.Helpers { using System; - using System.ComponentModel; using System.Diagnostics; using System.IO; using Microsoft.WinGet.Client.Engine.Common; @@ -19,8 +18,6 @@ namespace Microsoft.WinGet.Client.Engine.Helpers /// internal class WingetCLIWrapper { - private const int ErrorFileNotFound = 2; - /// /// The file name to use in start info. /// @@ -34,24 +31,15 @@ internal class WingetCLIWrapper /// family name directory. /// For test, point to the wingetdev executable. /// - /// Use the full path, or resolve winget from PATH. - public WingetCLIWrapper(bool fullPath = true) + /// The full path of winget, or null to use . + public WingetCLIWrapper(string? wingetPath = null) { if (Utilities.ExecutingAsSystem) { throw new NotSupportedException(); } - if (fullPath) - { - this.wingetPath = WinGetFullPath; - } - else - { - // Search PATH explicitly because Process.Start would also search the current directory. - this.wingetPath = FindInPath(Environment.GetEnvironmentVariable(Constants.PathEnvVar), Constants.WinGetExe) - ?? throw new Win32Exception(ErrorFileNotFound); - } + this.wingetPath = wingetPath ?? WinGetFullPath; } /// @@ -68,30 +56,6 @@ public static string WinGetFullPath } } - /// - /// Finds a file in the fully qualified directories of a PATH value, never in the current directory. - /// - /// The PATH value. - /// The file name to find. - /// The full path of the first match, or null if there is none. - internal static string? FindInPath(string? envPath, string fileName) - { - foreach (string directory in (envPath ?? string.Empty).Split(Path.PathSeparator)) - { - // Path.Combine throws on invalid characters in .NET Framework. - if (IsFullyQualified(directory) && directory.IndexOfAny(Path.GetInvalidPathChars()) < 0) - { - string candidate = Path.Combine(directory, fileName); - if (File.Exists(candidate)) - { - return candidate; - } - } - } - - return null; - } - /// /// Runs winget command with parameters. /// @@ -128,28 +92,5 @@ internal WinGetCLICommandResult RunCommand(PowerShellCmdlet pwshCmdlet, WinGetCL throw new WinGetCLITimeoutException(builder.Command, builder.Parameters); } - - // Path.IsPathFullyQualified is not available in .NET Framework. - private static bool IsFullyQualified(string path) - { - if (path.Length < 3) - { - return false; - } - - if (IsDirectorySeparator(path[0])) - { - return IsDirectorySeparator(path[1]); - } - - char drive = path[0]; - bool isDriveLetter = (drive >= 'A' && drive <= 'Z') || (drive >= 'a' && drive <= 'z'); - return isDriveLetter && path[1] == ':' && IsDirectorySeparator(path[2]); - } - - private static bool IsDirectorySeparator(char c) - { - return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar; - } } } diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/AppxModuleHelperTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/AppxModuleHelperTests.cs new file mode 100644 index 0000000000..1f6a6715dd --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/AppxModuleHelperTests.cs @@ -0,0 +1,39 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.UnitTests +{ + using Microsoft.WinGet.Client.Engine.Helpers; + using Windows.ApplicationModel; + using Xunit; + + /// + /// Tests for . + /// + public class AppxModuleHelperTests + { + /// + /// Tests that only packages published by Microsoft and signed by the Store are trusted. + /// + /// The PublisherId of the package. + /// The SignatureKind of the package. + /// Whether the package is trusted. + [Theory] + [InlineData("8wekyb3d8bbwe", PackageSignatureKind.Store, true)] + [InlineData("8wekyb3d8bbwe", "Store", true)] + [InlineData("8wekyb3d8bbwe", PackageSignatureKind.None, false)] + [InlineData("8wekyb3d8bbwe", "Developer", false)] + [InlineData("8wekyb3d8bbwe", PackageSignatureKind.Enterprise, false)] + [InlineData("8wekyb3d8bbwe", null, false)] + [InlineData("0000000000000", PackageSignatureKind.Store, false)] + [InlineData(null, "Store", false)] + [InlineData(null, null, false)] + public void IsStoreSignedMicrosoftPackage(string? publisherId, object? signatureKind, bool expected) + { + Assert.Equal(expected, AppxModuleHelper.IsStoreSignedMicrosoftPackage(publisherId, signatureKind)); + } + } +} diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs deleted file mode 100644 index 0447a873c0..0000000000 --- a/src/PowerShell/Microsoft.WinGet.UnitTests/WingetCLIWrapperTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -// ----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft Corporation. Licensed under the MIT License. -// -// ----------------------------------------------------------------------------- - -namespace Microsoft.WinGet.UnitTests -{ - using System; - using System.IO; - using Microsoft.WinGet.Client.Engine.Helpers; - using Xunit; - - /// - /// Tests for . - /// - public class WingetCLIWrapperTests - { - private const string FileName = "winget.exe"; - - /// - /// Tests that the first PATH directory containing the file is returned. - /// - [Fact] - public void FindInPathReturnsFirstMatch() - { - string root = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; - - try - { - string empty = Directory.CreateDirectory(Path.Combine(root, "empty")).FullName; - string first = Directory.CreateDirectory(Path.Combine(root, "first")).FullName; - string second = Directory.CreateDirectory(Path.Combine(root, "second")).FullName; - File.WriteAllText(Path.Combine(first, FileName), string.Empty); - File.WriteAllText(Path.Combine(second, FileName), string.Empty); - - string envPath = string.Join(Path.PathSeparator, empty, first, second); - - Assert.Equal(Path.Combine(first, FileName), WingetCLIWrapper.FindInPath(envPath, FileName)); - } - finally - { - Directory.Delete(root, true); - } - } - - /// - /// Tests that PATH entries that resolve to the current directory are ignored. - /// - [Fact] - public void FindInPathIgnoresCurrentDirectory() - { - string fileName = $"{Guid.NewGuid()}.exe"; - string currentDirectory = Environment.CurrentDirectory; - string plantedFile = Path.Combine(currentDirectory, fileName); - File.WriteAllText(plantedFile, string.Empty); - - try - { - string envPath = string.Join( - Path.PathSeparator, - string.Empty, - ".", - ".\\", - currentDirectory.Substring(0, 2), - currentDirectory.Substring(2)); - - Assert.Null(WingetCLIWrapper.FindInPath(envPath, fileName)); - } - finally - { - File.Delete(plantedFile); - } - } - } -} From 88cb424dbfc92cdb039ea86ca198b682d45db251 Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:53:37 -0800 Subject: [PATCH 4/7] Restore WinGet PATH and alias checks and fix PATH repair --- .../1.31/powershell-winget-path-resolution.md | 2 +- .../Common/Utilities.cs | 28 ++++++++- .../Common/WinGetIntegrity.cs | 48 +++++++++----- .../UtilitiesTests.cs | 43 +++++++++++++ .../WinGetIntegrityTests.cs | 63 +++++++++++++++++++ 5 files changed, 165 insertions(+), 19 deletions(-) create mode 100644 src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs create mode 100644 src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs diff --git a/doc/release-notes/1.31/powershell-winget-path-resolution.md b/doc/release-notes/1.31/powershell-winget-path-resolution.md index 9f47f756f2..9d99382733 100644 --- a/doc/release-notes/1.31/powershell-winget-path-resolution.md +++ b/doc/release-notes/1.31/powershell-winget-path-resolution.md @@ -2,4 +2,4 @@ ### Minor Bug Fixes -* Fixed `Assert-WinGetPackageManager` and `Repair-WinGetPackageManager` running a `winget.exe` from the current directory. They now only run `winget.exe` from the installed App Installer package. +* Fixed `Assert-WinGetPackageManager` and `Repair-WinGetPackageManager` running a `winget.exe` from the current directory. They now only run `winget.exe` from the installed App Installer package, while still checking PATH and app-execution alias availability. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/Utilities.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/Utilities.cs index 6d5df012ef..81bc533a99 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/Utilities.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/Utilities.cs @@ -10,6 +10,7 @@ namespace Microsoft.WinGet.Client.Engine.Common using System.Collections; using System.Collections.Generic; using System.IO; + using System.Linq; using System.Management.Automation; using System.Security.Principal; using System.Threading; @@ -111,15 +112,38 @@ public static void AddWindowsAppToPath() { var scope = EnvironmentVariableTarget.User; string? envPathValue = Environment.GetEnvironmentVariable(Constants.PathEnvVar, scope); - if (string.IsNullOrEmpty(envPathValue) || !envPathValue.Contains(Utilities.LocalDataWindowsAppPath)) + string updatedPath = AddDirectoryToPath(envPathValue, Utilities.LocalDataWindowsAppPath); + if (updatedPath != envPathValue) { Environment.SetEnvironmentVariable( Constants.PathEnvVar, - $"{envPathValue};{Utilities.LocalDataWindowsAppPath}", + updatedPath, scope); } } + /// Appends a missing directory without changing existing PATH entries. + /// The PATH value. + /// The directory to add. + /// The updated PATH value. + public static string AddDirectoryToPath(string? envPath, string directory) + { + return PathContainsDirectory(envPath, directory) ? envPath! : $"{envPath};{directory}"; + } + + /// Checks whether PATH contains the directory as a complete entry. + /// The PATH value. + /// The directory to find. + /// Whether the directory is present. + public static bool PathContainsDirectory(string? envPath, string directory) + { + return envPath is not null && + envPath.Split(Path.PathSeparator).Any(path => string.Equals( + path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), + directory, + StringComparison.OrdinalIgnoreCase)); + } + /// /// This is based of https://github.com/PowerShell/PowerShell/blob/master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs. /// So we can convert JSON to Hashtable for Windows PowerShell and PowerShell Core. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs index 703ea90afa..6c3fbdced0 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs @@ -67,6 +67,14 @@ public static void AssertWinGet(PowerShellCmdlet pwshCmdlet, string expectedVers throw new WinGetIntegrityException(IntegrityCategory.Unknown, e); } + var environmentCategory = GetEnvironmentIntegrityCategory( + Utilities.LocalDataWindowsAppPath, + Environment.GetEnvironmentVariable(Constants.PathEnvVar)); + if (environmentCategory != IntegrityCategory.Installed) + { + throw new WinGetIntegrityException(environmentCategory); + } + // WinGet is installed. Verify version if needed. if (!string.IsNullOrEmpty(expectedVersion)) { @@ -93,6 +101,25 @@ public static void AssertWinGet(PowerShellCmdlet pwshCmdlet, string expectedVers } } + /// Checks app-execution alias and PATH availability without running a command. + /// The WindowsApps directory. + /// The current process PATH. + /// The environment's integrity category. + internal static IntegrityCategory GetEnvironmentIntegrityCategory(string windowsAppsPath, string? envPath) + { + if (!File.Exists(Path.Combine(windowsAppsPath, Constants.WinGetExe))) + { + return IntegrityCategory.AppExecutionAliasDisabled; + } + + if (!Utilities.PathContainsDirectory(envPath, windowsAppsPath)) + { + return IntegrityCategory.NotInPath; + } + + return IntegrityCategory.Installed; + } + private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet, string? wingetPath) { // Ok, so you are here because calling winget --version failed. Lets try to figure out why. @@ -130,23 +157,12 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet, string? // First lets check if the file is there, which means it is installed or someone is taking our place. if (File.Exists(WingetCLIWrapper.WinGetFullPath)) { - // The file exists, but we couldn't call it... Well maybe winget's app execution alias is not enabled. - // The trick is knowing that a magical file appears under WindowsApp when its enabled. - string wingetAliasPath = Path.Combine(Utilities.LocalDataWindowsAppPath, Constants.WinGetExe); - if (File.Exists(wingetAliasPath)) - { - // App execution alias is enabled. Then maybe the path? - string? envPath = Environment.GetEnvironmentVariable(Constants.PathEnvVar, EnvironmentVariableTarget.User); - if (string.IsNullOrEmpty(envPath) || - !envPath.EndsWith(Utilities.LocalDataWindowsAppPath) || - !envPath.Contains($"{Utilities.LocalDataWindowsAppPath};")) - { - return IntegrityCategory.NotInPath; - } - } - else + var environmentCategory = GetEnvironmentIntegrityCategory( + Utilities.LocalDataWindowsAppPath, + Environment.GetEnvironmentVariable(Constants.PathEnvVar)); + if (environmentCategory != IntegrityCategory.Installed) { - return IntegrityCategory.AppExecutionAliasDisabled; + return environmentCategory; } } diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs new file mode 100644 index 0000000000..a9ff2adaaa --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs @@ -0,0 +1,43 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.UnitTests +{ + using Microsoft.WinGet.Client.Engine.Common; + using Xunit; + + /// Tests the PATH update used by Repair. + public class UtilitiesTests + { + private const string WindowsAppsPath = @"C:\Users\Test\AppData\Local\Microsoft\WindowsApps"; + + /// Repairs missing entries without mistaking lookalikes for the WindowsApps directory. + /// The original PATH format. + /// The expected PATH format. + [Theory] + [InlineData(null, ";{0}")] + [InlineData("", ";{0}")] + [InlineData("{0}.other", "{0}.other;{0}")] + [InlineData(@"{0}\SomePackage", @"{0}\SomePackage;{0}")] + [InlineData(@"{0}.other;{0}\SomePackage", @"{0}.other;{0}\SomePackage;{0}")] + [InlineData("{0}", "{0}")] + [InlineData(@"{1}\", @"{1}\")] + [InlineData("{0}.other;{0}", "{0}.other;{0}")] + public void AddDirectoryToPathRepairsMissingEntry(string? pathFormat, string expectedFormat) + { + string? envPath = pathFormat is null + ? null + : string.Format(pathFormat, WindowsAppsPath, WindowsAppsPath.ToUpperInvariant()); + string expectedPath = string.Format(expectedFormat, WindowsAppsPath, WindowsAppsPath.ToUpperInvariant()); + + string repairedPath = Utilities.AddDirectoryToPath(envPath, WindowsAppsPath); + + Assert.Equal(expectedPath, repairedPath); + Assert.True(Utilities.PathContainsDirectory(repairedPath, WindowsAppsPath)); + Assert.Equal(repairedPath, Utilities.AddDirectoryToPath(repairedPath, WindowsAppsPath)); + } + } +} diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs new file mode 100644 index 0000000000..ac9332fa96 --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs @@ -0,0 +1,63 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.UnitTests +{ + using System; + using System.IO; + using Microsoft.WinGet.Client.Engine.Common; + using Xunit; + + /// Tests the independent PATH and app-execution alias checks. + public class WinGetIntegrityTests + { + /// Checks environment health independently of executable launch success. + /// Whether the app-execution alias exists. + /// The PATH, with placeholders for the WindowsApps directory. + /// The expected integrity category. + [Theory] + [InlineData(false, "{0}", IntegrityCategory.AppExecutionAliasDisabled)] + [InlineData(false, null, IntegrityCategory.AppExecutionAliasDisabled)] + [InlineData(true, null, IntegrityCategory.NotInPath)] + [InlineData(true, "", IntegrityCategory.NotInPath)] + [InlineData(true, @".;C:\Other", IntegrityCategory.NotInPath)] + [InlineData(true, "{0}.other", IntegrityCategory.NotInPath)] + [InlineData(true, @"{0}\SomePackage", IntegrityCategory.NotInPath)] + [InlineData(true, @"{0}.other;{0}\SomePackage", IntegrityCategory.NotInPath)] + [InlineData(true, "{0}.other;{0}", IntegrityCategory.Installed)] + [InlineData(true, "{0}", IntegrityCategory.Installed)] + [InlineData(true, @"{0};C:\Other", IntegrityCategory.Installed)] + [InlineData(true, @"C:\Other;{0};C:\Another", IntegrityCategory.Installed)] + [InlineData(true, @"C:\Other;{0}", IntegrityCategory.Installed)] + [InlineData(true, @"{0}\", IntegrityCategory.Installed)] + [InlineData(true, "{1}", IntegrityCategory.Installed)] + public void GetEnvironmentIntegrityCategoryChecksAliasAndPath( + bool aliasEnabled, + string? pathFormat, + IntegrityCategory expected) + { + string windowsAppsPath = Directory.CreateTempSubdirectory("WinGetIntegrityTests-").FullName; + + try + { + if (aliasEnabled) + { + File.WriteAllText(Path.Combine(windowsAppsPath, Constants.WinGetExe), string.Empty); + } + + string? envPath = pathFormat is null + ? null + : string.Format(pathFormat, windowsAppsPath, windowsAppsPath.ToUpperInvariant()); + + Assert.Equal(expected, WinGetIntegrity.GetEnvironmentIntegrityCategory(windowsAppsPath, envPath)); + } + finally + { + Directory.Delete(windowsAppsPath, true); + } + } + } +} From 4c1869053d9e719ea0e247331915b3dc4ac68999 Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:12:20 -0800 Subject: [PATCH 5/7] Fix spelling check failure in PATH repair test comment --- src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs index a9ff2adaaa..023bbb75a5 100644 --- a/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs @@ -14,7 +14,7 @@ public class UtilitiesTests { private const string WindowsAppsPath = @"C:\Users\Test\AppData\Local\Microsoft\WindowsApps"; - /// Repairs missing entries without mistaking lookalikes for the WindowsApps directory. + /// Repairs missing entries without mistaking similar paths for the WindowsApps directory. /// The original PATH format. /// The expected PATH format. [Theory] From 80aaf14da5b8788edf9fb66bcccd009dbfbcd546 Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:18:22 -0800 Subject: [PATCH 6/7] Require Store signing only for production WinGet integrity checks --- .../Common/WinGetIntegrity.cs | 8 +++-- .../Helpers/AppxModuleHelper.cs | 18 +++++----- ...icrosoft.WinGet.Client.Integrity.Tests.ps1 | 33 +++++++++++++++++++ src/PowerShell/tests/RunTests.ps1 | 2 +- 4 files changed, 49 insertions(+), 12 deletions(-) create mode 100644 src/PowerShell/tests/Microsoft.WinGet.Client.Integrity.Tests.ps1 diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs index 6c3fbdced0..7643174167 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Common/WinGetIntegrity.cs @@ -177,7 +177,11 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet, string? // It could be that AppInstaller package is old or the package is not // registered at this point. To know that, call Get-AppxPackage. var appxModule = new AppxModuleHelper(pwshCmdlet); +#if USE_PROD_CLSIDS + string? version = appxModule.GetStoreSignedAppInstallerPropertyValue("Version"); +#else string? version = appxModule.GetAppInstallerPropertyValue("Version"); +#endif if (version is null) { // This can happen in Windows Sandbox. @@ -199,8 +203,8 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet, string? private static string? GetWinGetPath(PowerShellCmdlet pwshCmdlet) { #if USE_PROD_CLSIDS - string? location = new AppxModuleHelper(pwshCmdlet).GetStoreSignedAppInstallerLocation(); - return location is null ? null : Path.Combine(location, Constants.WinGetExe); + string? location = new AppxModuleHelper(pwshCmdlet).GetStoreSignedAppInstallerPropertyValue("InstallLocation"); + return string.IsNullOrEmpty(location) ? null : Path.Combine(location, Constants.WinGetExe); #else // Development packages are not Store signed. return WingetCLIWrapper.WinGetFullPath; diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs index 67d0ca45c6..d0e19ac308 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs @@ -66,7 +66,6 @@ internal class AppxModuleHelper private const string AppxManifest = "AppxManifest.xml"; private const string PackageFullName = "PackageFullName"; private const string Version = "Version"; - private const string InstallLocation = "InstallLocation"; private const string PublisherId = "PublisherId"; private const string SignatureKind = "SignatureKind"; private const string MicrosoftPublisherId = "8wekyb3d8bbwe"; @@ -120,14 +119,13 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) } /// - /// Gets the Microsoft-published, Store-signed AppInstaller package. + /// Calls Get-AppxPackage Microsoft.DesktopAppInstaller. /// /// Whether to get for all users. /// Result of Get-AppxPackage. public PSObject? GetAppInstallerObject(bool allUsers = false) { - return this.GetAppxObjects(AppInstallerName, allUsers) - .FirstOrDefault(p => IsStoreSignedMicrosoftPackage(p.Properties[PublisherId]?.Value, p.Properties[SignatureKind]?.Value)); + return this.GetAppxObjects(AppInstallerName, allUsers).FirstOrDefault(); } /// @@ -162,13 +160,15 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) } /// - /// Gets the install location of the AppInstaller package, if it is published by Microsoft and signed by the Store. + /// Gets a string property from the Microsoft-published, Store-signed AppInstaller package. /// - /// The install location, or null if there is no such package. - public string? GetStoreSignedAppInstallerLocation() + /// Property name. + /// The property value, or null if the package or property is missing. + public string? GetStoreSignedAppInstallerPropertyValue(string propertyName) { - string? location = this.GetAppInstallerPropertyValue(InstallLocation); - return string.IsNullOrEmpty(location) ? null : location; + var packageObj = this.GetAppxObjects(AppInstallerName) + .FirstOrDefault(p => IsStoreSignedMicrosoftPackage(p.Properties[PublisherId]?.Value, p.Properties[SignatureKind]?.Value)); + return packageObj?.Properties[propertyName]?.Value as string; } /// diff --git a/src/PowerShell/tests/Microsoft.WinGet.Client.Integrity.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.Client.Integrity.Tests.ps1 new file mode 100644 index 0000000000..735cc5f98b --- /dev/null +++ b/src/PowerShell/tests/Microsoft.WinGet.Client.Integrity.Tests.ps1 @@ -0,0 +1,33 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +param([switch]$TargetProduction) + +Describe 'Assert-WinGetPackageManager' -Skip:(-not $TargetProduction -or [Security.Principal.WindowsIdentity]::GetCurrent().IsSystem) { + BeforeAll { + Import-Module Microsoft.WinGet.Client + } + + It 'Reports using only the Store-signed package version' -ForEach @( + @{ StoreVersion = $null; Expected = 'AppInstallerNotInstalled' } + @{ StoreVersion = '1.0.0.0'; Expected = 'AppInstallerNotSupported' } + @{ StoreVersion = '1.31.0.0'; Expected = 'AppInstallerNotRegistered' } + ) { + Mock Get-AppxPackage { + [pscustomobject]@{ PublisherId = '8wekyb3d8bbwe'; SignatureKind = 'Developer'; Version = '1.31.0.0' } + if ($StoreVersion) { + [pscustomobject]@{ PublisherId = '8wekyb3d8bbwe'; SignatureKind = 'Store'; Version = $StoreVersion } + } + } -ParameterFilter { $Name -eq 'Microsoft.DesktopAppInstaller' } + + $originalLocalAppData = $env:LOCALAPPDATA + try { + $env:LOCALAPPDATA = $TestDrive + $failure = { Assert-WinGetPackageManager -ErrorAction Stop } | Should -Throw -PassThru + $failure.Exception.Category | Should -Be $Expected + } + finally { + $env:LOCALAPPDATA = $originalLocalAppData + } + } +} diff --git a/src/PowerShell/tests/RunTests.ps1 b/src/PowerShell/tests/RunTests.ps1 index 4490d2acaf..9e9f60f613 100644 --- a/src/PowerShell/tests/RunTests.ps1 +++ b/src/PowerShell/tests/RunTests.ps1 @@ -56,7 +56,7 @@ $clientConfig = New-PesterConfiguration $clientConfig.TestResult.OutputFormat = "NUnitXML" $clientConfig.TestResult.OutputPath = "$outputPath\Tests-WinGetClient.XML" $clientConfig.TestResult.Enabled = $true -$clientConfig.Run.Container = New-PesterContainer -Path "$PSScriptRoot\Microsoft.WinGet.Client.Tests.ps1" -Data @{ TargetProduction = $TargetProduction } +$clientConfig.Run.Container = New-PesterContainer -Path "$PSScriptRoot\Microsoft.WinGet.Client*.Tests.ps1" -Data @{ TargetProduction = $TargetProduction } Invoke-Pester -Configuration $clientConfig From 9017bf46be9cff7ac2167a53ed1f24b545184a9c Mon Sep 17 00:00:00 2001 From: Amir El Bawab <104940545+AmelBawa-msft@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:46:49 -0800 Subject: [PATCH 7/7] Remove the implicit alias fallback from the WinGet CLI wrapper --- .../Commands/CliCommand.cs | 2 +- .../Commands/UserSettingsCommand.cs | 2 +- .../Helpers/WinGetVersion.cs | 6 +++--- .../Helpers/WingetCLIWrapper.cs | 15 +++++---------- .../WinGetIntegrityTests.cs | 11 ++++++++++- 5 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/CliCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/CliCommand.cs index 577a0bedba..50e168aad6 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/CliCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/CliCommand.cs @@ -135,7 +135,7 @@ public void ResetAllSources() private WinGetCLICommandResult Run(WinGetCLICommandBuilder builder, int timeOut = 60000) { - var wingetCliWrapper = new WingetCLIWrapper(); + var wingetCliWrapper = new WingetCLIWrapper(WingetCLIWrapper.WinGetFullPath); var result = wingetCliWrapper.RunCommand(this, builder, timeOut); result.VerifyExitCode(); diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/UserSettingsCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/UserSettingsCommand.cs index 54fb476650..1d8f44f7a6 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/UserSettingsCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/UserSettingsCommand.cs @@ -41,7 +41,7 @@ public UserSettingsCommand(PSCmdlet psCmdlet) // Here would be "The specified method is not supported." if (winGetSettingsFilePath == null) { - var wingetCliWrapper = new WingetCLIWrapper(); + var wingetCliWrapper = new WingetCLIWrapper(WingetCLIWrapper.WinGetFullPath); var settingsResult = wingetCliWrapper.RunCommand(this, new WinGetCLICommandBuilder("settings").AppendSubCommand("export")); // Read the user settings file property. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs index 28e5d5285f..855d2ee030 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WinGetVersion.cs @@ -74,9 +74,9 @@ public WinGetVersion(string version) /// Runs the winget version command. /// /// PowerShell cmdlet. - /// The full path of winget, or null to use the default. + /// The full path to the WinGet executable. /// The command result. - public static WinGetCLICommandResult RunWinGetVersionFromCLI(PowerShellCmdlet pwshCmdlet, string? wingetPath = null) + public static WinGetCLICommandResult RunWinGetVersionFromCLI(PowerShellCmdlet pwshCmdlet, string wingetPath) { var wingetCliWrapper = new WingetCLIWrapper(wingetPath); return wingetCliWrapper.RunCommand(pwshCmdlet, new WinGetCLICommandBuilder().AppendSwitch("--version")); @@ -99,7 +99,7 @@ public static WinGetVersion InstalledWinGetVersion(PowerShellCmdlet pwshCmdlet, return new WinGetVersion(comVersion); } - versionResult = RunWinGetVersionFromCLI(pwshCmdlet); + versionResult = RunWinGetVersionFromCLI(pwshCmdlet, WingetCLIWrapper.WinGetFullPath); } return new WinGetVersion(versionResult.StdOut.Replace(Environment.NewLine, string.Empty)); diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs index 6e8b11b3a6..40423320b3 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs @@ -25,25 +25,20 @@ internal class WingetCLIWrapper /// /// Initializes a new instance of the class. - /// When app execution alias is disabled the path of the exe is - /// in the package family name directory in the local app data windows app directory. If its enabled then there's - /// link in the windows app data directory. To avoid checking if its enabled or not, just look in the package - /// family name directory. - /// For test, point to the wingetdev executable. /// - /// The full path of winget, or null to use . - public WingetCLIWrapper(string? wingetPath = null) + /// The full path to the WinGet executable. + public WingetCLIWrapper(string wingetPath) { + this.wingetPath = wingetPath ?? throw new ArgumentNullException(nameof(wingetPath)); + if (Utilities.ExecutingAsSystem) { throw new NotSupportedException(); } - - this.wingetPath = wingetPath ?? WinGetFullPath; } /// - /// Gets the full path of winget executable. + /// Gets the WinGet app execution alias path in the package family directory. /// public static string WinGetFullPath { diff --git a/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs index ac9332fa96..58402b4bb1 100644 --- a/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs @@ -9,11 +9,20 @@ namespace Microsoft.WinGet.UnitTests using System; using System.IO; using Microsoft.WinGet.Client.Engine.Common; + using Microsoft.WinGet.Client.Engine.Helpers; using Xunit; - /// Tests the independent PATH and app-execution alias checks. + /// Tests WinGet executable paths and environment integrity checks. public class WinGetIntegrityTests { + /// A missing executable path must not select the package alias. + [Fact] + public void MissingExecutablePathDoesNotFallBackToAlias() + { + static void CreateWithoutPath() => _ = new WingetCLIWrapper(null!); + Assert.Throws(CreateWithoutPath); + } + /// Checks environment health independently of executable launch success. /// Whether the app-execution alias exists. /// The PATH, with placeholders for the WindowsApps directory.