Skip to content
Merged
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
37 changes: 31 additions & 6 deletions docs/RFCs/017-TestHost-Launcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,23 +265,48 @@ public Task<ITestHostHandle> LaunchTestHostAsync(
string aumid = AppxManifest.ResolveAumid(context.FileName);

// 2. Activate, passing the SAME args the platform prepared. AUMID activation takes a single
// command-line string, so the launcher must escape/quote context.Arguments (e.g. with a
// PasteArguments-style helper) to preserve what ProcessStartInfo.ArgumentList would have done.
// string. Full-trust desktop apps need Windows argv quoting; AppContainer apps need a versioned
// opaque payload that Application.OnLaunched restores before CreateBuilderAsync.
var aam = (IApplicationActivationManager)new ApplicationActivationManager();
aam.ActivateApplication(aumid, PasteArguments(context.Arguments), ACTIVATEOPTIONS.AO_NONE, out uint pid);
string activationArguments;
string? activationPayloadPath = null;
if (manifest.UsesLaunchActivationArguments)
{
PackagedAppActivationData activationData = PackagedAppActivationArguments.Create(
context.Arguments,
manifest.LocalStateDirectory);
activationArguments = activationData.Arguments;
activationPayloadPath = activationData.PayloadPath;
}
else
{
activationArguments = PasteArguments(context.Arguments);
}

aam.ActivateApplication(aumid, activationArguments, ACTIVATEOPTIONS.AO_NONE, out uint pid);

// 3. Wrap the activated app. AUMID activation cannot set per-launch environment variables, so the
// launcher must bridge the values the host needs from context.EnvironmentVariables (the
// MONITORTOHOST pipe name, correlation id, etc.) another way — e.g. activation arguments or a
// broker process the activated app reads on startup. The handle surfaces the activated PID as
// its (diagnostic-only) Identifier.
return Task.FromResult<ITestHostHandle>(new ActivatedAppHandle(pid));
return Task.FromResult<ITestHostHandle>(new ActivatedAppHandle(pid, activationPayloadPath));
}
```

> Note: enabling the controller→host pipe across the AppContainer sandbox requires a loopback/pipe-ACL
> step (e.g. `CheckNetIsolation LoopbackExempt` or granting the package SID on the pipe). That belongs
> to the package/deploy extension, not the platform.
> step that grants the exact package SID access to the named pipe. Argument delivery and pipe
> authorization are deliberately separate: the reference packaged-app extension restores the opaque
> `LaunchActivatedEventArgs.Arguments` through a reusable bootstrap, while [#10486](https://github.com/microsoft/testfx/issues/10486)
> tracks the least-privilege pipe ACL. `CheckNetIsolation LoopbackExempt` is for network loopback and
> does not authorize named pipes.

For launch activation, Windows documents a 2,048-character argument envelope on
`SecondaryTile.Arguments`, one of the sources surfaced as `LaunchActivatedEventArgs.Arguments`.
The reference extension keeps payloads within that proven envelope inline. Larger MTP argument arrays
spill to a one-shot package `LocalState` file as authenticated ciphertext, with the random per-launch
key carried only in the activation string. This avoids plaintext persistence of filters, runsettings,
or secrets while preserving exact argument order and values.

### 2. Launch under a debugger

Expand Down
2 changes: 1 addition & 1 deletion docs/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ An experimental MTP extension (`Microsoft.Testing.Extensions.Logging`, `[TPEXP]`

### Microsoft.Testing.Extensions.PackagedApp

An MTP extension (`Microsoft.Testing.Extensions.PackagedApp`) that enables testing packaged Windows apps (full-trust MSIX desktop, e.g. packaged WinUI) by registering the layout with the `PackageManager` and activating it by AUMID through the [ITestHostLauncher](#itesthostlauncher) extension point, rather than a plain `Process.Start`. Register via `builder.AddPackagedAppDeployment()`, or simply by referencing the package (its MSBuild props register the hook). The launcher only enables itself when the test application is a packaged layout — a manifest in the app's own directory, or an ancestor `AppxManifest.xml` whose `Application/@Executable` resolves back to the app directory — so referencing it from an **unpackaged** app does not force the test host controller process model or copy the build output; `TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER` (`auto`/`always`/`never`) overrides that decision. Introduced in [PR #9454](https://github.com/microsoft/testfx/pull/9454); AUMID activation added in [PR #9970](https://github.com/microsoft/testfx/pull/9970). See also [ITestHostLauncher](#itesthostlauncher) and [docs/winui-testing.md](winui-testing.md).
An MTP extension (`Microsoft.Testing.Extensions.PackagedApp`) that enables testing packaged Windows apps by registering the layout with the `PackageManager` and activating it by AUMID through the [ITestHostLauncher](#itesthostlauncher) extension point, rather than a plain `Process.Start`. `packagedClassicApp`/`win32App` hosts receive normal `argv` (including classic AppContainer hosts); `windowsApp`/UWP hosts call `PackagedAppExtensions.GetTestApplicationArguments(LaunchActivatedEventArgs.Arguments)` before creating the MTP builder to restore the same logical arguments. Register via `builder.AddPackagedAppDeployment()`, or simply by referencing the package (its MSBuild props register the hook). The launcher only enables itself when the test application is a packaged layout — a manifest in the app's own directory, or an ancestor `AppxManifest.xml` whose `Application/@Executable` resolves back to the app directory — so referencing it from an **unpackaged** app does not force the test host controller process model or copy the build output; `TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER` (`auto`/`always`/`never`) overrides that decision. AppContainer pipe authorization is implemented independently from argument delivery and tracked by [#10486](https://github.com/microsoft/testfx/issues/10486). Introduced in [PR #9454](https://github.com/microsoft/testfx/pull/9454); AUMID activation added in [PR #9970](https://github.com/microsoft/testfx/pull/9970). See also [ITestHostLauncher](#itesthostlauncher) and [docs/winui-testing.md](winui-testing.md).

## N

Expand Down
24 changes: 23 additions & 1 deletion docs/winui-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,32 @@ Requirements and limitations:

- Target a Windows TFM at platform version `10.0.19041.0` or higher (for example `net8.0-windows10.0.19041.0`) so NuGet resolves the Windows asset that contains the register-and-activate path. The plain `net8.0`/`net9.0` asset fails fast with an actionable message instead.
- Registering an unsigned build-output layout requires **Developer Mode** (or sideloading) to be enabled on the machine.
- Only **full-trust packaged desktop** hosts are supported. True UWP/AppContainer hosts are not: activation arguments are not delivered as `argv` there, and the controller pipe is not granted the package SID.
- `packagedClassicApp`/`win32App` hosts receive MTP arguments as normal process `argv`, including classic hosts whose trust level is `appContainer`.
- `windowsApp`/UWP hosts receive one opaque string through `LaunchActivatedEventArgs.Arguments`. Restore the platform argument array with `PackagedAppExtensions.GetTestApplicationArguments(args.Arguments)` before `TestApplication.CreateBuilderAsync`; see [Launch activation](#launch-activation).
- End-to-end UWP/AppContainer execution remains dependent on granting the exact package SID access to the controller named pipe, tracked separately by [#10486](https://github.com/microsoft/testfx/issues/10486). Argument delivery from [#10485](https://github.com/microsoft/testfx/issues/10485) does not weaken that pipe ACL.

See [#9933](https://github.com/microsoft/testfx/issues/9933) for the implementation of this path.

### Launch activation

Unlike a packaged classic/Win32 app, a `windowsApp`/UWP app does not receive the string passed to `IApplicationActivationManager` as `argv`. Windows exposes it as one opaque value on the launch event. Use the package bootstrap from `OnLaunched` rather than adding a project-specific command-line parser. Classic AppContainer hosts continue to use their process arguments:

```csharp
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
string[] cliArgs = PackagedAppExtensions.GetTestApplicationArguments(args.Arguments);
ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(cliArgs);
builder.AddSelfRegisteredExtensions(cliArgs);
using ITestApplication app = await builder.BuildAsync();
Environment.ExitCode = await app.RunAsync();
Exit();
}
```

The launcher and bootstrap share a versioned, length-prefixed format that preserves empty values, whitespace, quotes, backslashes, Unicode, repeated options, and ordering. Arguments that fit the documented 2,048-character Windows launch envelope remain only in the activation string. Larger arrays use a one-shot `LocalState` payload encrypted with a random per-launch key carried in the activation string; the host consumes and deletes it before MTP starts, and the launcher handle removes it if startup fails. Runsettings, filters, and other user input are therefore never persisted in plaintext.

This bootstrap also restores the existing controller connect-back environment handoff before MTP reads it. It cannot by itself authorize the AppContainer token on that pipe; [#10486](https://github.com/microsoft/testfx/issues/10486) is the remaining end-to-end dependency.

## When does the PackagedApp launcher take over?

Registering an *enabled* test host launcher switches the whole run to the test host controller (process restart) model, because a custom launcher only has an effect when an out-of-process test host is started. That is the right trade for a packaged app, but it is pure overhead for an app that just needs `Process.Start`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ internal sealed class ActivatedAppTestHostHandle : ITestHostHandle
{
private readonly Process _process;
private readonly string? _handshakePath;
private readonly string? _activationPayloadPath;

public ActivatedAppTestHostHandle(uint processId, string? handshakePath)
public ActivatedAppTestHostHandle(uint processId, string? handshakePath, string? activationPayloadPath)
{
_process = Process.GetProcessById((int)processId);
_handshakePath = handshakePath;
_activationPayloadPath = activationPayloadPath;
}

public string? Identifier => _process.Id.ToString(CultureInfo.InvariantCulture);
Expand Down Expand Up @@ -55,6 +57,8 @@ public void Dispose()
{
PackagedAppConnectBackHandshake.TryDelete(_handshakePath);
}

PackagedAppActivationArguments.TryDeletePayload(_activationPayloadPath);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ namespace Microsoft.Testing.Extensions.PackagedApp;
/// </summary>
internal sealed class AppxApplicationInfo
{
internal AppxApplicationInfo(string id, string? executable, string appUserModelId)
internal AppxApplicationInfo(string id, string? executable, string appUserModelId, bool usesLaunchActivationArguments)
{
Id = id;
Executable = executable;
AppUserModelId = appUserModelId;
UsesLaunchActivationArguments = usesLaunchActivationArguments;
}

/// <summary>Gets the application id (the manifest's <c>Application/@Id</c>).</summary>
Expand All @@ -33,4 +34,10 @@ internal AppxApplicationInfo(string id, string? executable, string appUserModelI
/// application.
/// </summary>
public string AppUserModelId { get; }

/// <summary>
/// Gets a value indicating whether this application receives launch arguments through
/// <c>LaunchActivatedEventArgs.Arguments</c> instead of process <c>argv</c>.
/// </summary>
public bool UsesLaunchActivationArguments { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -225,26 +225,90 @@ public static AppxManifestInfo ReadFromManifest(Stream manifestStream)

string packageFamilyName = $"{name}_{ComputePublisherId(publisher)}";

bool canRunFullTrust = root is not null
&& root.Descendants()
.Any(static element =>
element.Name.LocalName == "Capability"
&& string.Equals(element.Attribute("Name")?.Value, "runFullTrust", StringComparison.OrdinalIgnoreCase));

List<XElement> applicationElements = root?.Elements().FirstOrDefault(static e => e.Name.LocalName == "Applications")?
.Elements().Where(static e => e.Name.LocalName == "Application")
.ToList()
?? [];

// A package may declare several applications, each with its own id (and AUMID). Capture them
// all so the launcher can resolve the one matching the executable it was asked to launch,
// instead of guessing with the first entry.
List<AppxApplicationInfo> applications = root?.Elements().FirstOrDefault(static e => e.Name.LocalName == "Applications")?
.Elements().Where(static e => e.Name.LocalName == "Application")
var applications = applicationElements
.Select(application =>
{
string? applicationId = application.Attribute("Id")?.Value;
string? executable = application.Attribute("Executable")?.Value;
string? entryPoint = application.Attribute("EntryPoint")?.Value;
string? trustLevel = application.Attributes().FirstOrDefault(static attribute => attribute.Name.LocalName == "TrustLevel")?.Value;
string? runtimeBehavior = application.Attributes().FirstOrDefault(static attribute => attribute.Name.LocalName == "RuntimeBehavior")?.Value;
bool hasFullTrustCompanion = application.Descendants()
.Any(static element =>
element.Name.LocalName == "Extension"
&& string.Equals(element.Attribute("Category")?.Value, "windows.fullTrustProcess", StringComparison.OrdinalIgnoreCase));
return applicationId is null || applicationId.Length == 0
? null
: new AppxApplicationInfo(applicationId, executable, $"{packageFamilyName}!{applicationId}");
: new AppxApplicationInfo(
applicationId,
executable,
$"{packageFamilyName}!{applicationId}",
UsesLaunchActivationArguments(
entryPoint,
trustLevel,
runtimeBehavior,
canUsePackageFullTrustFallback:
canRunFullTrust
&& applicationElements.Count == 1
&& !hasFullTrustCompanion));
})
.OfType<AppxApplicationInfo>()
.ToList()
?? [];
.ToList();

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

private static bool UsesLaunchActivationArguments(
string? entryPoint,
string? trustLevel,
string? runtimeBehavior,
bool canUsePackageFullTrustFallback)
{
// RuntimeBehavior determines the activation model. A packaged classic or Win32 application
// receives process argv even when its sandbox TrustLevel is appContainer.
if (string.Equals(runtimeBehavior, "packagedClassicApp", StringComparison.OrdinalIgnoreCase)
|| string.Equals(runtimeBehavior, "win32App", StringComparison.OrdinalIgnoreCase)
|| string.Equals(entryPoint, "Windows.FullTrustApplication", StringComparison.OrdinalIgnoreCase))
{
return false;
}

if (string.Equals(runtimeBehavior, "windowsApp", StringComparison.OrdinalIgnoreCase))
{
return true;
}

if (string.Equals(trustLevel, "appContainer", StringComparison.OrdinalIgnoreCase))
{
return true;
}

if (string.Equals(trustLevel, "mediumIL", StringComparison.OrdinalIgnoreCase))
{
return false;
}

// Legacy UWP manifests express AppContainer by omission. A package-wide runFullTrust capability
// is a safe fallback only for one application with no full-trust companion extension (the shape
// produced by packaged WinUI). Mixed packages and UWP apps with a windows.fullTrustProcess helper
// need application-specific desktop evidence.
return !canUsePackageFullTrustFallback;
}

/// <summary>
/// Resolves the application whose test host the platform asked to launch, preferring the one whose
/// declared executable resolves exactly to <paramref name="executablePath"/>. A package may declare
Expand Down
Loading
Loading