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..9d99382733 --- /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. 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/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/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 e647db1049..7643174167 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) { @@ -64,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)) { @@ -90,7 +101,26 @@ public static void AssertWinGet(PowerShellCmdlet pwshCmdlet, string expectedVers } } - private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) + /// 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. var category = IntegrityCategory.Unknown; @@ -103,8 +133,11 @@ 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(); + if (wingetPath != null) + { + var ps = PowerShell.Create(RunspaceMode.CurrentRunspace); + ps.AddCommand(wingetPath).Invoke(); + } } catch (ApplicationFailedException e) { @@ -124,23 +157,12 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) // 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)) + var environmentCategory = GetEnvironmentIntegrityCategory( + Utilities.LocalDataWindowsAppPath, + Environment.GetEnvironmentVariable(Constants.PathEnvVar)); + if (environmentCategory != IntegrityCategory.Installed) { - // 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 - { - return IntegrityCategory.AppExecutionAliasDisabled; + return environmentCategory; } } @@ -155,7 +177,11 @@ private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet) // 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. @@ -174,6 +200,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).GetStoreSignedAppInstallerPropertyValue("InstallLocation"); + return string.IsNullOrEmpty(location) ? 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..d0e19ac308 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AppxModuleHelper.cs @@ -66,6 +66,10 @@ internal class AppxModuleHelper private const string AppxManifest = "AppxManifest.xml"; private const string PackageFullName = "PackageFullName"; private const string Version = "Version"; + 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"; @@ -121,7 +125,7 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) /// Result of Get-AppxPackage. public PSObject? GetAppInstallerObject(bool allUsers = false) { - return this.GetAppxObject(AppInstallerName, allUsers); + return this.GetAppxObjects(AppInstallerName, allUsers).FirstOrDefault(); } /// @@ -130,7 +134,7 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) /// Result of Get-AppxPackage. public PSObject? GetWinGetSourceObject() { - return this.GetAppxObject(WinGetSourceName); + return this.GetAppxObjects(WinGetSourceName).FirstOrDefault(); } /// @@ -155,6 +159,18 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet) return result; } + /// + /// Gets a string property from the Microsoft-published, Store-signed AppInstaller package. + /// + /// Property name. + /// The property value, or null if the package or property is missing. + public string? GetStoreSignedAppInstallerPropertyValue(string propertyName) + { + var packageObj = this.GetAppxObjects(AppInstallerName) + .FirstOrDefault(p => IsStoreSignedMicrosoftPackage(p.Properties[PublisherId]?.Value, p.Properties[SignatureKind]?.Value)); + return packageObj?.Properties[propertyName]?.Value as string; + } + /// /// 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..855d2ee030 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 to the WinGet executable. /// The command result. - public static WinGetCLICommandResult RunWinGetVersionFromCLI(PowerShellCmdlet pwshCmdlet, bool fullPath = true) + public static WinGetCLICommandResult RunWinGetVersionFromCLI(PowerShellCmdlet pwshCmdlet, string wingetPath) { - var wingetCliWrapper = new WingetCLIWrapper(fullPath); + 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 d9c76a810c..40423320b3 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/WingetCLIWrapper.cs @@ -25,32 +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. /// - /// Use full path or not. - public WingetCLIWrapper(bool fullPath = true) + /// 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(); } - - if (fullPath) - { - this.wingetPath = WinGetFullPath; - } - else - { - this.wingetPath = Constants.WinGetExe; - } } /// - /// 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/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/UtilitiesTests.cs b/src/PowerShell/Microsoft.WinGet.UnitTests/UtilitiesTests.cs new file mode 100644 index 0000000000..023bbb75a5 --- /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 similar paths 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..58402b4bb1 --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.UnitTests/WinGetIntegrityTests.cs @@ -0,0 +1,72 @@ +// ----------------------------------------------------------------------------- +// +// 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 Microsoft.WinGet.Client.Engine.Helpers; + using Xunit; + + /// 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. + /// 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); + } + } + } +} 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