Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/release-notes/1.31/powershell-winget-path-resolution.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

/// <summary>Appends a missing directory without changing existing PATH entries.</summary>
/// <param name="envPath">The PATH value.</param>
/// <param name="directory">The directory to add.</param>
/// <returns>The updated PATH value.</returns>
public static string AddDirectoryToPath(string? envPath, string directory)
{
return PathContainsDirectory(envPath, directory) ? envPath! : $"{envPath};{directory}";
}

/// <summary>Checks whether PATH contains the directory as a complete entry.</summary>
/// <param name="envPath">The PATH value.</param>
/// <param name="directory">The directory to find.</param>
/// <returns>Whether the directory is present.</returns>
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));
}

/// <summary>
/// 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ namespace Microsoft.WinGet.Client.Engine.Common
/// </summary>
internal static class WinGetIntegrity
{
private const int ErrorFileNotFound = 2;

/// <summary>
/// Verifies winget runs correctly. If it doesn't, tries to find the reason why it failed.
/// </summary>
Expand All @@ -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);
Comment thread
AmelBawa-msft marked this conversation as resolved.
Resolved
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)
{
Expand All @@ -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))
{
Expand All @@ -90,7 +101,26 @@ public static void AssertWinGet(PowerShellCmdlet pwshCmdlet, string expectedVers
}
}

private static IntegrityCategory GetReason(PowerShellCmdlet pwshCmdlet)
/// <summary>Checks app-execution alias and PATH availability without running a command.</summary>
/// <param name="windowsAppsPath">The WindowsApps directory.</param>
/// <param name="envPath">The current process PATH.</param>
/// <returns>The environment's integrity category.</returns>
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;
Expand All @@ -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)
{
Expand All @@ -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;
}
}

Expand All @@ -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.
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -121,7 +125,7 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet)
/// <returns>Result of Get-AppxPackage.</returns>
public PSObject? GetAppInstallerObject(bool allUsers = false)
{
return this.GetAppxObject(AppInstallerName, allUsers);
return this.GetAppxObjects(AppInstallerName, allUsers).FirstOrDefault();
}

/// <summary>
Expand All @@ -130,7 +134,7 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet)
/// <returns>Result of Get-AppxPackage.</returns>
public PSObject? GetWinGetSourceObject()
{
return this.GetAppxObject(WinGetSourceName);
return this.GetAppxObjects(WinGetSourceName).FirstOrDefault();
}

/// <summary>
Expand All @@ -155,6 +159,18 @@ public AppxModuleHelper(PowerShellCmdlet pwshCmdlet)
return result;
}

/// <summary>
/// Gets a string property from the Microsoft-published, Store-signed AppInstaller package.
/// </summary>
/// <param name="propertyName">Property name.</param>
/// <returns>The property value, or null if the package or property is missing.</returns>
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;
}

/// <summary>
/// Checks if winget source is installed.
/// </summary>
Expand Down Expand Up @@ -245,6 +261,18 @@ public async Task InstallWinGetSourceAsync()
await this.DownloadPackageAndAddAsync(WinGetSourceUrl, WinGetSourceMsixName, options: null);
}

/// <summary>
/// Checks if a package is published by Microsoft and signed by the Store.
/// </summary>
/// <param name="publisherId">The PublisherId of the package.</param>
/// <param name="signatureKind">The SignatureKind of the package.</param>
/// <returns>True if the package is published by Microsoft and signed by the Store.</returns>
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;
}

/// <summary>
/// Gets the Xaml dependency package name and release tag based on the provided WinGet release tag.
/// </summary>
Expand Down Expand Up @@ -338,7 +366,7 @@ private async Task AddAppInstallerBundleAsync(string releaseTag, bool downgrade,
}
}

private PSObject? GetAppxObject(string packageName, bool allUsers = false)
private Collection<PSObject> GetAppxObjects(string packageName, bool allUsers = false)
{
var options = new List<string>();
if (allUsers)
Expand All @@ -352,8 +380,7 @@ private async Task AddAppInstallerBundleAsync(string releaseTag, bool downgrade,
{
{ Name, packageName },
},
options)
.FirstOrDefault();
options);
}

private async Task InstallDependenciesAsync(string releaseTag)
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ public WinGetVersion(string version)
/// Runs the winget version command.
/// </summary>
/// <param name="pwshCmdlet">PowerShell cmdlet.</param>
/// <param name="fullPath">Use full path or not.</param>
/// <param name="wingetPath">The full path to the WinGet executable.</param>
/// <returns>The command result.</returns>
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"));
}

Expand All @@ -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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,20 @@ internal class WingetCLIWrapper

/// <summary>
/// Initializes a new instance of the <see cref="WingetCLIWrapper"/> 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.
/// </summary>
/// <param name="fullPath">Use full path or not.</param>
public WingetCLIWrapper(bool fullPath = true)
/// <param name="wingetPath">The full path to the WinGet executable.</param>
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;
}
}

/// <summary>
/// Gets the full path of winget executable.
/// Gets the WinGet app execution alias path in the package family directory.
/// </summary>
public static string WinGetFullPath
{
Expand Down
Loading
Loading