Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread
Evangelink marked this conversation as resolved.
Resolved
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Security.Cryptography;

using Microsoft.Testing.Extensions.PackagedApp.Resources;

namespace Microsoft.Testing.Extensions.PackagedApp;

/// <summary>
/// The identity of a packaged Windows (UWP/WinUI) app, read from its <c>AppxManifest.xml</c>.
/// </summary>
/// <remarks>
/// <para>
/// A packaged app is launched by <em>Application User Model ID</em> (AUMID), never by
/// <c>Process.Start</c>. The AUMID is <c>{PackageFamilyName}!{ApplicationId}</c>, and the package
/// family name is <c>{PackageName}_{publisherId}</c> where <c>publisherId</c> is a 13-character hash
/// of the manifest's <c>Publisher</c>. VSTest reads these values from VS-internal deployment
/// components; this type computes them from the manifest using only public, cross-platform managed
/// APIs so the extension does not depend on the Visual Studio install.
/// </para>
/// </remarks>
internal sealed class AppxManifestInfo
Comment thread
Evangelink marked this conversation as resolved.
Resolved
{
/// <summary>
/// The canonical file name of a packaged app's manifest inside its (loose or extracted) layout.
/// </summary>
internal const string AppxManifestFileName = "AppxManifest.xml";

// The alphabet Windows uses to encode the publisher hash (Douglas Crockford's base32: the digits
// and lowercase letters with i, l, o and u removed). Must not be reordered.
private const string PublisherHashAlphabet = "0123456789abcdefghjkmnpqrstvwxyz";

private AppxManifestInfo(string packageName, string publisher, string? applicationId)
{
PackageName = packageName;
Publisher = publisher;
ApplicationId = applicationId;
PackageFamilyName = $"{packageName}_{ComputePublisherId(publisher)}";
AppUserModelId = applicationId is null ? null : $"{PackageFamilyName}!{applicationId}";
}

/// <summary>Gets the package name (the manifest's <c>Identity/@Name</c>).</summary>
public string PackageName { get; }

/// <summary>Gets the publisher (the manifest's <c>Identity/@Publisher</c>).</summary>
public string Publisher { get; }

/// <summary>
/// Gets the id of the first application declared in the manifest (<c>Applications/Application/@Id</c>),
/// or <see langword="null"/> when the manifest declares no application.
/// </summary>
public string? ApplicationId { get; }

/// <summary>Gets the package family name (<c>{PackageName}_{publisherId}</c>).</summary>
public string PackageFamilyName { get; }

/// <summary>
/// Gets the Application User Model ID (<c>{PackageFamilyName}!{ApplicationId}</c>) used to activate
/// the app, or <see langword="null"/> when the manifest declares no application.
/// </summary>
public string? AppUserModelId { get; }

/// <summary>
/// Reads the manifest at the root of <paramref name="layoutDirectory"/> if the directory is a
/// packaged-app layout.
/// </summary>
/// <param name="layoutDirectory">The directory to probe for an <c>AppxManifest.xml</c>.</param>
/// <param name="info">The parsed manifest info when the directory is a packaged-app layout.</param>
/// <returns>
/// <see langword="true"/> when an <c>AppxManifest.xml</c> was found and parsed; otherwise
/// <see langword="false"/>.
/// </returns>
public static bool TryReadFromLayout(string layoutDirectory, [NotNullWhen(true)] out AppxManifestInfo? info)
{
string manifestPath = Path.Combine(layoutDirectory, AppxManifestFileName);
if (!File.Exists(manifestPath))
{
info = null;
return false;
}

info = ReadFromManifest(manifestPath);
return true;
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}

/// <summary>Reads and parses the manifest at <paramref name="manifestPath"/>.</summary>
/// <param name="manifestPath">The path to an <c>AppxManifest.xml</c>.</param>
/// <returns>The parsed manifest info.</returns>
public static AppxManifestInfo ReadFromManifest(string manifestPath)
{
using FileStream stream = File.OpenRead(manifestPath);
return ReadFromManifest(stream);
}

/// <summary>Reads and parses a manifest from <paramref name="manifestStream"/>.</summary>
/// <param name="manifestStream">A stream over an <c>AppxManifest.xml</c>.</param>
/// <returns>The parsed manifest info.</returns>
public static AppxManifestInfo ReadFromManifest(Stream manifestStream)
{
var document = XDocument.Load(manifestStream);
XElement? root = document.Root;

// Match by local name so we are resilient to the manifest schema version (the foundation
// namespace URI changes across Windows 10 SDK revisions).
XElement? identity = root?.Elements().FirstOrDefault(static e => e.Name.LocalName == "Identity");
string? name = identity?.Attribute("Name")?.Value;
string? publisher = identity?.Attribute("Publisher")?.Value;

if (name is null || name.Length == 0 || publisher is null || publisher.Length == 0)
{
throw new InvalidOperationException(ExtensionResources.InvalidAppxManifestMissingIdentity);
}

string? applicationId = root?.Elements().FirstOrDefault(static e => e.Name.LocalName == "Applications")?
.Elements().FirstOrDefault(static e => e.Name.LocalName == "Application")?
.Attribute("Id")?.Value;
Comment thread
Evangelink marked this conversation as resolved.
Resolved
Comment thread
Evangelink marked this conversation as resolved.
Resolved
Comment thread
Evangelink marked this conversation as resolved.
Resolved

return new AppxManifestInfo(name, publisher, applicationId);
}

/// <summary>
/// Computes the 13-character publisher id (the suffix of the package family name) for
/// <paramref name="publisher"/>, using the public Windows algorithm: base32-encode the first 8
/// bytes of the SHA-256 hash of the UTF-16LE publisher string.
/// </summary>
/// <param name="publisher">The manifest's <c>Identity/@Publisher</c> value.</param>
/// <returns>The 13-character publisher id.</returns>
internal static string ComputePublisherId(string publisher)
{
byte[] hash = SHA256.HashData(Encoding.Unicode.GetBytes(publisher));

// Take the first 8 bytes (64 bits) and encode them big-endian as 13 base32 characters. 64 bits
// is not a multiple of 5, so the final character carries the 4 leftover bits padded with a 0.
var builder = new StringBuilder(13);
int buffer = 0;
int bitsInBuffer = 0;
for (int i = 0; i < 8; i++)
{
buffer = (buffer << 8) | hash[i];
bitsInBuffer += 8;
while (bitsInBuffer >= 5)
{
bitsInBuffer -= 5;
builder.Append(PublisherHashAlphabet[(buffer >> bitsInBuffer) & 0x1F]);
buffer &= (1 << bitsInBuffer) - 1;
}
}

if (bitsInBuffer > 0)
{
builder.Append(PublisherHashAlphabet[(buffer << (5 - bitsInBuffer)) & 0x1F]);
}

return builder.ToString();
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
#nullable enable
Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo
Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.AppUserModelId.get -> string?
Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ApplicationId.get -> string?
Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.PackageFamilyName.get -> string!
Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.PackageName.get -> string!
Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.Publisher.get -> string!
const Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.AppxManifestFileName = "AppxManifest.xml" -> string!
static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ComputePublisherId(string! publisher) -> string!
static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ReadFromManifest(System.IO.Stream! manifestStream) -> Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo!
static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.ReadFromManifest(string! manifestPath) -> Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo!
static Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo.TryReadFromLayout(string! layoutDirectory, out Microsoft.Testing.Extensions.PackagedApp.AppxManifestInfo? info) -> bool
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,8 @@ This package extends Microsoft Testing Platform to deploy and launch a packaged
<ProjectReference Include="$(RepoRoot)src\Platform\Microsoft.Testing.Platform\Microsoft.Testing.Platform.csproj" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.Testing.Extensions.UnitTests" Key="$(VsPublicKey)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,15 @@ namespace Microsoft.Testing.Extensions.PackagedApp;
/// WinUI); see https://github.com/microsoft/testfx/issues/2784.
/// </para>
/// <para>
/// This reference implementation performs the deploy-and-launch step (stage the loose layout, then
/// launch the produced executable from the deployment directory). The packaged AUMID-activation
/// branch — registering the layout with <c>PackageManager.RegisterPackageByUriAsync</c> and calling
/// <c>IApplicationActivationManager.ActivateApplication</c> — is a clearly-marked follow-up.
/// This reference implementation performs the deploy-and-launch step for a <em>non-packaged</em>
/// (loose-layout) test host (stage the layout, then launch the produced executable from the
/// deployment directory). A genuinely packaged layout — detected by the presence of an
/// <c>AppxManifest.xml</c> — cannot be started with <c>Process.Start</c>; its AUMID-activation branch
/// (registering the layout with <c>PackageManager.RegisterPackageByUriAsync</c> and calling
/// <c>IApplicationActivationManager.ActivateApplication</c>) is a clearly-marked follow-up
/// (https://github.com/microsoft/testfx/issues/2784), so for now such a layout is rejected with an
/// actionable error rather than silently failing at launch. The AUMID that activation will use is
/// already computed from the manifest by <see cref="AppxManifestInfo"/>.
/// </para>
/// <para>
/// In all cases the platform owns argument/environment preparation, the controller-to-host IPC pipe,
Expand All @@ -42,7 +47,10 @@ internal sealed class PackagedAppTestHostLauncher : ITestHostLauncher

public string Description => ExtensionResources.PackagedAppExtensionDescription;

public Task<bool> IsEnabledAsync() => Task.FromResult(true);
// Packaged Windows apps (UWP/WinUI) are a Windows-only concept. On other operating systems the
// launcher stays disabled so it is never registered, which keeps the platform on its default
// in-process/Process.Start path instead of forcing the controller (deploy-and-launch) host.
public Task<bool> IsEnabledAsync() => Task.FromResult(OperatingSystem.IsWindows());
Comment thread
Evangelink marked this conversation as resolved.
Resolved

public Task<ITestHostHandle> LaunchTestHostAsync(TestHostLaunchContext context, CancellationToken cancellationToken)
{
Expand All @@ -52,15 +60,28 @@ public Task<ITestHostHandle> LaunchTestHostAsync(TestHostLaunchContext context,
string sourceDirectory = Path.GetDirectoryName(context.FileName)
?? throw new InvalidOperationException($"Unable to determine the source directory of '{context.FileName}'.");

// 1. Deploy the app's loose layout into an isolated directory. For packaged UWP/WinUI this is
// also where the layout would be registered via PackageManager.RegisterPackageByUriAsync.
// A genuinely packaged (MSIX) app cannot be started with Process.Start: it must be registered
// with the PackageManager and activated by AUMID. That path is not implemented yet (see issue
// #2784), so fail fast with an actionable message — including the AUMID activation would use —
// instead of starting an executable that cannot host the run.
Comment thread
Evangelink marked this conversation as resolved.
Resolved
if (AppxManifestInfo.TryReadFromLayout(sourceDirectory, out AppxManifestInfo? manifestInfo))
{
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
Comment thread
Evangelink marked this conversation as resolved.
Resolved
ExtensionResources.PackagedAppLaunchNotSupported,
manifestInfo.AppUserModelId ?? manifestInfo.PackageFamilyName,
Path.Combine(sourceDirectory, AppxManifestInfo.AppxManifestFileName)));
}

// The layout is not packaged (no AppxManifest.xml). Deploy the loose layout into an isolated
// directory and launch the produced executable from there.
Comment thread
Evangelink marked this conversation as resolved.
Resolved
// 1. Copy the app's loose layout into an isolated directory.
string deploymentDirectory = Path.Combine(Path.GetTempPath(), "MTPPackagedAppDeployment", Guid.NewGuid().ToString("N"));
CopyDirectory(sourceDirectory, deploymentDirectory, cancellationToken);

// 2. Launch the deployed test host, forwarding the platform-prepared arguments and
// environment (which include the controller IPC pipe name the host connects back on).
// Packaged UWP/WinUI would instead AUMID-activate here via IApplicationActivationManager
// and wrap the activated process id.
string deployedFileName = Path.Combine(deploymentDirectory, Path.GetFileName(context.FileName));
var startInfo = new ProcessStartInfo(deployedFileName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,10 @@
<data name="PackagedAppExtensionDisplayName" xml:space="preserve">
<value>Packaged app test host launcher</value>
</data>
<data name="InvalidAppxManifestMissingIdentity" xml:space="preserve">
<value>The packaged app manifest does not declare a valid &lt;Identity Name="..." Publisher="..." /&gt; element.</value>
</data>
<data name="PackagedAppLaunchNotSupported" xml:space="preserve">
<value>Cannot launch the packaged Windows app '{0}' (found '{1}'). Launching a packaged (MSIX) app requires registering the layout with the PackageManager and activating it by Application User Model ID, which this extension does not implement yet (see https://github.com/microsoft/testfx/issues/2784). Only non-packaged (loose-layout) test hosts can be launched today.</value>
Comment thread
Evangelink marked this conversation as resolved.
Resolved
Comment thread
Evangelink marked this conversation as resolved.
Resolved
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../ExtensionResources.resx">
<body>
<trans-unit id="InvalidAppxManifestMissingIdentity">
<source>The packaged app manifest does not declare a valid &lt;Identity Name="..." Publisher="..." /&gt; element.</source>
<target state="new">The packaged app manifest does not declare a valid &lt;Identity Name="..." Publisher="..." /&gt; element.</target>
<note />
</trans-unit>
<trans-unit id="PackagedAppExtensionDescription">
<source>Deploys a packaged Windows (UWP/WinUI) test host to an isolated directory and launches it from there.</source>
<target state="translated">Nasadí zabaleného hostitele testů Windows (UWP/WinUI) do izolovaného adresáře a spustí ho odtamtud.</target>
Expand All @@ -12,6 +17,11 @@
<target state="translated">Spouštěč hostitele testu zabalené aplikace</target>
<note />
</trans-unit>
<trans-unit id="PackagedAppLaunchNotSupported">
<source>Cannot launch the packaged Windows app '{0}' (found '{1}'). Launching a packaged (MSIX) app requires registering the layout with the PackageManager and activating it by Application User Model ID, which this extension does not implement yet (see https://github.com/microsoft/testfx/issues/2784). Only non-packaged (loose-layout) test hosts can be launched today.</source>
<target state="new">Cannot launch the packaged Windows app '{0}' (found '{1}'). Launching a packaged (MSIX) app requires registering the layout with the PackageManager and activating it by Application User Model ID, which this extension does not implement yet (see https://github.com/microsoft/testfx/issues/2784). Only non-packaged (loose-layout) test hosts can be launched today.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../ExtensionResources.resx">
<body>
<trans-unit id="InvalidAppxManifestMissingIdentity">
<source>The packaged app manifest does not declare a valid &lt;Identity Name="..." Publisher="..." /&gt; element.</source>
<target state="new">The packaged app manifest does not declare a valid &lt;Identity Name="..." Publisher="..." /&gt; element.</target>
<note />
</trans-unit>
<trans-unit id="PackagedAppExtensionDescription">
<source>Deploys a packaged Windows (UWP/WinUI) test host to an isolated directory and launches it from there.</source>
<target state="translated">Stellt einen verpackten Windows-Testhost (UWP/WinUI) in einem isolierten Verzeichnis bereit und startet ihn von dort aus.</target>
Expand All @@ -12,6 +17,11 @@
<target state="translated">Testhoststarter für App-Pakete</target>
<note />
</trans-unit>
<trans-unit id="PackagedAppLaunchNotSupported">
<source>Cannot launch the packaged Windows app '{0}' (found '{1}'). Launching a packaged (MSIX) app requires registering the layout with the PackageManager and activating it by Application User Model ID, which this extension does not implement yet (see https://github.com/microsoft/testfx/issues/2784). Only non-packaged (loose-layout) test hosts can be launched today.</source>
<target state="new">Cannot launch the packaged Windows app '{0}' (found '{1}'). Launching a packaged (MSIX) app requires registering the layout with the PackageManager and activating it by Application User Model ID, which this extension does not implement yet (see https://github.com/microsoft/testfx/issues/2784). Only non-packaged (loose-layout) test hosts can be launched today.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
Loading
Loading