From a467c796c566b855eb645d6752eedbc00f8204de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 22 Jul 2026 17:56:56 +0200 Subject: [PATCH 01/21] Add HTTP dotnettestcli transport Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 178 ++++++++-- .../InternalAPI/InternalAPI.Unshipped.txt | 4 + .../InternalAPI.Unshipped.txt | 4 + .../InternalAPI/InternalAPI.Unshipped.txt | 4 + .../InternalAPI/InternalAPI.Unshipped.txt | 4 + .../Builder/TestApplication.cs | 2 +- .../CommandLineArgumentsRedactor.cs | 120 +++++++ .../PlatformCommandLineProvider.cs | 99 +++++- .../IPC/NamedPipeConnectionBase.cs | 24 +- .../InternalAPI/InternalAPI.Unshipped.txt | 22 ++ .../DotnetTestPassthroughOutputDevice.cs | 6 - .../Resources/PlatformResources.cs | 18 + .../Resources/PlatformResources.resx | 48 +++ .../Resources/xlf/PlatformResources.cs.xlf | 60 ++++ .../Resources/xlf/PlatformResources.de.xlf | 60 ++++ .../Resources/xlf/PlatformResources.es.xlf | 60 ++++ .../Resources/xlf/PlatformResources.fr.xlf | 60 ++++ .../Resources/xlf/PlatformResources.it.xlf | 60 ++++ .../Resources/xlf/PlatformResources.ja.xlf | 60 ++++ .../Resources/xlf/PlatformResources.ko.xlf | 60 ++++ .../Resources/xlf/PlatformResources.pl.xlf | 60 ++++ .../Resources/xlf/PlatformResources.pt-BR.xlf | 60 ++++ .../Resources/xlf/PlatformResources.ru.xlf | 60 ++++ .../Resources/xlf/PlatformResources.tr.xlf | 60 ++++ .../xlf/PlatformResources.zh-Hans.xlf | 60 ++++ .../xlf/PlatformResources.zh-Hant.xlf | 60 ++++ .../DotnetTest/DotnetTestConnection.cs | 90 +++-- .../ServerMode/DotnetTest/DotnetTestHelper.cs | 26 ++ .../DotnetTest/IPC/DotnetTestDataConsumer.cs | 1 - .../Transport/DotnetTestHttpClient.cs | 229 +++++++++++++ .../BrowserWasmExecutionTests.cs | 324 ++++++++++++++++++ .../HelpInfoAllExtensionsTests.cs | 12 + .../HelpInfoTests.cs | 12 + .../CommandLineArgumentsRedactorTests.cs | 46 +++ .../PlatformCommandLineProviderTests.cs | 138 +++++++- .../IPC/DotnetTestHttpClientTests.cs | 317 +++++++++++++++++ ...icrosoft.Testing.Platform.UnitTests.csproj | 4 + 37 files changed, 2415 insertions(+), 97 deletions(-) create mode 100644 src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs create mode 100644 src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs create mode 100644 test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs create mode 100644 test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index d9bd5efabc..f0b3486fc3 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -1,16 +1,17 @@ -# 004 - `dotnet test` Named-Pipe Protocol +# 004 - `dotnet test` Binary Protocol -This document is the descriptive specification of the **`dotnet test` pipe protocol** (a.k.a. the -`dotnettestcli` protocol): the small, versioned, **binary** protocol used over a named pipe between a -Microsoft.Testing.Platform (MTP) test application and the `dotnet test` implementation shipped in the -.NET SDK. +This document is the descriptive specification of the **`dotnettestcli` protocol**: the small, +versioned, **binary** protocol used between a Microsoft.Testing.Platform (MTP) test application and the +`dotnet test` implementation shipped in the .NET SDK. The protocol can be bootstrapped over the legacy +named-pipe transport or over authenticated HTTP request/reply for environments such as +`browser-wasm`. It is a *different* protocol from the [JSON-RPC server-mode protocol](./001-protocol-intro.md): | | JSON-RPC server mode | `dotnet test` pipe protocol (this doc) | | --- | --- | --- | -| Activation | `--server` (or `--server jsonrpc`) | `--server dotnettestcli --dotnet-test-pipe ` | -| Wire format | JSON-RPC 2.0 over stdio / TCP | Custom length-prefixed **binary** framing over a named pipe | +| Activation | `--server` (or `--server jsonrpc`) | `--server dotnettestcli` plus named-pipe or HTTP bootstrap options | +| Wire format | JSON-RPC 2.0 over stdio / TCP | Custom length-prefixed **binary** frames over a named pipe or HTTP POST bodies | | Shape | Full request/response + notifications, bidirectional | **Push-only** data channel (host → SDK) + auxiliary reverse control channel | | Role of the runner | Server | Client (connects out to the SDK's pipe server) | @@ -24,10 +25,10 @@ It is a *different* protocol from the [JSON-RPC server-mode protocol](./001-prot > `ServerMode/DotnetTest/DotnetTestProtocolContract.props`. > > **Shared wire contract vs. per-repo transport.** Only the *wire contract* (serializer/field IDs, -> message models, serializers, handshake/state constants) is shared source. The **named-pipe transport** -> (framing loop, buffering, connection-loss reactions, unknown-message handling, pipe-name resolution) is -> deliberately **not** shared and is implemented independently on each side (`NamedPipeConnectionBase`, -> `NamedPipeServer`, `NamedPipeClient` are local to testfx). Wherever this document describes transport +> message models, serializers, handshake/state constants) is shared source. The **transport** +> (framing loop, buffering, connection-loss reactions, authentication, unknown-message handling, endpoint +> or pipe-name resolution) is deliberately **not** shared and is implemented independently on each side. +> Wherever this document describes transport > *behavior*, it describes testfx's implementation. The current `dotnet/sdk` data-pipe server implements > its own transport and **diverges** in several places (called out inline below); such behaviors are not > protocol guarantees and must not be assumed to be symmetric across both sides. @@ -37,11 +38,15 @@ It is a *different* protocol from the [JSON-RPC server-mode protocol](./001-prot ## 1. Terminology - **Test application / test host** — the MTP-based test executable (the process being run by - `dotnet test`). In this protocol it is the **pipe client**. + `dotnet test`). In this protocol it is the named-pipe or HTTP **client**. - **SDK / `dotnet test`** — the .NET SDK component that launches test applications and renders their output. It is the **pipe server** (it creates and listens on the data pipe). -- **Data pipe** — the primary named pipe, whose OS name is supplied via `--dotnet-test-pipe`. All - test data flows host → SDK on it. +- **Primary channel** — the host-initiated request/reply channel carrying all handshakes and test data. + It is either the data pipe or the HTTP gateway endpoint. +- **Data pipe** — the legacy primary-channel named pipe, whose OS name is supplied via + `--dotnet-test-pipe`. +- **HTTP gateway** — the SDK-side per-run endpoint that receives authenticated binary HTTP POSTs and + returns one binary reply per request. - **Server-control pipe** — an optional *reverse* named pipe, created and listened on by the SDK, used to push control signals (today only session cancellation) SDK → host. Its name is advertised in the handshake reply. @@ -60,22 +65,38 @@ It is a *different* protocol from the [JSON-RPC server-mode protocol](./001-prot ## 2. Activation & configuration -The SDK starts the test application with: +The legacy SDK bootstrap remains: ```text --server dotnettestcli --dotnet-test-pipe [other options] ``` +For HTTP the SDK starts the test application with: + +```text + --server dotnettestcli + --dotnet-test-transport http + --dotnet-test-http-endpoint + --dotnet-test-http-token + [other options] +``` + Rules and behavior: - `--server` accepts zero or one argument. The value `dotnettestcli` (case-insensitive) selects this protocol. `--server jsonrpc` (or `--server` with no value) selects JSON-RPC server mode instead. -- `--server dotnettestcli` **requires** `--dotnet-test-pipe`; command-line validation fails otherwise - (`PlatformCommandLineDotnetTestCliRequiresPipe`). +- Omitting `--dotnet-test-transport` preserves the legacy behavior: `--dotnet-test-pipe` implicitly + selects the named-pipe transport. +- `--dotnet-test-transport` accepts `pipe` or `http`. Explicit `pipe` requires + `--dotnet-test-pipe`; explicit `http` requires both HTTP options and rejects a pipe option. - `--dotnet-test-pipe` takes **exactly one** argument: the fully-resolved OS pipe name/path the SDK is already listening on (see §3). -- Both options are built-in and **hidden**: the platform omits them from `--help`, so they are only - listed by `--info`. They are not meant for direct end-user use. +- `--dotnet-test-http-endpoint` must be an absolute HTTPS URL. Plain HTTP is accepted only for a + loopback host. User information, query strings, and fragments are rejected. +- `--dotnet-test-http-token` is a non-empty bearer token without whitespace or control characters. + It is per-run bootstrap material, must have enough entropy to be unguessable, and must not be logged. +- All bootstrap options are built-in and **hidden**: the platform omits them from `--help`, so they are + only listed by `--info`. They are pre-launch SDK/host integration options, not direct end-user options. ### Environment variables @@ -87,7 +108,20 @@ Rules and behavior: --- -## 3. Pipe naming & transport +## 3. Transport bootstrap & security + +| Concern | Named pipe | Authenticated HTTP | +| --- | --- | --- | +| Bootstrap | `--dotnet-test-pipe `; implicit default or `--dotnet-test-transport pipe` | `--dotnet-test-transport http` + endpoint + per-run token | +| Access control | Current-user pipe ACL on .NET plus OS pipe naming | HTTPS (except loopback HTTP) plus bearer authentication on every POST | +| Protocol bytes | One complete existing frame per write/read | One complete existing frame per request/response body | +| Ordering | One request/reply under the client lock | One POST in flight under the same ordering lock | +| Versioning | Handshake negotiates the existing serializer/message contract | Identical handshake and versions; HTTP is bootstrap/transport only | +| Disconnect signal | Persistent pipe EOF/write failure | No persistent signal; failure appears on the current or next POST | +| Browser considerations | Unavailable on browser/WASI | `HttpClient`/fetch; gateway must support CORS/PNA preflight | +| Cost | Persistent local stream | HTTP headers, possible preflight, and request setup per protocol message | + +### 3.1 Named pipe The pipe is a `System.IO.Pipes` named pipe opened as `PipeDirection.InOut`, `PipeTransmissionMode.Byte`, `PipeOptions.Asynchronous`, and — on .NET (Core) — `PipeOptions.CurrentUserOnly` @@ -117,11 +151,64 @@ The peer uses it verbatim and never recomputes it. This keeps the SDK and host v > uses the fully-resolved name verbatim, this divergence is harmless for interop — it only changes *where* > the SDK's socket file lands. The test host simply opens a `NamedPipeClient` to `.`/``. +### 3.2 Authenticated HTTP + +The HTTP transport uses ordinary .NET `HttpClient`; on `browser-wasm` this flows through the runtime's +browser `fetch` implementation. It requires no custom JavaScript shim. + +For each host request the client sends: + +```http +POST +Authorization: Bearer +Content-Type: application/octet-stream + + +``` + +The gateway replies with a successful status and `application/octet-stream` body containing exactly one +complete reply frame. The host validates success status, framing, response type, and the absence of a +second frame. A semaphore permits exactly one request in flight, preserving the same ordering and +backpressure as the named pipe. `ConnectAsync` performs no probe: the handshake is the first POST, avoiding +an otherwise redundant browser preflight. + +The SDK-side gateway contract is: + +1. Create a unique endpoint and cryptographically strong bearer token for each launched test-application + run. Do not reuse either across unrelated runs. +2. Authenticate every POST before decoding or dispatching its body. Compare credentials without logging + them, and never place the token in a URL. +3. Accept exactly one existing protocol request frame and return exactly one existing protocol reply + frame. Do not translate serializer IDs, field IDs, framing, or negotiated versions. +4. Serialize handling per host connection/run. The host already limits itself to one request in flight; + the gateway must not reorder requests across asynchronous handlers. +5. Keep the endpoint available for the entire run and return explicit non-success status codes for + authentication or gateway failures. There is no health polling. +6. Bound request and response sizes, reject malformed or trailing frames, and avoid buffering/logging + bodies in diagnostics because protocol payloads can contain test names, paths, and output. + +#### Browser CORS and Private Network Access + +An actual browser applies CORS, and may apply Private Network Access (PNA), even when a Node-hosted +`browser-wasm` acceptance test does not. The gateway must: + +- allow the test application's exact origin (not `*` when credentials or policy require a specific + origin); +- allow `POST`, `Authorization`, and `Content-Type`; +- answer `OPTIONS` preflight without requiring the bearer header that the browser has not sent yet; +- include the matching CORS response headers on success and error responses; +- account for PNA preflight when a public or secure origin targets a loopback/private-network gateway + (including `Access-Control-Allow-Private-Network: true` where the browser requires it); and +- use HTTPS for non-loopback endpoints to avoid mixed-content and bootstrap validation failures. + +This adds preflight and per-request HTTP overhead compared with a persistent WebSocket or named pipe, but +substantially reduces browser-specific host code and reuses the platform `HttpClient` stack. + --- ## 4. Framing -Every message — request and reply, on both the data and control pipes — is a single frame: +Every message — request and reply, on the primary channel and control pipe — is a single frame: ```text +-------------------------+------------------------+------------------------+ @@ -283,8 +370,8 @@ change or reuse an ID. ## 7. Request/reply model -Although data flows host → SDK, the transport is still **request/reply** at the frame level: the client -(host) writes one request frame and blocks reading exactly one reply frame before sending the next. This +Although data flows host → SDK, the primary channel is entirely **host-initiated request/reply**: the +host sends one request frame and waits for exactly one reply frame before sending the next. This serializes all sends behind a single lock (`RequestReplyAsync` holds a `SemaphoreSlim`), so messages are delivered in order. @@ -294,14 +381,15 @@ delivered in order. - The one exception is the **handshake**: the SDK replies with a `HandshakeMessage` (§9), not a `VoidResponse`. -The protocol is therefore "push-only" from a *semantic* standpoint (the SDK never initiates a data -request), but every push is acknowledged. +The protocol is therefore "push-only" from a *semantic* standpoint (the SDK never initiates a primary +channel request), but every push is acknowledged. HTTP needs no polling because there is no SDK-initiated +primary-channel traffic to retrieve. ```mermaid sequenceDiagram participant H as Test host (client) participant S as dotnet test SDK (server) - Note over H,S: data pipe, one in-flight message at a time + Note over H,S: named pipe or HTTP, one in-flight message at a time H->>S: DiscoveredTestMessages / TestResultMessages / ... S-->>H: VoidResponse H->>S: next message @@ -312,7 +400,7 @@ sequenceDiagram ## 8. Handshake & version negotiation -Before any data is sent, the host performs one handshake round-trip on the data pipe. +Before any data is sent, the host performs one handshake round-trip on the selected primary transport. ### 8.1 Host → SDK: `HandshakeMessage` (request) @@ -531,7 +619,7 @@ Compatibility rules / assumptions: ## 11. Connection-loss behavior (assumptions) -The connection-loss semantics differ by pipe and are a core part of the contract. +Connection-loss detection differs by transport and is a core integration consideration. **Data pipe (`exitProcessOnConnectionLoss: true`).** If the SDK disconnects there is no way to recover, so the host process **exits abnormally** with exit code `GenericFailure` (1). This happens on two paths: @@ -540,6 +628,14 @@ while sending a request. On the **read-EOF** path the host also writes a diagnos exiting; the **write-failure** path calls `Exit(GenericFailure)` directly **without** that diagnostic. This is deliberate: if the user kills `dotnet.exe`, the test host must die too rather than orphan. +**HTTP primary channel.** HTTP has no persistent session whose closure can notify an otherwise idle host. +Gateway loss, DNS/network failure, authentication expiry, or a malformed response is detected by the +current POST, or by the next POST if the host was idle. A failed request fails the host operation; there +is no transparent retry because retrying after an ambiguous network failure could duplicate a message. +Cancellation is passed to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch +without converting expected cancellation into a connection-loss failure. Disposal cancels no completed +messages and prevents later use. + **Server-control pipe (`exitProcessOnConnectionLoss: false`).** A dropped control pipe must **not** kill the test host. This listener runs *inside the test host* as the control-pipe **client**, so an unexpected early close means the **SDK/server peer went away**; the listener treats that as a @@ -567,6 +663,13 @@ Purpose: let the SDK push a control signal (today only session cancellation, e.g `--maximum-failed-tests` or `--timeout`) to the running test host, even while the host is otherwise silent. +This reverse channel is explicitly **separate from the HTTP primary transport**. An HTTP handshake reply +does not activate `ServerControlPipeName`, because named pipes are unavailable to `browser-wasm` and the +host must not invent polling on the primary endpoint. A future browser-capable reverse-control transport +requires its own capability/bootstrap contract and is out of scope for the HTTP request/reply gateway. +Host-local cancellation (for example, the test application's own timeout token) still cancels an +in-flight HTTP POST normally. + Setup and flow: 1. In its handshake reply the SDK advertises `ServerControlPipeName` (a pipe it is already listening on). @@ -602,18 +705,18 @@ feature simply disabled. ## 13. End-to-end lifecycle -The host builder creates a `DotnetTestConnection` and calls `AfterCommonServiceSetupAsync`, which — when -`--server dotnettestcli` + `--dotnet-test-pipe` are present — sets/reads the Execution ID env var and -connects the data-pipe client. The overall flow: +The host builder creates a `DotnetTestConnection` and calls `AfterCommonServiceSetupAsync`, which selects +the legacy named pipe or authenticated HTTP from the hidden bootstrap options, sets/reads the Execution ID +environment variable, and initializes the client. The overall flow: ```mermaid sequenceDiagram participant SDK as dotnet test SDK participant Host as Test host - SDK->>SDK: create & listen on data pipe - SDK->>Host: launch: --server dotnettestcli --dotnet-test-pipe [--list-tests|--help|...] - Host->>SDK: connect data pipe + SDK->>SDK: create data pipe or per-run HTTP gateway + token + SDK->>Host: launch with named-pipe or HTTP bootstrap [--list-tests|--help|...] + Host->>SDK: connect pipe, or initialize HttpClient (no probe) Host->>SDK: HandshakeMessage (request) SDK-->>Host: HandshakeMessage (reply: negotiated version, [IsIDE], [ServerControlPipeName]) @@ -623,7 +726,7 @@ sequenceDiagram Host->>SDK: CommandLineOptionMessages SDK-->>Host: VoidResponse else run / discover - opt control channel advertised + opt named-pipe transport and control channel advertised Host->>SDK: connect control pipe + park WaitForServerControlRequest end Host->>SDK: TestSessionEvent(TestSessionStart) @@ -665,11 +768,12 @@ own Execution ID (see §1/§2). | Constants (states, versions, handshake props) | `ServerMode/DotnetTest/IPC/Constants.cs` | | Serializer registry | `IPC/Serializers/RegisterSerializers.cs` | | Serializer primitives / envelope | `IPC/Serializers/BaseSerializer.cs`, `NamedPipeSerializer.cs` | -| Framing / transport | `IPC/NamedPipeConnectionBase.cs`, `NamedPipeServer.cs`, `NamedPipeClient.cs` | +| Framing / named-pipe transport | `IPC/NamedPipeConnectionBase.cs`, `NamedPipeServer.cs`, `NamedPipeClient.cs` | +| HTTP primary transport | `ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs` | | Pipe naming | `NamedPipeServer.GetPipeName` | | Message models | `ServerMode/DotnetTest/IPC/Models/*.cs`, `IPC/Models/*.cs` | | Message serializers | `ServerMode/DotnetTest/IPC/Serializers/*.cs` | | Host connection / handshake / control channel | `ServerMode/DotnetTest/DotnetTestConnection.cs` | | Host data consumer (state → message mapping) | `ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs` | | Shared-source manifest (vendored to dotnet/sdk) | `ServerMode/DotnetTest/DotnetTestProtocolContract.props` | -| Black-box protocol reference / tests | `test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/*`, `test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/*` | +| Black-box protocol reference / tests | `test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/DotnetTestPipe/*`, `BrowserWasmExecutionTests.cs`, `test/UnitTests/Microsoft.Testing.Platform.DotnetTestProtocolContract.UnitTests/*` | diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt index 5a42e4a96e..5da6caa7e6 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt @@ -15,3 +15,7 @@ static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteExecutionS static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteListPayload(System.IO.Stream! stream, ushort fieldId, T[]? list, System.Action! writeItem) -> void const Microsoft.Testing.Platform.IPC.FailedTestResultMessageFieldsId.Expected = 10 -> ushort const Microsoft.Testing.Platform.IPC.FailedTestResultMessageFieldsId.Actual = 11 -> ushort +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken, int maximumFrameSize = 2147483647) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/src/Platform/Microsoft.Testing.Extensions.MSBuild/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.MSBuild/InternalAPI.Unshipped.txt index eab62e52eb..258823f224 100644 --- a/src/Platform/Microsoft.Testing.Extensions.MSBuild/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.MSBuild/InternalAPI.Unshipped.txt @@ -14,3 +14,7 @@ static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteExecutionS static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteListPayload(System.IO.Stream! stream, ushort fieldId, T[]? list, System.Action! writeItem) -> void const Microsoft.Testing.Platform.IPC.FailedTestResultMessageFieldsId.Expected = 10 -> ushort const Microsoft.Testing.Platform.IPC.FailedTestResultMessageFieldsId.Actual = 11 -> ushort +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken, int maximumFrameSize = 2147483647) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt index 64777f2fb2..ec3bf29aaf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/InternalAPI/InternalAPI.Unshipped.txt @@ -18,3 +18,7 @@ static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteExecutionS static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteListPayload(System.IO.Stream! stream, ushort fieldId, T[]? list, System.Action! writeItem) -> void const Microsoft.Testing.Platform.IPC.FailedTestResultMessageFieldsId.Expected = 10 -> ushort const Microsoft.Testing.Platform.IPC.FailedTestResultMessageFieldsId.Actual = 11 -> ushort +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken, int maximumFrameSize = 2147483647) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Extensions.TrxReport/InternalAPI/InternalAPI.Unshipped.txt index ef54e98ea1..b7e672e068 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/InternalAPI/InternalAPI.Unshipped.txt @@ -68,3 +68,7 @@ Microsoft.Testing.Extensions.MergeOutputFileHelper static Microsoft.Testing.Extensions.MergeOutputFileHelper.BuildCaseFoldedProbePath(string! directory, string! probeFileName) -> string! static Microsoft.Testing.Extensions.MergeOutputFileHelper.EnsureOutputDoesNotAliasInput(System.Collections.Generic.IReadOnlyList! inputPaths, string! outputPath) -> void static Microsoft.Testing.Extensions.MergeOutputFileHelper.WriteViaTemporarySiblingAsync(string! outputPath, System.Func! writeToTempAsync) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken, int maximumFrameSize = 2147483647) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index c58fc6b5d4..6658e72576 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -186,7 +186,7 @@ private static async Task LogInformationAsync( string moduleName = testApplicationModuleInfo.GetDisplayName(); await logger.LogInformationAsync($"Test module: {moduleName}").ConfigureAwait(false); - await logger.LogInformationAsync($"Command line arguments: '{(args.Length == 0 ? string.Empty : args.Aggregate((a, b) => $"{a} {b}"))}'").ConfigureAwait(false); + await logger.LogInformationAsync($"Command line arguments: '{CommandLineArgumentsRedactor.Redact(args)}'").ConfigureAwait(false); StringBuilder machineInfo = new(); #pragma warning disable RS0030 // Do not use banned APIs diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs new file mode 100644 index 0000000000..031e339112 --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Testing.Platform.CommandLine; + +internal static class CommandLineArgumentsRedactor +{ + private const string RedactedPlaceholder = "***REDACTED***"; + + public static string Redact(string[] args) + { + if (args.Length == 0) + { + return string.Empty; + } + + string[] redacted = new string[args.Length]; + bool redactNextValue = false; + bool sanitizeNextEndpoint = false; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + if (TryParseOption(arg, out string? prefix, out string? name, out string? delimiter, out string? inlineValue)) + { + if (redactNextValue) + { + redacted[i] = RedactedPlaceholder; + redactNextValue = false; + continue; + } + + bool isToken = PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); + bool isEndpoint = PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); + if (isToken) + { + redacted[i] = inlineValue is null + ? arg + : $"{prefix}{name}{delimiter}{RedactedPlaceholder}"; + redactNextValue = inlineValue is null; + sanitizeNextEndpoint = false; + } + else if (isEndpoint) + { + redacted[i] = inlineValue is null + ? arg + : $"{prefix}{name}{delimiter}{SanitizeEndpoint(inlineValue)}"; + sanitizeNextEndpoint = inlineValue is null; + redactNextValue = false; + } + else + { + redacted[i] = arg; + redactNextValue = false; + sanitizeNextEndpoint = false; + } + + continue; + } + + if (redactNextValue) + { + redacted[i] = RedactedPlaceholder; + redactNextValue = false; + } + else if (sanitizeNextEndpoint) + { + redacted[i] = SanitizeEndpoint(arg); + sanitizeNextEndpoint = false; + } + else + { + redacted[i] = arg; + } + } + + return string.Join(" ", redacted); + } + + private static bool TryParseOption( + string arg, + [NotNullWhen(true)] out string? prefix, + [NotNullWhen(true)] out string? name, + out string? delimiter, + out string? inlineValue) + { + prefix = null; + name = null; + delimiter = null; + inlineValue = null; + + bool isDoubleDash = arg.Length > 2 && arg[0] == '-' && arg[1] == '-' && arg[2] != '-'; + bool isSingleDash = !isDoubleDash && arg.Length > 1 && arg[0] == '-' && arg[1] != '-'; + if (!isDoubleDash && !isSingleDash) + { + return false; + } + + prefix = isDoubleDash ? "--" : "-"; + string withoutPrefix = arg[prefix.Length..]; + int delimiterIndex = withoutPrefix.IndexOfAny(['=', ':']); + if (delimiterIndex == -1) + { + name = withoutPrefix; + return true; + } + + name = withoutPrefix[..delimiterIndex]; + delimiter = withoutPrefix[delimiterIndex].ToString(); + inlineValue = withoutPrefix[(delimiterIndex + 1)..]; + return true; + } + + private static string SanitizeEndpoint(string endpoint) + => Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) + && uri.Scheme is "http" or "https" + && RoslynString.IsNullOrEmpty(uri.UserInfo) + ? uri.GetLeftPart(UriPartial.Authority) + : RedactedPlaceholder; +} diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index 2306aae0dd..f1f742596f 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -27,6 +27,7 @@ internal sealed class PlatformCommandLineProvider : CommandLineOptionsProviderBa private static readonly string SupportedDiscoverTestsValues = $"'{DiscoverTestsTextArgument}', '{DiscoverTestsJsonArgument}'"; private static readonly string SupportedServerProtocolValues = $"'{JsonRpcProtocolName}', '{DotnetTestCliProtocolName}'"; + private static readonly string SupportedDotNetTestTransportValues = $"'{DotNetTestTransportPipeArgument}', '{DotNetTestTransportHttpArgument}'"; public const string ResultDirectoryOptionKey = "results-directory"; public const string IgnoreExitCodeOptionKey = "ignore-exit-code"; public const string MinimumExpectedTestsOptionKey = "minimum-expected-tests"; @@ -45,6 +46,11 @@ internal sealed class PlatformCommandLineProvider : CommandLineOptionsProviderBa public const string JsonRpcProtocolName = "jsonrpc"; public const string DotNetTestPipeOptionKey = "dotnet-test-pipe"; public const string DotnetTestCliProtocolName = "dotnettestcli"; + public const string DotNetTestTransportOptionKey = "dotnet-test-transport"; + public const string DotNetTestTransportPipeArgument = "pipe"; + public const string DotNetTestTransportHttpArgument = "http"; + public const string DotNetTestHttpEndpointOptionKey = "dotnet-test-http-endpoint"; + public const string DotNetTestHttpTokenOptionKey = "dotnet-test-http-token"; private static readonly string[] VerbosityOptions = ["Trace", "Debug", "Information", "Warning", "Error", "Critical"]; @@ -81,7 +87,10 @@ internal sealed class PlatformCommandLineProvider : CommandLineOptionsProviderBa new(SkipBuildersNumberCheckOptionKey, PlatformResources.PlatformCommandLineSkipBuildersNumberCheckOptionDescription, ArgumentArity.Zero, true, isBuiltIn: true), new(NoBannerOptionKey, PlatformResources.PlatformCommandLineNoBannerOptionDescription, ArgumentArity.ZeroOrOne, true, isBuiltIn: true), new(TestHostControllerPIDOptionKey, PlatformResources.PlatformCommandLineTestHostControllerPIDOptionDescription, ArgumentArity.ZeroOrOne, true, isBuiltIn: true), - new(DotNetTestPipeOptionKey, PlatformResources.PlatformCommandLineDotnetTestPipe, ArgumentArity.ExactlyOne, true, isBuiltIn: true) + new(DotNetTestHttpEndpointOptionKey, PlatformResources.PlatformCommandLineDotnetTestHttpEndpointOptionDescription, ArgumentArity.ExactlyOne, true, isBuiltIn: true), + new(DotNetTestHttpTokenOptionKey, PlatformResources.PlatformCommandLineDotnetTestHttpTokenOptionDescription, ArgumentArity.ExactlyOne, true, isBuiltIn: true), + new(DotNetTestPipeOptionKey, PlatformResources.PlatformCommandLineDotnetTestPipe, ArgumentArity.ExactlyOne, true, isBuiltIn: true), + new(DotNetTestTransportOptionKey, PlatformResources.PlatformCommandLineDotnetTestTransportOptionDescription, ArgumentArity.ExactlyOne, true, isBuiltIn: true) ]; public PlatformCommandLineProvider() @@ -121,6 +130,32 @@ public override Task ValidateOptionArgumentsAsync(CommandLineO return ValidationResult.InvalidTask(string.Format(CultureInfo.InvariantCulture, PlatformResources.PlatformCommandLineServerInvalidArgument, arguments[0], SupportedServerProtocolValues)); } + if (commandOption.Name == DotNetTestTransportOptionKey + && !DotNetTestTransportPipeArgument.Equals(arguments[0], StringComparison.OrdinalIgnoreCase) + && !DotNetTestTransportHttpArgument.Equals(arguments[0], StringComparison.OrdinalIgnoreCase)) + { + return ValidationResult.InvalidTask(string.Format( + CultureInfo.InvariantCulture, + PlatformResources.PlatformCommandLineDotnetTestTransportInvalid, + arguments[0], + SupportedDotNetTestTransportValues)); + } + + if (commandOption.Name == DotNetTestHttpEndpointOptionKey + && !IsValidHttpEndpoint(arguments[0])) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpEndpointInvalid); + } + + if (commandOption.Name == DotNetTestHttpTokenOptionKey + && (RoslynString.IsNullOrWhiteSpace(arguments[0]) + || arguments[0].Any(char.IsWhiteSpace) + || arguments[0].Any(char.IsControl) + || !System.Net.Http.Headers.AuthenticationHeaderValue.TryParse($"Bearer {arguments[0]}", out _))) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpTokenInvalid); + } + if (commandOption.Name == ClientPortOptionKey && (!int.TryParse(arguments[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int port) || port < System.Net.IPEndPoint.MinPort @@ -207,6 +242,16 @@ private static Task IsMinimumExpectedTestsOptionValidAsync(Com ? ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineMinimumExpectedTestsOptionSingleArgument) : ValidationResult.ValidTask; + private static bool IsValidHttpEndpoint(string value) + => Uri.TryCreate(value, UriKind.Absolute, out Uri? endpoint) + && endpoint is not null + && endpoint.Scheme is "http" or "https" + && endpoint.Host.Length > 0 + && endpoint.UserInfo.Length == 0 + && endpoint.Query.Length == 0 + && endpoint.Fragment.Length == 0 + && (endpoint.Scheme == Uri.UriSchemeHttps || endpoint.IsLoopback); + public override Task ValidateCommandLineOptionsAsync(ICommandLineOptions commandLineOptions) { if (!commandLineOptions.IsOptionSet(DiagnosticOptionKey)) @@ -234,16 +279,54 @@ public override Task ValidateCommandLineOptionsAsync(ICommandL return ValidationResult.InvalidTask(PlatformResources.OnlyOneFilterSupported); } - // The '--server dotnettestcli' protocol path requires '--dotnet-test-pipe' to connect to the - // dotnet test pipe. Without it, the dotnet test connection silently never activates and the - // application falls back to console mode, leading to confusing behavior. Both options are - // internal and are expected to be passed together by 'dotnet test'. + // The '--server dotnettestcli' protocol path requires exactly one pre-launch transport: either the + // legacy named pipe (implied by '--dotnet-test-pipe') or authenticated HTTP. if (commandLineOptions.TryGetOptionArgumentList(ServerOptionKey, out string[]? serverProtocolArgs) && serverProtocolArgs is { Length: 1 } - && DotnetTestCliProtocolName.Equals(serverProtocolArgs[0], StringComparison.OrdinalIgnoreCase) - && !commandLineOptions.IsOptionSet(DotNetTestPipeOptionKey)) + && DotnetTestCliProtocolName.Equals(serverProtocolArgs[0], StringComparison.OrdinalIgnoreCase)) { - return ValidationResult.InvalidTask(string.Format(CultureInfo.InvariantCulture, PlatformResources.PlatformCommandLineDotnetTestCliRequiresPipe, DotnetTestCliProtocolName, DotNetTestPipeOptionKey)); + bool hasPipe = commandLineOptions.IsOptionSet(DotNetTestPipeOptionKey); + bool hasTransport = commandLineOptions.TryGetOptionArgumentList(DotNetTestTransportOptionKey, out string[]? transportArguments) + && transportArguments is { Length: 1 }; + bool isPipeTransport = hasTransport + && DotNetTestTransportPipeArgument.Equals(transportArguments![0], StringComparison.OrdinalIgnoreCase); + bool isHttpTransport = hasTransport + && DotNetTestTransportHttpArgument.Equals(transportArguments![0], StringComparison.OrdinalIgnoreCase); + bool hasHttpEndpoint = commandLineOptions.IsOptionSet(DotNetTestHttpEndpointOptionKey); + bool hasHttpToken = commandLineOptions.IsOptionSet(DotNetTestHttpTokenOptionKey); + + if (hasPipe && (isHttpTransport || hasHttpEndpoint || hasHttpToken)) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestTransportConflict); + } + + if (!isHttpTransport && (hasHttpEndpoint || hasHttpToken)) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpOptionsRequireTransport); + } + + if (!hasPipe && !isHttpTransport) + { + return ValidationResult.InvalidTask( + isPipeTransport + ? string.Format(CultureInfo.InvariantCulture, PlatformResources.PlatformCommandLineDotnetTestCliRequiresPipe, DotnetTestCliProtocolName, DotNetTestPipeOptionKey) + : PlatformResources.PlatformCommandLineDotnetTestCliRequiresTransport); + } + + if (isHttpTransport && (!hasHttpEndpoint || !hasHttpToken)) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken); + } + + if (hasPipe && OperatingSystem.IsBrowser()) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLinePipeTransportNotSupportedOnBrowser); + } + + if (hasPipe && OperatingSystem.IsWasi()) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLinePipeTransportNotSupportedOnWasi); + } } if (commandLineOptions.IsOptionSet(DiagnosticFileLoggerSynchronousWriteOptionKey)) diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs index b183ca3418..1d9b9fc376 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs @@ -30,10 +30,7 @@ internal abstract class NamedPipeConnectionBase : NamedPipeBase /// 4-byte size header and 4-byte serializer-ID prefix, writes the frame to , /// flushes, and (on Windows) waits for the pipe to drain. /// -#if !MTP_MSBUILD_TASKS - [UnsupportedOSPlatform("browser")] -#endif - protected async Task WriteMessageAsync(PipeStream stream, INamedPipeSerializer serializer, object message, CancellationToken cancellationToken) + protected async Task WriteMessageAsync(Stream stream, INamedPipeSerializer serializer, object message, CancellationToken cancellationToken) { // Serialize the message body _serializationBuffer.Position = 0; @@ -103,9 +100,9 @@ protected async Task WriteMessageAsync(PipeStream stream, INamedPipeSerializer s await stream.WriteAsync(_messageBuffer.GetBuffer(), 0, (int)_messageBuffer.Position, cancellationToken).ConfigureAwait(false); #endif await stream.FlushAsync(cancellationToken).ConfigureAwait(false); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && stream is PipeStream pipeStream) { - stream.WaitForPipeDrain(); + pipeStream.WaitForPipeDrain(); } } finally @@ -119,12 +116,13 @@ protected async Task WriteMessageAsync(PipeStream stream, INamedPipeSerializer s /// Reads one complete framed message from , deserializes it, and returns /// the result. Returns when the stream reaches EOF (peer disconnected). /// -#if !MTP_MSBUILD_TASKS - [UnsupportedOSPlatform("browser")] -#endif - protected async Task ReadNextMessageAsync(PipeStream stream, CancellationToken cancellationToken) + protected async Task ReadNextMessageAsync( + Stream stream, + CancellationToken cancellationToken, + int maximumFrameSize = int.MaxValue) { _messageBuffer.Position = 0; + _messageBuffer.SetLength(0); try { @@ -149,6 +147,11 @@ protected async Task WriteMessageAsync(PipeStream stream, INamedPipeSerializer s } int currentMessageSize = BitConverter.ToInt32(_readBuffer, 0); + if (currentMessageSize < sizeof(int) || currentMessageSize > maximumFrameSize - sizeof(int)) + { + throw new IOException($"The transport returned an invalid response payload length of {currentMessageSize} bytes."); + } + int missingBytesToReadOfWholeMessage = currentMessageSize; // Read the message body in chunks, using _readBuffer as a transfer buffer. @@ -184,6 +187,7 @@ protected async Task WriteMessageAsync(PipeStream stream, INamedPipeSerializer s finally { _messageBuffer.Position = 0; + _messageBuffer.SetLength(0); } } diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index bdfe0215e4..6be17ef5ca 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -136,6 +136,28 @@ Microsoft.Testing.Platform.Services.ClientInfoService.Deconstruct(out string! Id override Microsoft.Testing.Platform.Services.ClientCapabilitiesService.Equals(object? obj) -> bool override Microsoft.Testing.Platform.Services.ClientCapabilitiesService.GetHashCode() -> int override Microsoft.Testing.Platform.Services.ClientCapabilitiesService.ToString() -> string! +const Microsoft.Testing.Platform.CommandLine.PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey = "dotnet-test-http-endpoint" -> string! +const Microsoft.Testing.Platform.CommandLine.PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey = "dotnet-test-http-token" -> string! +const Microsoft.Testing.Platform.CommandLine.PlatformCommandLineProvider.DotNetTestTransportHttpArgument = "http" -> string! +const Microsoft.Testing.Platform.CommandLine.PlatformCommandLineProvider.DotNetTestTransportOptionKey = "dotnet-test-transport" -> string! +const Microsoft.Testing.Platform.CommandLine.PlatformCommandLineProvider.DotNetTestTransportPipeArgument = "pipe" -> string! +Microsoft.Testing.Platform.CommandLine.CommandLineArgumentsRedactor +Microsoft.Testing.Platform.DotnetTestTransportKind +Microsoft.Testing.Platform.DotnetTestTransportKind.Http = 1 -> Microsoft.Testing.Platform.DotnetTestTransportKind +Microsoft.Testing.Platform.DotnetTestTransportKind.NamedPipe = 0 -> Microsoft.Testing.Platform.DotnetTestTransportKind +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.ConnectAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.Dispose() -> void +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.DotnetTestHttpClient(System.Uri! endpoint, string! authToken, System.Net.Http.HttpClient! httpClient, bool disposeHttpClient) -> void +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.DotnetTestHttpClient(System.Uri! endpoint, string! authToken) -> void +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.IsConnected.get -> bool +Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.RequestReplyAsync(TRequest request, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken, int maximumFrameSize = 2147483647) -> System.Threading.Tasks.Task! +Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +static Microsoft.Testing.Platform.CommandLine.CommandLineArgumentsRedactor.Redact(string![]! args) -> string! +static Microsoft.Testing.Platform.DotnetTestHelper.TryGetDotnetTestTransport(this Microsoft.Testing.Platform.CommandLine.CommandLineHandler! commandLineHandler, out Microsoft.Testing.Platform.DotnetTestTransportKind transport) -> bool +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +*REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.ReadFields(System.IO.Stream! stream, System.Func! tryReadField) -> void static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.TryReadExecutionScopedField(System.IO.Stream! stream, ushort fieldId, int fieldSize, ref string? executionId, ref string? instanceId) -> bool static Microsoft.Testing.Platform.IPC.Serializers.BaseSerializer.WriteExecutionScopedHeader(System.IO.Stream! stream, string? executionId, string? instanceId, ushort payloadFieldCount) -> void diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs index 3bb359f492..4a7bb62bbc 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/DotnetTestPassthroughOutputDevice.cs @@ -87,9 +87,6 @@ public async Task DisplayAsync(IOutputDeviceDataProducer producer, IOutputDevice private async Task ForwardAzureDevOpsAsync(AzureDevOpsCommandOutputDeviceData commandData, CancellationToken cancellationToken) { - // The dotnet test pipe protocol (DotnetTestConnection) is never active on browser, so the - // browser-unsupported members below are unreachable there; suppress CA1416 accordingly. -#pragma warning disable CA1416 // Validate platform compatibility if (_serviceProvider.GetService() is not DotnetTestConnection connection || !connection.IsLogForwardingSupported) { @@ -97,12 +94,10 @@ private async Task ForwardAzureDevOpsAsync(AzureDevOpsCommandOutputDeviceData co } await connection.SendMessageAsync(new AzureDevOpsLogMessage(GetExecutionId(), DotnetTestConnection.InstanceId, commandData.Text)).ConfigureAwait(false); -#pragma warning restore CA1416 // Validate platform compatibility } private async Task ForwardDisplayMessageAsync(byte level, string text, CancellationToken cancellationToken) { -#pragma warning disable CA1416 // Validate platform compatibility if (_serviceProvider.GetService() is not DotnetTestConnection connection || !connection.IsDisplayMessageForwardingSupported) { @@ -110,7 +105,6 @@ private async Task ForwardDisplayMessageAsync(byte level, string text, Cancellat } await connection.SendMessageAsync(new DisplayMessage(GetExecutionId(), DotnetTestConnection.InstanceId, level, text)).ConfigureAwait(false); -#pragma warning restore CA1416 // Validate platform compatibility } private string? GetExecutionId() diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.cs b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.cs index b06cd4e0c0..28420e6329 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.cs +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.cs @@ -53,6 +53,24 @@ internal static partial class PlatformResources internal static string @PlatformCommandLineDotnetTestCliRequiresPipe => GetResourceString("PlatformCommandLineDotnetTestCliRequiresPipe"); + internal static string @PlatformCommandLineDotnetTestTransportInvalid => GetResourceString("PlatformCommandLineDotnetTestTransportInvalid"); + + internal static string @PlatformCommandLineDotnetTestHttpEndpointInvalid => GetResourceString("PlatformCommandLineDotnetTestHttpEndpointInvalid"); + + internal static string @PlatformCommandLineDotnetTestHttpTokenInvalid => GetResourceString("PlatformCommandLineDotnetTestHttpTokenInvalid"); + + internal static string @PlatformCommandLineDotnetTestTransportConflict => GetResourceString("PlatformCommandLineDotnetTestTransportConflict"); + + internal static string @PlatformCommandLineDotnetTestHttpOptionsRequireTransport => GetResourceString("PlatformCommandLineDotnetTestHttpOptionsRequireTransport"); + + internal static string @PlatformCommandLineDotnetTestCliRequiresTransport => GetResourceString("PlatformCommandLineDotnetTestCliRequiresTransport"); + + internal static string @PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken => GetResourceString("PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken"); + + internal static string @PlatformCommandLinePipeTransportNotSupportedOnBrowser => GetResourceString("PlatformCommandLinePipeTransportNotSupportedOnBrowser"); + + internal static string @PlatformCommandLinePipeTransportNotSupportedOnWasi => GetResourceString("PlatformCommandLinePipeTransportNotSupportedOnWasi"); + internal static string @PlatformCommandLineExitOnProcessExitSingleArgument => GetResourceString("PlatformCommandLineExitOnProcessExitSingleArgument"); internal static string @PlatformCommandLineDiagnosticOptionIsMissing => GetResourceString("PlatformCommandLineDiagnosticOptionIsMissing"); diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx index e89aed2514..f3995b2dce 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx +++ b/src/Platform/Microsoft.Testing.Platform/Resources/PlatformResources.resx @@ -607,6 +607,54 @@ The default is TestResults in the directory that contains the test application.< dotnet test pipe. {Locked="dotnet test"} + + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Use a tree filter to filter down the tests to execute diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf index bd7bba562c..193779c614 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.cs.xlf @@ -621,11 +621,61 @@ Volitelně přijímá hodnotu „text“ (výchozí výstup čitelný pro člov Parametr „--server {0}“ vyžaduje zadání hodnoty „--{1}“. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test kanál. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Volitelně přijímá hodnotu „text“ (výchozí výstup čitelný pro člov Nezobrazovat úvodní banner, zprávu o autorských právech ani banner telemetrie + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Zadejte port serveru. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf index 617918e2f8..a6a9db2efb 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.de.xlf @@ -621,11 +621,61 @@ Akzeptiert optional „text“ (die standardmäsige lesbare Ausgabe) oder „jso „--server {0}' reqiueres'--{1}“ muss angegeben werden. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test pipe. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Akzeptiert optional „text“ (die standardmäsige lesbare Ausgabe) oder „jso Zeigen Sie das Startbanner, die Copyrightmeldung oder das Telemetriebanner nicht an. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Geben Sie den Port des Servers an. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf index e0960d9b39..ad2ca0f806 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.es.xlf @@ -621,11 +621,61 @@ Opcionalmente, acepta "text" (la salida legible por el usuario predeterminada) o La opción "--server {0}" requiere que se especifique "--{1}". {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. canalización de dotnet test {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Opcionalmente, acepta "text" (la salida legible por el usuario predeterminada) o No muestre el banner de inicio, el mensaje de copyright o el banner de telemetría. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Especifique el puerto del servidor. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf index 13f2c0a0c7..23004406fc 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.fr.xlf @@ -621,11 +621,61 @@ Accepte éventuellement « text » (sortie lisible par l’humain par défaut) « --server {0} » nécessite la spécification de « --{1} ». {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. canal de dotnet test. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Accepte éventuellement « text » (sortie lisible par l’humain par défaut) Ne pas afficher la bannière de démarrage, le message de copyright ou la bannière de télémétrie. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Spécifier le port du serveur. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf index d1d0ac4313..ebcddba59e 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.it.xlf @@ -621,11 +621,61 @@ Facoltativamente accetta ''text'' (output leggibile predefinito) o ''json'' per '--server {0}' richiede che sia specificato '--{1}'. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. pipe di dotnet test. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Facoltativamente accetta ''text'' (output leggibile predefinito) o ''json'' per Non visualizzare il banner di avvio, il messaggio di copyright o il banner di telemetria. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Specifica la porta del server. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf index 04980f3e0f..20a909ae98 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ja.xlf @@ -621,11 +621,61 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print '--server {0}' には '--{1}' を指定する必要があります。 {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test パイプ。 {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -698,6 +748,16 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print スタートアップ バナー、著作権メッセージ、テレメトリ バナーは表示しないでください。 + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. サーバーのポートを指定します。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf index b569dd3ac1..05c3a83748 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ko.xlf @@ -621,11 +621,61 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print '--server {0}'를 사용하려면 '--{1}'를 지정해야 합니다. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test 파이프. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print 시작 배너, 저작권 메시지 또는 원격 분석 배너를 표시하지 마세요. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. 서버의 포트를 지정합니다. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf index 6c871df623..e760ace9a7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pl.xlf @@ -621,11 +621,61 @@ Opcjonalnie akceptuje „text” (domyślne dane wyjściowe czytelne dla człowi Element „--server {0}„ wymaga określenia elementu „--{1}”. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. potok dotnet test. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Opcjonalnie akceptuje „text” (domyślne dane wyjściowe czytelne dla człowi Nie wyświetlaj baneru startowego, komunikatu o prawach autorskich ani transparentu telemetrii. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Określ port serwera. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf index d0c2bde469..58f1ffe7a7 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.pt-BR.xlf @@ -621,11 +621,61 @@ Opcionalmente, aceita 'text' (a saída legível por humanos padrão) ou 'json' p ''--server {0}'' requer que ''--{1}'' seja especificado. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. pipe de dotnet test. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Opcionalmente, aceita 'text' (a saída legível por humanos padrão) ou 'json' p Não exiba a faixa de inicialização, a mensagem de direitos autorais ou a faixa de telemetria. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Especifique a porta do servidor. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf index 076346dd4a..c28d15635a 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.ru.xlf @@ -621,11 +621,61 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print Для --server {0} требуется указать --{1}. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test канал. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print Не отображать баннер запуска, сообщение об авторских правах и баннер телеметрии. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Укажите порт сервера. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf index fcad947c96..8176ff2acd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.tr.xlf @@ -621,11 +621,61 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print '--server {0}' için '--{1}' belirtilmelidir. {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test kanalı. {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print Başlangıç başlığını, telif hakkı iletisini veya telemetri başlığını görüntülemez. + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. Sunucunun bağlantı noktasını belirtir. diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf index 4b00eca074..bd0ff021fd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hans.xlf @@ -621,11 +621,61 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print “--server {0}”需要指定“--{1}”。 {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test 管道。 {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print 请勿显示启动横幅、版权信息或遥测横幅。 + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. 指定服务器的端口。 diff --git a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf index 0e94b44533..0e021c5fcd 100644 --- a/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf +++ b/src/Platform/Microsoft.Testing.Platform/Resources/xlf/PlatformResources.zh-Hant.xlf @@ -621,11 +621,61 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print '--server {0}' 要求指定 '--{1}'。 {0} is the server protocol value. {1} is the required option name without the leading dashes. {Locked="--server"}{Locked="dotnettestcli"}{Locked="dotnet-test-pipe"} + + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + '--server dotnettestcli' requires either '--dotnet-test-pipe' or '--dotnet-test-transport http'. + {Locked="--server dotnettestcli"}{Locked="--dotnet-test-pipe"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + '--dotnet-test-http-endpoint' requires an absolute HTTPS URL, or an HTTP loopback URL, without user information, query, or fragment. + {Locked="--dotnet-test-http-endpoint"}{Locked="HTTP"}{Locked="HTTPS"} + + + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + Specifies the authenticated HTTP endpoint for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + + + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + The dotnet test HTTP endpoint and token options require '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="HTTP"}{Locked="--dotnet-test-transport http"} + + + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + '--dotnet-test-transport http' requires both '--dotnet-test-http-endpoint' and '--dotnet-test-http-token'. + {Locked="--dotnet-test-transport http"}{Locked="--dotnet-test-http-endpoint"}{Locked="--dotnet-test-http-token"} + + + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + '--dotnet-test-http-token' requires a non-empty valid bearer token without whitespace or control characters. + {Locked="--dotnet-test-http-token"} + + + Specifies the per-run HTTP bearer token for the dotnet test protocol. + Specifies the per-run HTTP bearer token for the dotnet test protocol. + {Locked="HTTP"}{Locked="dotnet test"} + dotnet test pipe. dotnet test 管道。 {Locked="dotnet test"} + + The dotnet test named-pipe and HTTP transports cannot be selected together. + The dotnet test named-pipe and HTTP transports cannot be selected together. + {Locked="dotnet test"}{Locked="HTTP"} + + + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + '--dotnet-test-transport' received unexpected value '{0}'. Supported values are: {1}. + {0} is the unexpected transport value. {1} is the comma-separated list of supported transport values. {Locked="--dotnet-test-transport"}{Locked="pipe"}{Locked="http"} + + + Selects the pre-launch transport for the dotnet test protocol. + Selects the pre-launch transport for the dotnet test protocol. + {Locked="dotnet test"} + Invalid PID '{0}' {1} @@ -697,6 +747,16 @@ Optionally accepts 'text' (the default human-readable output) or 'json' to print 不要顯示啟動橫幅、著作權訊息或遙測橫幅。 + + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on browser-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="browser-wasm"}{Locked="--dotnet-test-transport http"} + + + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + The dotnet test named-pipe transport is not supported on wasi-wasm. Use '--dotnet-test-transport http'. + {Locked="dotnet test"}{Locked="wasi-wasm"}{Locked="--dotnet-test-transport http"} + Specify the port of the server. 指定伺服器的連接埠。 diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index 8b67f24b08..5daf74ba6c 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -14,7 +14,6 @@ namespace Microsoft.Testing.Platform; -[UnsupportedOSPlatform("browser")] internal sealed class DotnetTestConnection : IPushOnlyProtocol, IDisposable { private readonly CommandLineHandler _commandLineHandler; @@ -23,7 +22,8 @@ internal sealed class DotnetTestConnection : IPushOnlyProtocol, IDisposable private readonly ITestApplicationCancellationTokenSource _cancellationTokenSource; private readonly ILogger _logger; - private NamedPipeClient? _dotnetTestPipeClient; + private IClient? _transportClient; + private DotnetTestTransportKind _transportKind; private NamedPipeClient? _serverControlPipeClient; private Task? _serverControlListenerTask; @@ -53,17 +53,15 @@ public DotnetTestConnection(CommandLineHandler commandLineHandler, IEnvironment _logger = logger; } - public bool IsServerMode => _dotnetTestPipeClient?.IsConnected == true; + public bool IsServerMode => _transportClient?.IsConnected == true; public Task GetDataConsumerAsync() => Task.FromResult((IPushOnlyProtocolConsumer)new DotnetTestDataConsumer(this, _environment)); public async Task AfterCommonServiceSetupAsync() { - // If we are in server mode and the pipe name is provided - // then, we need to connect to the pipe server. - if (_commandLineHandler.HasDotnetTestServerOption() && - _commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.DotNetTestPipeOptionKey, out string[]? arguments)) + if (_commandLineHandler.HasDotnetTestServerOption() + && _commandLineHandler.TryGetDotnetTestTransport(out DotnetTestTransportKind transport)) { // The execution id is used to identify the test execution // We are storing it as an env var so that it can be read by the test host, test host controller and the test host orchestrator @@ -73,16 +71,38 @@ public async Task AfterCommonServiceSetupAsync() _environment.SetEnvironmentVariable(EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_EXECUTIONID, Guid.NewGuid().ToString("N")); } - _dotnetTestPipeClient = new(arguments[0], _environment); - _dotnetTestPipeClient.RegisterAllSerializers(); + _transportKind = transport; + _transportClient = transport switch + { + DotnetTestTransportKind.Http => CreateHttpClient(), + DotnetTestTransportKind.NamedPipe when !OperatingSystem.IsBrowser() && !OperatingSystem.IsWasi() => CreateNamedPipeClient(), + DotnetTestTransportKind.NamedPipe => throw new PlatformNotSupportedException("The dotnet test named-pipe transport is not supported on WebAssembly."), + _ => throw ApplicationStateGuard.Unreachable(), + }; + + ((NamedPipeBase)_transportClient).RegisterAllSerializers(); - await _dotnetTestPipeClient.ConnectAsync(_cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await _transportClient.ConnectAsync(_cancellationTokenSource.CancellationToken).ConfigureAwait(false); } } + [UnsupportedOSPlatform("browser")] + private NamedPipeClient CreateNamedPipeClient() + { + ApplicationStateGuard.Ensure(_commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.DotNetTestPipeOptionKey, out string[]? arguments)); + return new NamedPipeClient(arguments[0], _environment); + } + + private DotnetTestHttpClient CreateHttpClient() + { + ApplicationStateGuard.Ensure(_commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey, out string[]? endpointArguments)); + ApplicationStateGuard.Ensure(_commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey, out string[]? tokenArguments)); + return new DotnetTestHttpClient(new Uri(endpointArguments[0], UriKind.Absolute), tokenArguments[0]); + } + public async Task HelpInvokedAsync() { - RoslynDebug.Assert(_dotnetTestPipeClient is not null); + RoslynDebug.Assert(_transportClient is not null); List commandLineHelpOptions = []; foreach (ICommandLineOptionsProvider commandLineOptionProvider in _commandLineHandler.CommandLineOptionsProviders) @@ -102,7 +122,7 @@ public async Task HelpInvokedAsync() } } - await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await _transportClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken).ConfigureAwait(false); } public bool IsIDE { get; private set; } @@ -125,7 +145,7 @@ public async Task HelpInvokedAsync() public async Task IsCompatibleProtocolAsync(string hostType, IReadOnlyDictionary? additionalHandshakeProperties = null) { - RoslynDebug.Assert(_dotnetTestPipeClient is not null); + RoslynDebug.Assert(_transportClient is not null); string supportedProtocolVersions = ProtocolConstants.SupportedVersions; Dictionary properties = new() @@ -157,13 +177,14 @@ public async Task IsCompatibleProtocolAsync(string hostType, IReadOnlyDict HandshakeMessage handshakeMessage = new(properties); - HandshakeMessage response = await _dotnetTestPipeClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + HandshakeMessage response = await _transportClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); IsIDE = response.Properties?.TryGetValue(HandshakeMessagePropertyNames.IsIDE, out string? isIDEValue) == true && bool.TryParse(isIDEValue, out bool isIDE) && isIDE; - if (response.Properties?.TryGetValue(HandshakeMessagePropertyNames.ServerControlPipeName, out string? serverControlPipeName) is true && + if (_transportKind == DotnetTestTransportKind.NamedPipe + && response.Properties?.TryGetValue(HandshakeMessagePropertyNames.ServerControlPipeName, out string? serverControlPipeName) is true && !RoslynString.IsNullOrEmpty(serverControlPipeName)) { _serverControlPipeName = serverControlPipeName; @@ -205,33 +226,33 @@ private string GetAttemptNumber() public async Task SendMessageAsync(IRequest message) { - NamedPipeClient dotnetTestPipeClient = _dotnetTestPipeClient - ?? throw new InvalidOperationException("The dotnet test pipe client is not connected."); + IClient transportClient = _transportClient + ?? throw new InvalidOperationException("The dotnet test transport client is not connected."); switch (message) { case DiscoveredTestMessages discoveredTestMessages: - await dotnetTestPipeClient.RequestReplyAsync(discoveredTestMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(discoveredTestMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case TestResultMessages testResultMessages: - await dotnetTestPipeClient.RequestReplyAsync(testResultMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(testResultMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case FileArtifactMessages fileArtifactMessages: - await dotnetTestPipeClient.RequestReplyAsync(fileArtifactMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(fileArtifactMessages, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case TestSessionEvent testSessionEvent: - await dotnetTestPipeClient.RequestReplyAsync(testSessionEvent, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(testSessionEvent, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case AzureDevOpsLogMessage azureDevOpsLogMessage: - await dotnetTestPipeClient.RequestReplyAsync(azureDevOpsLogMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(azureDevOpsLogMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; case DisplayMessage displayMessage: - await dotnetTestPipeClient.RequestReplyAsync(displayMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(displayMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); break; } } @@ -258,7 +279,12 @@ public async Task SendMessageAsync(IRequest message) /// public Task StartServerControlChannelAsync(Func onCancelSessionRequestedAsync) { - if (!IsServerControlChannelSupported || RoslynString.IsNullOrEmpty(_serverControlPipeName) || _serverControlPipeClient is not null) + if (_transportKind != DotnetTestTransportKind.NamedPipe + || OperatingSystem.IsBrowser() + || OperatingSystem.IsWasi() + || !IsServerControlChannelSupported + || RoslynString.IsNullOrEmpty(_serverControlPipeName) + || _serverControlPipeClient is not null) { return Task.CompletedTask; } @@ -273,11 +299,14 @@ public Task StartServerControlChannelAsync(Func onCance // Connect AND listen on a background task: we deliberately do not await the connect on the run path so a // slow/absent control server can never delay (or fail) test execution start. +#pragma warning disable CA1416 // The runtime guards above exclude browser before the named-pipe operation is scheduled. _serverControlListenerTask = Task.Run( () => ConnectAndListenForServerControlAsync(controlClient, onCancelSessionRequestedAsync, _serverControlListenerCts.Token)); +#pragma warning restore CA1416 return Task.CompletedTask; } + [UnsupportedOSPlatform("browser")] private async Task ConnectAndListenForServerControlAsync(NamedPipeClient controlClient, Func onCancelSessionRequestedAsync, CancellationToken cancellationToken) { try @@ -301,6 +330,7 @@ private async Task ConnectAndListenForServerControlAsync(NamedPipeClient control await ListenForServerControlAsync(controlClient, onCancelSessionRequestedAsync, cancellationToken).ConfigureAwait(false); } + [UnsupportedOSPlatform("browser")] private async Task ListenForServerControlAsync(NamedPipeClient controlClient, Func onCancelSessionRequestedAsync, CancellationToken cancellationToken) { try @@ -369,7 +399,10 @@ public async Task OnExitAsync() // Framework cancellation of an already-parked overlapped read is not reliable - disposing the stream is // what forces it to unblock. We cancelled first (above) so the listener treats the resulting failure as // shutdown rather than "host gone => cancel". - _serverControlPipeClient?.Dispose(); + if (!OperatingSystem.IsBrowser()) + { + _serverControlPipeClient?.Dispose(); + } if (_serverControlListenerTask is { } listenerTask) { @@ -387,7 +420,10 @@ public void Dispose() _serverControlListenerCts?.Cancel(); // Disposing the pipe client forces a parked read to abort even where token cancellation alone would not. - _serverControlPipeClient?.Dispose(); + if (!OperatingSystem.IsBrowser()) + { + _serverControlPipeClient?.Dispose(); + } if (_serverControlListenerTask is { } listenerTask) { @@ -404,7 +440,7 @@ public void Dispose() } _serverControlListenerCts?.Dispose(); - _dotnetTestPipeClient?.Dispose(); + _transportClient?.Dispose(); } private async Task TryLogAsync(LogLevel logLevel, string message) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestHelper.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestHelper.cs index ad9aeaa230..1ed91eae12 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestHelper.cs @@ -5,10 +5,36 @@ namespace Microsoft.Testing.Platform; +internal enum DotnetTestTransportKind +{ + NamedPipe, + Http, +} + internal static class DotnetTestHelper { public static bool HasDotnetTestServerOption(this CommandLineHandler commandLineHandler) => commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.ServerOptionKey, out string[]? serverArgs) && serverArgs.Length == 1 && serverArgs[0].Equals(PlatformCommandLineProvider.DotnetTestCliProtocolName, StringComparison.OrdinalIgnoreCase); + + public static bool TryGetDotnetTestTransport(this CommandLineHandler commandLineHandler, out DotnetTestTransportKind transport) + { + if (commandLineHandler.TryGetOptionArgumentList(PlatformCommandLineProvider.DotNetTestTransportOptionKey, out string[]? transportArgs) + && transportArgs is { Length: 1 } + && PlatformCommandLineProvider.DotNetTestTransportHttpArgument.Equals(transportArgs[0], StringComparison.OrdinalIgnoreCase)) + { + transport = DotnetTestTransportKind.Http; + return true; + } + + if (commandLineHandler.IsOptionSet(PlatformCommandLineProvider.DotNetTestPipeOptionKey)) + { + transport = DotnetTestTransportKind.NamedPipe; + return true; + } + + transport = default; + return false; + } } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index a362ed4eda..09a3b89fc5 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -10,7 +10,6 @@ namespace Microsoft.Testing.Platform.IPC; -[UnsupportedOSPlatform("browser")] internal sealed class DotnetTestDataConsumer : IPushOnlyProtocolConsumer { private readonly DotnetTestConnection? _dotnetTestConnection; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs new file mode 100644 index 0000000000..5a02c7dc5e --- /dev/null +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Net.Http.Headers; + +using Microsoft.CodeAnalysis; +#if !NETCOREAPP +using Microsoft.Testing.Platform.Helpers; +#endif + +namespace Microsoft.Testing.Platform.IPC; + +/// +/// Carries the existing framed dotnettestcli request/reply protocol over authenticated HTTP POSTs. +/// +[Embedded] +internal sealed class DotnetTestHttpClient : NamedPipeConnectionBase, IClient +{ + private const string MediaType = "application/octet-stream"; + private const int MaximumResponseFrameSize = 256 * 1024 * 1024; + + private readonly Uri _endpoint; + private readonly string _authToken; + private readonly HttpClient _httpClient; + private readonly bool _disposeHttpClient; + private readonly SemaphoreSlim _requestLock = new(1, 1); + private readonly CancellationTokenSource _disposeCancellationTokenSource = new(); +#if NET9_0_OR_GREATER + private readonly Lock _lifecycleLock = new(); +#else + private readonly object _lifecycleLock = new(); +#endif + + private volatile bool _connected; + private volatile bool _disposed; + private int _activeOperations; + private bool _disposeCancellationCompleted; + private bool _cleanupCompleted; + + public DotnetTestHttpClient(Uri endpoint, string authToken) + : this(endpoint, authToken, new HttpClient(), disposeHttpClient: true) + { + } + + internal DotnetTestHttpClient(Uri endpoint, string authToken, HttpClient httpClient, bool disposeHttpClient) + { + _endpoint = endpoint; + _authToken = authToken; + _httpClient = httpClient; + _disposeHttpClient = disposeHttpClient; + } + + public bool IsConnected => _connected && !_disposed; + + public Task ConnectAsync(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + lock (_lifecycleLock) + { + ThrowIfDisposed(); + + // HTTP has no persistent connection to establish. The first protocol request is the handshake POST, + // avoiding a separate health probe and its additional browser preflight. + _connected = true; + } + + return Task.CompletedTask; + } + + public async Task RequestReplyAsync(TRequest request, CancellationToken cancellationToken) + where TRequest : IRequest + where TResponse : IResponse + { + CancellationTokenSource operationCancellationTokenSource; + lock (_lifecycleLock) + { + ThrowIfDisposed(); + if (!_connected) + { + throw new InvalidOperationException("The dotnet test HTTP transport is not connected."); + } + + operationCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + _disposeCancellationTokenSource.Token); + _activeOperations++; + } + + bool requestLockAcquired = false; + try + { + await _requestLock.WaitAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); + requestLockAcquired = true; + operationCancellationTokenSource.Token.ThrowIfCancellationRequested(); + ThrowIfDisposed(); + + using var framedRequest = new MemoryStream(); + await WriteMessageAsync( + framedRequest, + GetSerializer(typeof(TRequest)), + request, + operationCancellationTokenSource.Token).ConfigureAwait(false); + + using var content = new ByteArrayContent(framedRequest.ToArray()); + content.Headers.ContentType = new MediaTypeHeaderValue(MediaType); + + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, _endpoint) + { + Content = content, + }; + httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authToken); + + Task sendTask = _httpClient.SendAsync( + httpRequest, + HttpCompletionOption.ResponseHeadersRead, + operationCancellationTokenSource.Token); + using HttpResponseMessage httpResponse = await sendTask.WaitAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); + + if (!httpResponse.IsSuccessStatusCode) + { + throw new IOException( + $"The dotnet test HTTP gateway returned status code {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase ?? "unknown"})."); + } + + if (httpResponse.Content.Headers.ContentLength is long contentLength + && (contentLength < (sizeof(int) * 2) || contentLength > MaximumResponseFrameSize)) + { + throw new IOException($"The dotnet test HTTP gateway returned an invalid response frame length of {contentLength} bytes."); + } + +#if NET + using Stream responseStream = await httpResponse.Content.ReadAsStreamAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); +#else + using Stream responseStream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); +#endif + object response = await ReadNextMessageAsync( + responseStream, + operationCancellationTokenSource.Token, + MaximumResponseFrameSize).ConfigureAwait(false) + ?? throw new IOException("The dotnet test HTTP gateway returned an empty or truncated response frame."); + + byte[] trailingByte = new byte[1]; + int trailingByteCount = await responseStream.ReadAsync( + trailingByte, + 0, + trailingByte.Length, + operationCancellationTokenSource.Token).ConfigureAwait(false); + return (trailingByteCount, response) switch + { + (not 0, _) => throw new IOException("The dotnet test HTTP gateway returned more than one response frame."), + (0, TResponse typedResponse) => typedResponse, + _ => throw new IOException( + $"The dotnet test HTTP gateway returned '{response.GetType().Name}' when '{typeof(TResponse).Name}' was expected."), + }; + } + finally + { + if (requestLockAcquired) + { + _requestLock.Release(); + } + + operationCancellationTokenSource.Dispose(); + CompleteOperation(); + } + } + + public void Dispose() + { + lock (_lifecycleLock) + { + if (_disposed) + { + return; + } + + _disposed = true; + _connected = false; + } + + try + { + _disposeCancellationTokenSource.Cancel(); + } + finally + { + lock (_lifecycleLock) + { + _disposeCancellationCompleted = true; + TryCleanup(); + } + } + } + + private void CompleteOperation() + { + lock (_lifecycleLock) + { + _activeOperations--; + TryCleanup(); + } + } + + private void TryCleanup() + { + if (_cleanupCompleted || !_disposed || !_disposeCancellationCompleted || _activeOperations != 0) + { + return; + } + + _cleanupCompleted = true; + _requestLock.Dispose(); + _disposeCancellationTokenSource.Dispose(); + DisposeBuffers(); + if (_disposeHttpClient) + { + _httpClient.Dispose(); + } + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(DotnetTestHttpClient)); + } + } +} diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs index b29b2b93ed..8d635e8afa 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs @@ -132,6 +132,224 @@ public void FailingTest() // Set exitCode rather than calling process.exit(): process.exit() can terminate Node before // redirected stdout/stderr has flushed, which would truncate the MTP summary this test asserts on. process.exitCode = exitCode; +"""; + + private const string DotnetTestHttpToken = "browser-wasm-http-transport-test-token"; + + private const string DotnetTestHttpNodeRunnerSource = """ +import { Worker } from 'node:worker_threads'; + +const scenario = '$Scenario$'; +const token = '$Token$'; +function gatewayMain() { +const http = require('node:http'); +const { parentPort, workerData } = require('node:worker_threads'); +const { scenario, token } = workerData; +const serializerIds = []; +let activeRequests = 0; +let maximumActiveRequests = 0; +let authorizedRequests = 0; +let validFrames = 0; +let cancelledRequests = 0; +let cancellationSafetyTimerExpirations = 0; + +function createFrame(serializerId, body = Buffer.alloc(0)) { + const frame = Buffer.alloc(8 + body.length); + frame.writeInt32LE(4 + body.length, 0); + frame.writeInt32LE(serializerId, 4); + body.copy(frame, 8); + return frame; +} + +function createHandshakeFrame() { + const version = Buffer.from('1.4.0', 'utf8'); + const body = Buffer.alloc(2 + 1 + 4 + version.length); + body.writeUInt16LE(1, 0); + body.writeUInt8(4, 2); + body.writeInt32LE(version.length, 3); + version.copy(body, 7); + return createFrame(9, body); +} + +const server = http.createServer(async (request, response) => { + activeRequests++; + maximumActiveRequests = Math.max(maximumActiveRequests, activeRequests); + + const chunks = []; + for await (const chunk of request) { + chunks.push(chunk); + } + + const requestBody = Buffer.concat(chunks); + const isAuthorized = request.headers.authorization === `Bearer ${token}`; + if (isAuthorized) { + authorizedRequests++; + } + + const hasValidFrame = + request.method === 'POST' + && request.headers['content-type']?.startsWith('application/octet-stream') + && requestBody.length >= 8 + && requestBody.readInt32LE(0) === requestBody.length - 4; + if (hasValidFrame) { + validFrames++; + serializerIds.push(requestBody.readInt32LE(4)); + } + + if (!isAuthorized || !hasValidFrame || scenario === 'unauthorized') { + activeRequests--; + response.writeHead(401); + response.end(); + return; + } + + if (scenario === 'disconnect') { + activeRequests--; + request.socket.destroy(); + return; + } + + const serializerId = requestBody.readInt32LE(4); + if (scenario === 'cancel' && serializerId === 6) { + let safetyTimerExpired = false; + const safetyTimer = setTimeout(() => { + safetyTimerExpired = true; + cancellationSafetyTimerExpirations++; + response.destroy(); + }, 30000); + safetyTimer.unref(); + response.on('close', () => { + clearTimeout(safetyTimer); + if (!safetyTimerExpired) { + cancelledRequests++; + } + + activeRequests--; + }); + + return; + } + + await new Promise(resolve => setTimeout(resolve, 20)); + const responseBody = serializerId === 9 ? createHandshakeFrame() : createFrame(0); + response.writeHead(200, { + 'Content-Type': 'application/octet-stream', + 'Content-Length': responseBody.length, + }); + response.end(responseBody); + activeRequests--; +}); + +parentPort.on('message', message => { + if (message !== 'close') { + return; + } + + server.close(() => { + parentPort.postMessage({ + type: 'result', + serializerIds, + maximumActiveRequests, + authorizedRequests, + validFrames, + cancelledRequests, + cancellationSafetyTimerExpirations, + }); + parentPort.close(); + }); + server.closeIdleConnections?.(); +}); + +server.listen(0, '127.0.0.1', () => { + parentPort.postMessage({ type: 'ready', port: server.address().port }); +}); +} + +const gatewaySource = '(' + gatewayMain.toString() + ')();'; +const gateway = new Worker(gatewaySource, { + eval: true, + workerData: { scenario, token }, +}); +const gatewayMessages = new Map(); +const gatewayWaiters = new Map(); +gateway.on('message', message => { + const waiter = gatewayWaiters.get(message.type); + if (waiter) { + gatewayWaiters.delete(message.type); + waiter(message); + } + else { + gatewayMessages.set(message.type, message); + } +}); + +function receiveGatewayMessage(type) { + const message = gatewayMessages.get(type); + if (message) { + gatewayMessages.delete(type); + return Promise.resolve(message); + } + + return new Promise(resolve => gatewayWaiters.set(type, resolve)); +} + +const ready = await receiveGatewayMessage('ready'); +const endpoint = 'http://127.0.0.1:' + ready.port + '/dotnettest'; + +// BrowserHttpHandler probes streaming-request support with new Request(""). Browsers resolve that +// against the document URL, while Node rejects it before the real fetch. Preserve browser semantics +// for that feature probe without replacing the product's HttpClient/fetch transport. +const NodeRequest = globalThis.Request; +globalThis.Request = class extends NodeRequest { + constructor(input, init) { + super(input === '' ? endpoint : input, init); + } +}; + +const { dotnet } = await import('./_framework/dotnet.js'); +const extraArguments = scenario === 'help' + ? ['--help'] + : scenario === 'discover' + ? ['--list-tests'] + : scenario === 'cancel' + ? ['--timeout', '5s'] + : []; + +let exitCode = 99; +let thrown = false; +try { + const { runMain } = await dotnet + .withApplicationArguments( + '--server', 'dotnettestcli', + '--dotnet-test-transport', 'http', + '--dotnet-test-http-endpoint', endpoint, + '--dotnet-test-http-token', token, + ...extraArguments) + .create(); + exitCode = await runMain(); +} +catch (error) { + thrown = true; + console.error(error); +} + +gateway.postMessage('close'); +const gatewayResult = await receiveGatewayMessage('result'); +await gateway.terminate(); + +const result = 'HTTP_GATEWAY_RESULT=' + JSON.stringify({ + scenario, + exitCode, + thrown, + ...gatewayResult, +}); +// A canceled BrowserHttpHandler operation can retain a Node runtime handle after managed Main returns. +// Flush the observation marker before explicitly terminating this acceptance-only process. +await new Promise(resolve => process.stdout.write(result + '\n', resolve)); +// Let the worker's libuv handle finish closing before terminating the Node runtime, whose browser +// emulation can retain handles after managed Main returns (especially after a canceled fetch). +await new Promise(resolve => setTimeout(resolve, 100)); +process.exit(exitCode); """; // The runsettings XML (declaring an section) that the run-settings validation @@ -329,6 +547,63 @@ public async Task BrowserWasmBuild_GeneratesTestingPlatformEntryPoint() $"Expected a generated 'MicrosoftTestingPlatformEntryPoint.cs' under '{Path.Combine(generator.TargetAssetPath, "obj")}'."); } + [TestMethod] + public async Task BrowserWasmExecution_DotnetTestHttpTransportExercisesLiveGateway() + { + string? node = WasmRuntime.LocateNode(); + if (node is null) + { + Assert.Inconclusive(WasmRuntime.NodeUnavailableMessage); + return; + } + + using TestAsset generator = await GenerateBrowserWasmAssetAsync(); + DotnetMuxerResult publishResult = await WasmRuntime.PublishForBrowserAsync( + generator.TargetAssetPath, TargetFramework, TestContext.CancellationToken); + if (publishResult.ExitCode != 0) + { + Assert.IsTrue( + WasmRuntime.IsMissingWasmToolsWorkload(publishResult), + $"'dotnet publish -r browser-wasm' failed for an unexpected reason (not a missing 'wasm-tools' workload).{Environment.NewLine}{publishResult}"); + Assert.Inconclusive( + $"Skipping browser-wasm execution: the 'wasm-tools' workload is not installed.{Environment.NewLine}{publishResult}"); + } + + string appBundle = WasmRuntime.GetBrowserAppBundlePath(generator.TargetAssetPath, TargetFramework); + Assert.IsTrue(Directory.Exists(appBundle), $"Expected the browser-wasm AppBundle directory at '{appBundle}'."); + + HttpGatewayScenarioResult help = await RunDotnetTestHttpScenarioAsync(node, appBundle, "help"); + Assert.AreEqual((int)ExitCode.Success, help.ProcessExitCode, help.CombinedOutput); + AssertHttpGatewaySuccess(help, expectedMessageSerializerId: 3); + + HttpGatewayScenarioResult discovery = await RunDotnetTestHttpScenarioAsync(node, appBundle, "discover"); + Assert.AreEqual((int)ExitCode.Success, discovery.ProcessExitCode, discovery.CombinedOutput); + AssertHttpGatewaySuccess(discovery, expectedMessageSerializerId: 5); + + HttpGatewayScenarioResult run = await RunDotnetTestHttpScenarioAsync(node, appBundle, "run"); + Assert.AreEqual((int)ExitCode.AtLeastOneTestFailed, run.ProcessExitCode, run.CombinedOutput); + AssertHttpGatewaySuccess(run, expectedMessageSerializerId: 6); + Assert.Contains(8, run.SerializerIds, $"Expected test-session traffic after the handshake.{Environment.NewLine}{run.CombinedOutput}"); + + HttpGatewayScenarioResult unauthorized = await RunDotnetTestHttpScenarioAsync(node, appBundle, "unauthorized"); + Assert.AreNotEqual((int)ExitCode.Success, unauthorized.ProcessExitCode, unauthorized.CombinedOutput); + Assert.AreEqual(1, unauthorized.AuthorizedRequests, unauthorized.CombinedOutput); + Assert.AreEqual(1, unauthorized.ValidFrames, unauthorized.CombinedOutput); + Assert.Contains("401", unauthorized.CombinedOutput); + + HttpGatewayScenarioResult disconnect = await RunDotnetTestHttpScenarioAsync(node, appBundle, "disconnect"); + Assert.AreNotEqual((int)ExitCode.Success, disconnect.ProcessExitCode, disconnect.CombinedOutput); + Assert.AreEqual(1, disconnect.AuthorizedRequests, disconnect.CombinedOutput); + Assert.AreEqual(1, disconnect.ValidFrames, disconnect.CombinedOutput); + + HttpGatewayScenarioResult cancellation = await RunDotnetTestHttpScenarioAsync(node, appBundle, "cancel"); + Assert.AreNotEqual((int)ExitCode.Success, cancellation.ProcessExitCode, cancellation.CombinedOutput); + Assert.AreEqual(1, cancellation.CancelledRequests, cancellation.CombinedOutput); + Assert.AreEqual(0, cancellation.CancellationSafetyTimerExpirations, cancellation.CombinedOutput); + Assert.IsGreaterThanOrEqualTo(2, cancellation.ValidFrames, cancellation.CombinedOutput); + Assert.AreEqual(1, cancellation.MaximumActiveRequests, cancellation.CombinedOutput); + } + [TestMethod] public async Task BrowserWasmExecution_RunsTestsUnderNode() { @@ -503,6 +778,45 @@ public async Task BrowserWasmExecution_RunSettingsEnvironmentVariables_FailsWith return await WasmRuntime.RunUnderNodeAsync(node, appBundle, NodeRunnerSource, TestContext.CancellationToken); } + private async Task RunDotnetTestHttpScenarioAsync(string node, string appBundle, string scenario) + { + string runner = DotnetTestHttpNodeRunnerSource + .PatchCodeWithReplace("$Scenario$", scenario) + .PatchCodeWithReplace("$Token$", DotnetTestHttpToken); + (int processExitCode, _, _, string combined) = await WasmRuntime.RunUnderNodeAsync( + node, appBundle, runner, TestContext.CancellationToken); + + Assert.DoesNotContain(DotnetTestHttpToken, combined, "The per-run bearer token must never be written to host diagnostics."); + const string marker = "HTTP_GATEWAY_RESULT="; + int markerIndex = combined.LastIndexOf(marker, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, markerIndex, $"The Node HTTP gateway did not report its observations.{Environment.NewLine}{combined}"); + int jsonStart = markerIndex + marker.Length; + int jsonEnd = combined.IndexOfAny(['\r', '\n'], jsonStart); + string json = jsonEnd < 0 ? combined[jsonStart..] : combined[jsonStart..jsonEnd]; + + using var document = System.Text.Json.JsonDocument.Parse(json); + System.Text.Json.JsonElement root = document.RootElement; + return new HttpGatewayScenarioResult( + processExitCode, + combined, + [.. root.GetProperty("serializerIds").EnumerateArray().Select(element => element.GetInt32())], + root.GetProperty("maximumActiveRequests").GetInt32(), + root.GetProperty("authorizedRequests").GetInt32(), + root.GetProperty("validFrames").GetInt32(), + root.GetProperty("cancelledRequests").GetInt32(), + root.GetProperty("cancellationSafetyTimerExpirations").GetInt32()); + } + + private static void AssertHttpGatewaySuccess(HttpGatewayScenarioResult result, int expectedMessageSerializerId) + { + Assert.IsNotEmpty(result.SerializerIds, result.CombinedOutput); + Assert.AreEqual(9, result.SerializerIds[0], $"The protocol handshake must be the first HTTP request.{Environment.NewLine}{result.CombinedOutput}"); + Assert.Contains(expectedMessageSerializerId, result.SerializerIds, result.CombinedOutput); + Assert.AreEqual(result.SerializerIds.Count, result.AuthorizedRequests, result.CombinedOutput); + Assert.AreEqual(result.SerializerIds.Count, result.ValidFrames, result.CombinedOutput); + Assert.AreEqual(1, result.MaximumActiveRequests, result.CombinedOutput); + } + private Task GenerateBrowserWasmAssetAsync() => TestAsset.GenerateAssetAsync( "BrowserTestProject", @@ -521,6 +835,16 @@ private Task GenerateBrowserWasmWarningAssetAsync() .PatchCodeWithReplace("$ErrorText$", ErrorText) .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)); + private sealed record HttpGatewayScenarioResult( + int ProcessExitCode, + string CombinedOutput, + IReadOnlyList SerializerIds, + int MaximumActiveRequests, + int AuthorizedRequests, + int ValidFrames, + int CancelledRequests, + int CancellationSafetyTimerExpirations); + private Task GenerateBrowserWasmRunSettingsAssetAsync() => TestAsset.GenerateAssetAsync( "BrowserRunSettingsProject", diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs index c6397aa222..7425554ac3 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoAllExtensionsTests.cs @@ -313,10 +313,22 @@ Note that this is slowing down the test execution. Hidden: False Description: Define the level of the verbosity for the --diagnostic. The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', and 'Critical'. + --dotnet-test-http-endpoint + Arity: 1 + Hidden: True + Description: Specifies the authenticated HTTP endpoint for the dotnet test protocol. + --dotnet-test-http-token + Arity: 1 + Hidden: True + Description: Specifies the per-run HTTP bearer token for the dotnet test protocol. --dotnet-test-pipe Arity: 1 Hidden: True Description: dotnet test pipe. + --dotnet-test-transport + Arity: 1 + Hidden: True + Description: Selects the pre-launch transport for the dotnet test protocol. --exit-on-process-exit Arity: 1 Hidden: False diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs index dc8fd587b1..85bab3d0be 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/HelpInfoTests.cs @@ -207,10 +207,22 @@ Note that this is slowing down the test execution\. Hidden: False Description: Define the level of the verbosity for the --diagnostic\. The available values are 'Trace', 'Debug', 'Information', 'Warning', 'Error', and 'Critical' + --dotnet-test-http-endpoint + Arity: 1 + Hidden: True + Description: Specifies the authenticated HTTP endpoint for the dotnet test protocol\. + --dotnet-test-http-token + Arity: 1 + Hidden: True + Description: Specifies the per-run HTTP bearer token for the dotnet test protocol\. --dotnet-test-pipe Arity: 1 Hidden: True Description: dotnet test pipe\. + --dotnet-test-transport + Arity: 1 + Hidden: True + Description: Selects the pre-launch transport for the dotnet test protocol\. --exit-on-process-exit Arity: 1 Hidden: False diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs new file mode 100644 index 0000000000..d3f763e484 --- /dev/null +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Testing.Platform.CommandLine; + +namespace Microsoft.Testing.Platform.UnitTests.CommandLine; + +[TestClass] +public sealed class CommandLineArgumentsRedactorTests +{ + [TestMethod] + [DataRow("--dotnet-test-http-token", "secret", "--dotnet-test-http-token ***REDACTED***")] + [DataRow("--dotnet-test-http-token=secret", null, "--dotnet-test-http-token=***REDACTED***")] + [DataRow("-dotnet-test-http-token:secret", null, "-dotnet-test-http-token:***REDACTED***")] + public void Redact_MasksToken(string option, string? value, string expected) + { + string[] arguments = value is null ? [option] : [option, value]; + + Assert.AreEqual(expected, CommandLineArgumentsRedactor.Redact(arguments)); + } + + [TestMethod] + public void Redact_RemovesEndpointPathAndPreservesOtherArguments() + { + string[] arguments = + [ + "--server", + "dotnettestcli", + "--dotnet-test-http-endpoint", + "https://gateway.example:8443/private/run-id", + "--list-tests", + ]; + + Assert.AreEqual( + "--server dotnettestcli --dotnet-test-http-endpoint https://gateway.example:8443 --list-tests", + CommandLineArgumentsRedactor.Redact(arguments)); + } + + [TestMethod] + [DataRow("not-a-url")] + [DataRow("https://user:password@gateway.example/private/run-id")] + public void Redact_MasksInvalidOrCredentialedEndpoint(string endpoint) + => Assert.AreEqual( + "--dotnet-test-http-endpoint ***REDACTED***", + CommandLineArgumentsRedactor.Redact(["--dotnet-test-http-endpoint", endpoint])); +} diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs index f2395774e9..8a951d584e 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs @@ -331,25 +331,149 @@ public async Task IsValid_When_Server_DotnetTestCli_With_DotnetTestPipe() } [TestMethod] - [DataRow("dotnettestcli")] - [DataRow("DotnetTestCli")] - public async Task IsInvalid_When_Server_DotnetTestCli_Without_DotnetTestPipe(string protocol) + public async Task IsValid_When_Server_DotnetTestCli_With_HttpTransport() { var provider = new PlatformCommandLineProvider(); var options = new Dictionary { - { PlatformCommandLineProvider.ServerOptionKey, [protocol] }, + [PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"], + [PlatformCommandLineProvider.DotNetTestTransportOptionKey] = ["http"], + [PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey] = ["https://localhost:1234/dotnettest"], + [PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey] = ["valid-token-value"], }; ValidationResult validateOptionsResult = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); - Assert.IsFalse(validateOptionsResult.IsValid); + Assert.IsTrue(validateOptionsResult.IsValid); + } + + [TestMethod] + [DataRow("pipe")] + [DataRow("http")] + [DataRow("HTTP")] + public async Task IsValid_When_DotnetTestTransport_HasAcceptedArgument(string argument) + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.DotNetTestTransportOptionKey); + + ValidationResult result = await provider.ValidateOptionArgumentsAsync(option, [argument]).ConfigureAwait(false); + Assert.IsTrue(result.IsValid); + } + + [TestMethod] + public async Task IsInvalid_When_DotnetTestTransport_HasUnknownArgument() + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.DotNetTestTransportOptionKey); + + ValidationResult result = await provider.ValidateOptionArgumentsAsync(option, ["websocket"]).ConfigureAwait(false); + Assert.IsFalse(result.IsValid); + Assert.Contains("websocket", result.ErrorMessage); + } + + [TestMethod] + [DataRow("https://gateway.example/dotnettest", true)] + [DataRow("http://localhost:1234/dotnettest", true)] + [DataRow("http://127.0.0.1:1234/dotnettest", true)] + [DataRow("http://gateway.example/dotnettest", false)] + [DataRow("https://user@gateway.example/dotnettest", false)] + [DataRow("https://gateway.example/dotnettest?token=secret", false)] + [DataRow("https://gateway.example/dotnettest#fragment", false)] + [DataRow("ws://localhost:1234/dotnettest", false)] + [DataRow("/dotnettest", false)] + public async Task DotnetTestHttpEndpoint_ValidatesSecurityRequirements(string endpoint, bool expectedValid) + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey); + + ValidationResult result = await provider.ValidateOptionArgumentsAsync(option, [endpoint]).ConfigureAwait(false); + Assert.AreEqual(expectedValid, result.IsValid); + } + + [TestMethod] + [DataRow("valid-token", true)] + [DataRow("", false)] + [DataRow(" ", false)] + [DataRow("token with spaces", false)] + [DataRow("token\r\nheader", false)] + [DataRow("token,parameter", false)] + public async Task DotnetTestHttpToken_ValidatesBearerSyntax(string token, bool expectedValid) + { + var provider = new PlatformCommandLineProvider(); + CommandLineOption option = provider.GetCommandLineOptions().First(x => x.Name == PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey); + + ValidationResult result = await provider.ValidateOptionArgumentsAsync(option, [token]).ConfigureAwait(false); + Assert.AreEqual(expectedValid, result.IsValid); + } + + [TestMethod] + public async Task IsInvalid_When_HttpTransport_IsIncomplete() + { + var provider = new PlatformCommandLineProvider(); + var options = new Dictionary + { + [PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"], + [PlatformCommandLineProvider.DotNetTestTransportOptionKey] = ["http"], + [PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey] = ["https://localhost:1234/dotnettest"], + }; + + ValidationResult result = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); + Assert.IsFalse(result.IsValid); + Assert.AreEqual(PlatformResources.PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken, result.ErrorMessage); + } + + [TestMethod] + public async Task IsInvalid_When_HttpAndPipeTransportsAreCombined() + { + var provider = new PlatformCommandLineProvider(); + var options = new Dictionary + { + [PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"], + [PlatformCommandLineProvider.DotNetTestPipeOptionKey] = ["pipe-name"], + [PlatformCommandLineProvider.DotNetTestTransportOptionKey] = ["http"], + [PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey] = ["https://localhost:1234/dotnettest"], + [PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey] = ["valid-token"], + }; + + ValidationResult result = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); + Assert.IsFalse(result.IsValid); + Assert.AreEqual(PlatformResources.PlatformCommandLineDotnetTestTransportConflict, result.ErrorMessage); + } + + [TestMethod] + public async Task IsInvalid_When_ExplicitPipeTransportHasNoPipeName() + { + var provider = new PlatformCommandLineProvider(); + var options = new Dictionary + { + [PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"], + [PlatformCommandLineProvider.DotNetTestTransportOptionKey] = ["pipe"], + }; + + ValidationResult result = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); + Assert.IsFalse(result.IsValid); Assert.AreEqual( string.Format( CultureInfo.InvariantCulture, PlatformResources.PlatformCommandLineDotnetTestCliRequiresPipe, - PlatformCommandLineProvider.DotnetTestCliProtocolName, + "dotnettestcli", PlatformCommandLineProvider.DotNetTestPipeOptionKey), - validateOptionsResult.ErrorMessage); + result.ErrorMessage); + } + + [TestMethod] + [DataRow("dotnettestcli")] + [DataRow("DotnetTestCli")] + public async Task IsInvalid_When_Server_DotnetTestCli_Without_DotnetTestPipe(string protocol) + { + var provider = new PlatformCommandLineProvider(); + var options = new Dictionary + { + { PlatformCommandLineProvider.ServerOptionKey, [protocol] }, + }; + + ValidationResult validateOptionsResult = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); + Assert.IsFalse(validateOptionsResult.IsValid); + Assert.AreEqual(PlatformResources.PlatformCommandLineDotnetTestCliRequiresTransport, validateOptionsResult.ErrorMessage); } [TestMethod] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs new file mode 100644 index 0000000000..bac4106e54 --- /dev/null +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -0,0 +1,317 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Net; +using System.Net.Http.Headers; + +using Microsoft.Testing.Platform.IPC; +using Microsoft.Testing.Platform.IPC.Serializers; + +namespace Microsoft.Testing.Platform.UnitTests.IPC; + +[TestClass] +public sealed class DotnetTestHttpClientTests +{ + private static readonly Uri Endpoint = new("https://127.0.0.1:12345/dotnettest"); + private const string Token = "test-only-256-bit-style-token-value"; + private const int RequestSerializerId = 201; + private const int ResponseSerializerId = 202; + private readonly TestContext _testContext; + + public DotnetTestHttpClientTests(TestContext testContext) + => _testContext = testContext; + + [TestMethod] + public async Task RequestReplyAsync_PostsFullFrameWithBearerAuthentication() + { + byte[]? requestBody = null; + AuthenticationHeaderValue? authorization = null; + MediaTypeHeaderValue? contentType = null; + var handler = new DelegateHttpMessageHandler(async (request, cancellationToken) => + { + requestBody = await request.Content!.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); + authorization = request.Headers.Authorization; + contentType = request.Content.Headers.ContentType; + return CreateResponse(TestResponseFrame()); + }); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + _ = await client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + + Assert.IsNotNull(requestBody); + Assert.IsGreaterThanOrEqualTo(8, requestBody.Length); + Assert.AreEqual(requestBody.Length - sizeof(int), BitConverter.ToInt32(requestBody, 0)); + Assert.AreEqual(RequestSerializerId, BitConverter.ToInt32(requestBody, sizeof(int))); + Assert.AreEqual("Bearer", authorization?.Scheme); + Assert.AreEqual(Token, authorization?.Parameter); + Assert.AreEqual("application/octet-stream", contentType?.MediaType); + } + + [TestMethod] + public async Task RequestReplyAsync_SerializesConcurrentRequests() + { + int activeRequests = 0; + int maximumActiveRequests = 0; + var firstRequestEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseFirstRequest = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int requestCount = 0; + var handler = new DelegateHttpMessageHandler(async (_, cancellationToken) => + { + int active = Interlocked.Increment(ref activeRequests); + maximumActiveRequests = Math.Max(maximumActiveRequests, active); + int currentRequest = Interlocked.Increment(ref requestCount); + if (currentRequest == 1) + { + firstRequestEntered.SetResult(); + await releaseFirstRequest.Task.WaitAsync(cancellationToken); + } + + Interlocked.Decrement(ref activeRequests); + return CreateResponse(TestResponseFrame()); + }); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + Task first = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + await firstRequestEntered.Task; + + Task second = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + await Task.Delay(50, _testContext.CancellationToken); + + Assert.AreEqual(1, requestCount); + releaseFirstRequest.SetResult(); + await Task.WhenAll(first, second); + Assert.AreEqual(1, maximumActiveRequests); + Assert.AreEqual(2, requestCount); + } + + [TestMethod] + public async Task RequestReplyAsync_PropagatesCancellation() + { + var pendingResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new DelegateHttpMessageHandler(async (_, _) => await pendingResponse.Task); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + cancellationTokenSource.Token)); + } + + [TestMethod] + public async Task RequestReplyAsync_DisposeCancelsActiveRequestAndWaiter() + { + var requestEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new DelegateHttpMessageHandler(async (_, cancellationToken) => + { + requestEntered.SetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return CreateResponse(TestResponseFrame()); + }); + + DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + Task activeRequest = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + await requestEntered.Task; + Task waiter = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + + client.Dispose(); + + await Assert.ThrowsAsync(() => activeRequest); + await Assert.ThrowsAsync(() => waiter); + } + + [TestMethod] + [DataRow(-1)] + [DataRow(0)] + [DataRow(3)] + [DataRow(int.MaxValue)] + public async Task RequestReplyAsync_RejectsInvalidChunkedFramePayloadLength(int payloadLength) + { + byte[] body = BitConverter.GetBytes(payloadLength); + var handler = new DelegateHttpMessageHandler((_, _) => Task.FromResult(CreateChunkedResponse(body))); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + + IOException exception = await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + Assert.Contains("invalid response payload length", exception.Message); + } + + [TestMethod] + public async Task RequestReplyAsync_RejectsNonSuccessWithoutLeakingToken() + { + var handler = new DelegateHttpMessageHandler((_, _) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized))); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + + IOException exception = await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + Assert.Contains("401", exception.Message); + Assert.DoesNotContain(Token, exception.ToString()); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task RequestReplyAsync_RejectsMissingOrMultipleResponseFrames(bool appendSecondFrame) + { + byte[] body = appendSecondFrame + ? [.. TestResponseFrame(), .. TestResponseFrame()] + : []; + var handler = new DelegateHttpMessageHandler((_, _) => Task.FromResult(CreateResponse(body))); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + + IOException exception = await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + Assert.Contains(appendSecondFrame ? "more than one" : "invalid response frame length", exception.Message); + } + + [TestMethod] + public async Task RequestReplyAsync_RequiresConnectAndRejectsUseAfterDispose() + { + var handler = new DelegateHttpMessageHandler((_, _) => Task.FromResult(CreateResponse(TestResponseFrame()))); + DotnetTestHttpClient client = CreateClient(handler); + + await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + + client.Dispose(); + await Assert.ThrowsExactlyAsync(() => client.ConnectAsync(_testContext.CancellationToken)); + } + + private static DotnetTestHttpClient CreateClient(HttpMessageHandler handler) + { + var client = new DotnetTestHttpClient(Endpoint, Token, new HttpClient(handler), disposeHttpClient: true); + client.RegisterSerializer(new TestRequestSerializer(), typeof(TestRequest)); + client.RegisterSerializer(new TestResponseSerializer(), typeof(TestResponse)); + return client; + } + + private static HttpResponseMessage CreateResponse(byte[] body) + => new(HttpStatusCode.OK) + { + Content = new ByteArrayContent(body), + }; + + private static HttpResponseMessage CreateChunkedResponse(byte[] body) + => new(HttpStatusCode.OK) + { + Content = new StreamContent(new NonSeekableReadStream(body)), + }; + + private static byte[] TestResponseFrame() + => [.. BitConverter.GetBytes(sizeof(int)), .. BitConverter.GetBytes(ResponseSerializerId)]; + + private sealed class TestRequest : IRequest + { + public static readonly TestRequest Instance = new(); + } + + private sealed class TestResponse : IResponse + { + public static readonly TestResponse Instance = new(); + } + + private sealed class TestRequestSerializer : NamedPipeSerializer, INamedPipeSerializer + { + public override int Id => RequestSerializerId; + + protected override TestRequest DeserializeCore(Stream _) + => TestRequest.Instance; + + protected override void SerializeCore(TestRequest _, Stream __) + { + } + } + + private sealed class TestResponseSerializer : NamedPipeSerializer, INamedPipeSerializer + { + public override int Id => ResponseSerializerId; + + protected override TestResponse DeserializeCore(Stream _) + => TestResponse.Instance; + + protected override void SerializeCore(TestResponse _, Stream __) + { + } + } + + private sealed class DelegateHttpMessageHandler(Func> sendAsync) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => sendAsync(request, cancellationToken); + } + + private sealed class NonSeekableReadStream(byte[] body) : Stream + { + private readonly MemoryStream _innerStream = new(body); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + => _innerStream.Read(buffer, offset, count); + + public override long Seek(long offset, SeekOrigin origin) + => throw new NotSupportedException(); + + public override void SetLength(long value) + => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) + => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _innerStream.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Microsoft.Testing.Platform.UnitTests.csproj b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Microsoft.Testing.Platform.UnitTests.csproj index a549f31a29..f9f6931223 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Microsoft.Testing.Platform.UnitTests.csproj +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Microsoft.Testing.Platform.UnitTests.csproj @@ -13,6 +13,7 @@ + @@ -23,6 +24,9 @@ + From 1af0d2098d256f451bd6a7a2b237e44c4d2dbba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 22 Jul 2026 23:39:09 +0200 Subject: [PATCH 02/21] Address HTTP transport review feedback Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 2 + .../CommandLineArgumentsRedactor.cs | 7 --- .../DotnetTest/DotnetTestConnection.cs | 10 +-- .../Transport/DotnetTestHttpClient.cs | 12 +++- .../CommandLineArgumentsRedactorTests.cs | 7 +++ .../IPC/DotnetTestHttpClientTests.cs | 63 +++++++++++++++++-- 6 files changed, 84 insertions(+), 17 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index f0b3486fc3..e73e6886fb 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -632,6 +632,8 @@ This is deliberate: if the user kills `dotnet.exe`, the test host must die too r Gateway loss, DNS/network failure, authentication expiry, or a malformed response is detected by the current POST, or by the next POST if the host was idle. A failed request fails the host operation; there is no transparent retry because retrying after an ambiguous network failure could duplicate a message. +Automatic redirects are disabled for the same reason: every `3xx` response fails the operation instead +of replaying the authenticated frame at another location. Cancellation is passed to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch without converting expected cancellation into a connection-loss failure. Disposal cancels no completed messages and prevents later use. diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index 031e339112..1a6c3a0583 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -23,13 +23,6 @@ public static string Redact(string[] args) string arg = args[i]; if (TryParseOption(arg, out string? prefix, out string? name, out string? delimiter, out string? inlineValue)) { - if (redactNextValue) - { - redacted[i] = RedactedPlaceholder; - redactNextValue = false; - continue; - } - bool isToken = PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); bool isEndpoint = PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); if (isToken) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index 5daf74ba6c..1791f28dc9 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -102,7 +102,8 @@ private DotnetTestHttpClient CreateHttpClient() public async Task HelpInvokedAsync() { - RoslynDebug.Assert(_transportClient is not null); + IClient transportClient = _transportClient + ?? throw new InvalidOperationException("The dotnet test transport client is not connected."); List commandLineHelpOptions = []; foreach (ICommandLineOptionsProvider commandLineOptionProvider in _commandLineHandler.CommandLineOptionsProviders) @@ -122,7 +123,7 @@ public async Task HelpInvokedAsync() } } - await _transportClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + await transportClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken).ConfigureAwait(false); } public bool IsIDE { get; private set; } @@ -145,7 +146,8 @@ public async Task HelpInvokedAsync() public async Task IsCompatibleProtocolAsync(string hostType, IReadOnlyDictionary? additionalHandshakeProperties = null) { - RoslynDebug.Assert(_transportClient is not null); + IClient transportClient = _transportClient + ?? throw new InvalidOperationException("The dotnet test transport client is not connected."); string supportedProtocolVersions = ProtocolConstants.SupportedVersions; Dictionary properties = new() @@ -177,7 +179,7 @@ public async Task IsCompatibleProtocolAsync(string hostType, IReadOnlyDict HandshakeMessage handshakeMessage = new(properties); - HandshakeMessage response = await _transportClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); + HandshakeMessage response = await transportClient.RequestReplyAsync(handshakeMessage, _cancellationTokenSource.CancellationToken).ConfigureAwait(false); IsIDE = response.Properties?.TryGetValue(HandshakeMessagePropertyNames.IsIDE, out string? isIDEValue) == true && bool.TryParse(isIDEValue, out bool isIDE) && diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index 5a02c7dc5e..d1daf42346 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -38,7 +38,11 @@ internal sealed class DotnetTestHttpClient : NamedPipeConnectionBase, IClient private bool _cleanupCompleted; public DotnetTestHttpClient(Uri endpoint, string authToken) - : this(endpoint, authToken, new HttpClient(), disposeHttpClient: true) + : this( + endpoint, + authToken, + new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }), + disposeHttpClient: true) { } @@ -123,6 +127,12 @@ await WriteMessageAsync( $"The dotnet test HTTP gateway returned status code {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase ?? "unknown"})."); } + if (!MediaType.Equals(httpResponse.Content.Headers.ContentType?.MediaType, StringComparison.OrdinalIgnoreCase)) + { + throw new IOException( + $"The dotnet test HTTP gateway returned content type '{httpResponse.Content.Headers.ContentType?.MediaType ?? "missing"}' instead of '{MediaType}'."); + } + if (httpResponse.Content.Headers.ContentLength is long contentLength && (contentLength < (sizeof(int) * 2) || contentLength > MaximumResponseFrameSize)) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index d3f763e484..c3aee6b0f7 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -36,6 +36,13 @@ public void Redact_RemovesEndpointPathAndPreservesOtherArguments() CommandLineArgumentsRedactor.Redact(arguments)); } + [TestMethod] + public void Redact_RepeatedTokenOptionDoesNotExposeValue() + => Assert.AreEqual( + "--dotnet-test-http-token --dotnet-test-http-token ***REDACTED***", + CommandLineArgumentsRedactor.Redact( + ["--dotnet-test-http-token", "--dotnet-test-http-token", "secret"])); + [TestMethod] [DataRow("not-a-url")] [DataRow("https://user:password@gateway.example/private/run-id")] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index bac4106e54..82de1be081 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -172,6 +172,47 @@ public async Task RequestReplyAsync_RejectsNonSuccessWithoutLeakingToken() Assert.DoesNotContain(Token, exception.ToString()); } + [TestMethod] + [DataRow(HttpStatusCode.TemporaryRedirect)] + [DataRow(HttpStatusCode.PermanentRedirect)] + public async Task RequestReplyAsync_RejectsRedirectResponses(HttpStatusCode statusCode) + { + var handler = new DelegateHttpMessageHandler((_, _) => + Task.FromResult(new HttpResponseMessage(statusCode) + { + Headers = { Location = new Uri("https://redirect.example/dotnettest") }, + })); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + + IOException exception = await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + Assert.Contains(((int)statusCode).ToString(CultureInfo.InvariantCulture), exception.Message); + } + + [TestMethod] + [DataRow(null)] + [DataRow("text/plain")] + public async Task RequestReplyAsync_RejectsUnexpectedResponseContentType(string? mediaType) + { + HttpResponseMessage response = CreateResponse(TestResponseFrame()); + response.Content.Headers.ContentType = mediaType is null ? null : new MediaTypeHeaderValue(mediaType); + var handler = new DelegateHttpMessageHandler((_, _) => Task.FromResult(response)); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + + IOException exception = await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + Assert.Contains("content type", exception.Message); + Assert.Contains(mediaType ?? "missing", exception.Message); + } + [TestMethod] [DataRow(false)] [DataRow(true)] @@ -216,16 +257,24 @@ private static DotnetTestHttpClient CreateClient(HttpMessageHandler handler) } private static HttpResponseMessage CreateResponse(byte[] body) - => new(HttpStatusCode.OK) + { + var content = new ByteArrayContent(body); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + return new HttpResponseMessage(HttpStatusCode.OK) { - Content = new ByteArrayContent(body), + Content = content, }; + } private static HttpResponseMessage CreateChunkedResponse(byte[] body) - => new(HttpStatusCode.OK) + { + var content = new StreamContent(new NonSeekableReadStream(body)); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + return new HttpResponseMessage(HttpStatusCode.OK) { - Content = new StreamContent(new NonSeekableReadStream(body)), + Content = content, }; + } private static byte[] TestResponseFrame() => [.. BitConverter.GetBytes(sizeof(int)), .. BitConverter.GetBytes(ResponseSerializerId)]; @@ -285,7 +334,11 @@ private sealed class NonSeekableReadStream(byte[] body) : Stream public override long Position { get => throw new NotSupportedException(); - set => throw new NotSupportedException(); + set + { + _ = value; + throw new NotSupportedException(); + } } public override void Flush() From f269f7daf65c1cb0fdda39e28c09ef2cdbd24cb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 16:29:11 +0200 Subject: [PATCH 03/21] Harden HTTP transport diagnostics Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 7 ++-- .../Transport/DotnetTestHttpClient.cs | 3 +- .../IPC/DotnetTestHttpClientTests.cs | 32 +++++++++++++++++-- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index e73e6886fb..ebcefb476f 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -634,9 +634,10 @@ current POST, or by the next POST if the host was idle. A failed request fails t is no transparent retry because retrying after an ambiguous network failure could duplicate a message. Automatic redirects are disabled for the same reason: every `3xx` response fails the operation instead of replaying the authenticated frame at another location. -Cancellation is passed to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch -without converting expected cancellation into a connection-loss failure. Disposal cancels no completed -messages and prevents later use. +The implicit `HttpClient` timeout is disabled; cancellation is controlled by the operation token passed +to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch without converting +expected cancellation into a connection-loss failure. Disposal cancels no completed messages and +prevents later use. **Server-control pipe (`exitProcessOnConnectionLoss: false`).** A dropped control pipe must **not** kill the test host. This listener runs *inside the test host* as the control-pipe **client**, so an diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index d1daf42346..640b573d1e 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -51,6 +51,7 @@ internal DotnetTestHttpClient(Uri endpoint, string authToken, HttpClient httpCli _endpoint = endpoint; _authToken = authToken; _httpClient = httpClient; + _httpClient.Timeout = Timeout.InfiniteTimeSpan; _disposeHttpClient = disposeHttpClient; } @@ -124,7 +125,7 @@ await WriteMessageAsync( if (!httpResponse.IsSuccessStatusCode) { throw new IOException( - $"The dotnet test HTTP gateway returned status code {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase ?? "unknown"})."); + $"The dotnet test HTTP gateway returned status code {(int)httpResponse.StatusCode}."); } if (!MediaType.Equals(httpResponse.Content.Headers.ContentType?.MediaType, StringComparison.OrdinalIgnoreCase)) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index 82de1be081..1fe5194fb9 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -108,6 +108,23 @@ await Assert.ThrowsExactlyAsync(() => cancellationTokenSource.Token)); } + [TestMethod] + public async Task RequestReplyAsync_UsesCallerCancellationInsteadOfHttpClientTimeout() + { + var handler = new DelegateHttpMessageHandler(async (_, cancellationToken) => + { + await Task.Delay(100, cancellationToken); + return CreateResponse(TestResponseFrame()); + }); + + using DotnetTestHttpClient client = CreateClient(handler, TimeSpan.FromMilliseconds(10)); + await client.ConnectAsync(_testContext.CancellationToken); + + _ = await client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + } + [TestMethod] public async Task RequestReplyAsync_DisposeCancelsActiveRequestAndWaiter() { @@ -159,7 +176,10 @@ public async Task RequestReplyAsync_RejectsInvalidChunkedFramePayloadLength(int public async Task RequestReplyAsync_RejectsNonSuccessWithoutLeakingToken() { var handler = new DelegateHttpMessageHandler((_, _) => - Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized))); + Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized) + { + ReasonPhrase = Token, + })); using DotnetTestHttpClient client = CreateClient(handler); await client.ConnectAsync(_testContext.CancellationToken); @@ -248,9 +268,15 @@ await Assert.ThrowsExactlyAsync(() => await Assert.ThrowsExactlyAsync(() => client.ConnectAsync(_testContext.CancellationToken)); } - private static DotnetTestHttpClient CreateClient(HttpMessageHandler handler) + private static DotnetTestHttpClient CreateClient(HttpMessageHandler handler, TimeSpan? httpClientTimeout = null) { - var client = new DotnetTestHttpClient(Endpoint, Token, new HttpClient(handler), disposeHttpClient: true); + var httpClient = new HttpClient(handler); + if (httpClientTimeout is not null) + { + httpClient.Timeout = httpClientTimeout.Value; + } + + var client = new DotnetTestHttpClient(Endpoint, Token, httpClient, disposeHttpClient: true); client.RegisterSerializer(new TestRequestSerializer(), typeof(TestRequest)); client.RegisterSerializer(new TestResponseSerializer(), typeof(TestResponse)); return client; From 315e0f1f86c235c50a95a3aa0a29f61b3d513e2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 16:46:14 +0200 Subject: [PATCH 04/21] Close HTTP transport cancellation gaps Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 6 +- .../CommandLineArgumentsRedactor.cs | 6 + .../CommandLine/ParseResult.cs | 2 +- .../Transport/DotnetTestHttpClient.cs | 136 ++++++++++++------ .../CommandLineArgumentsRedactorTests.cs | 6 + .../CommandLine/CommandLineHandlerTests.cs | 26 ++++ .../IPC/DotnetTestHttpClientTests.cs | 49 +++++++ 7 files changed, 188 insertions(+), 43 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index ebcefb476f..4a01d95901 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -636,8 +636,10 @@ Automatic redirects are disabled for the same reason: every `3xx` response fails of replaying the authenticated frame at another location. The implicit `HttpClient` timeout is disabled; cancellation is controlled by the operation token passed to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch without converting -expected cancellation into a connection-loss failure. Disposal cancels no completed messages and -prevents later use. +expected cancellation into a connection-loss failure. If a handler does not complete its send after +cancellation, the transport is made terminal and the pending send is observed before its request +resources are released, so another protocol request cannot overlap it. Disposal cancels no completed +messages and prevents later use. **Server-control pipe (`exitProcessOnConnectionLoss: false`).** A dropped control pipe must **not** kill the test host. This listener runs *inside the test host* as the control-pipe **client**, so an diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index 1a6c3a0583..e7be5deb98 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -41,6 +41,12 @@ public static string Redact(string[] args) sanitizeNextEndpoint = inlineValue is null; redactNextValue = false; } + else if (redactNextValue) + { + redacted[i] = RedactedPlaceholder; + redactNextValue = false; + sanitizeNextEndpoint = false; + } else { redacted[i] = arg; diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs index 6921b21b3e..b10f66f160 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs @@ -35,7 +35,7 @@ internal CommandLineParseResult(string? toolName, IReadOnlyList diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index 640b573d1e..298e237bce 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -107,10 +107,10 @@ await WriteMessageAsync( request, operationCancellationTokenSource.Token).ConfigureAwait(false); - using var content = new ByteArrayContent(framedRequest.ToArray()); + var content = new ByteArrayContent(framedRequest.ToArray()); content.Headers.ContentType = new MediaTypeHeaderValue(MediaType); - using var httpRequest = new HttpRequestMessage(HttpMethod.Post, _endpoint) + var httpRequest = new HttpRequestMessage(HttpMethod.Post, _endpoint) { Content = content, }; @@ -120,50 +120,71 @@ await WriteMessageAsync( httpRequest, HttpCompletionOption.ResponseHeadersRead, operationCancellationTokenSource.Token); - using HttpResponseMessage httpResponse = await sendTask.WaitAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); - - if (!httpResponse.IsSuccessStatusCode) - { - throw new IOException( - $"The dotnet test HTTP gateway returned status code {(int)httpResponse.StatusCode}."); - } - - if (!MediaType.Equals(httpResponse.Content.Headers.ContentType?.MediaType, StringComparison.OrdinalIgnoreCase)) - { - throw new IOException( - $"The dotnet test HTTP gateway returned content type '{httpResponse.Content.Headers.ContentType?.MediaType ?? "missing"}' instead of '{MediaType}'."); - } - - if (httpResponse.Content.Headers.ContentLength is long contentLength - && (contentLength < (sizeof(int) * 2) || contentLength > MaximumResponseFrameSize)) + bool disposeRequest = true; + try { - throw new IOException($"The dotnet test HTTP gateway returned an invalid response frame length of {contentLength} bytes."); - } + using HttpResponseMessage httpResponse = await sendTask.WaitAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); + + if (!httpResponse.IsSuccessStatusCode) + { + throw new IOException( + $"The dotnet test HTTP gateway returned status code {(int)httpResponse.StatusCode}."); + } + + HttpContent? responseContent = httpResponse.Content; + string? responseMediaType = responseContent?.Headers.ContentType?.MediaType; + if (responseContent is null || !MediaType.Equals(responseMediaType, StringComparison.OrdinalIgnoreCase)) + { + throw new IOException( + $"The dotnet test HTTP gateway returned content type '{responseMediaType ?? "missing"}' instead of '{MediaType}'."); + } + + if (responseContent.Headers.ContentLength is long contentLength + && (contentLength < (sizeof(int) * 2) || contentLength > MaximumResponseFrameSize)) + { + throw new IOException($"The dotnet test HTTP gateway returned an invalid response frame length of {contentLength} bytes."); + } #if NET - using Stream responseStream = await httpResponse.Content.ReadAsStreamAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); + using Stream responseStream = await responseContent.ReadAsStreamAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); #else - using Stream responseStream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + using Stream responseStream = await responseContent.ReadAsStreamAsync().ConfigureAwait(false); #endif - object response = await ReadNextMessageAsync( - responseStream, - operationCancellationTokenSource.Token, - MaximumResponseFrameSize).ConfigureAwait(false) - ?? throw new IOException("The dotnet test HTTP gateway returned an empty or truncated response frame."); - - byte[] trailingByte = new byte[1]; - int trailingByteCount = await responseStream.ReadAsync( - trailingByte, - 0, - trailingByte.Length, - operationCancellationTokenSource.Token).ConfigureAwait(false); - return (trailingByteCount, response) switch + object response = await ReadNextMessageAsync( + responseStream, + operationCancellationTokenSource.Token, + MaximumResponseFrameSize).ConfigureAwait(false) + ?? throw new IOException("The dotnet test HTTP gateway returned an empty or truncated response frame."); + + byte[] trailingByte = new byte[1]; + int trailingByteCount = await responseStream.ReadAsync( + trailingByte, + 0, + trailingByte.Length, + operationCancellationTokenSource.Token).ConfigureAwait(false); + return (trailingByteCount, response) switch + { + (not 0, _) => throw new IOException("The dotnet test HTTP gateway returned more than one response frame."), + (0, TResponse typedResponse) => typedResponse, + _ => throw new IOException( + $"The dotnet test HTTP gateway returned '{response.GetType().Name}' when '{typeof(TResponse).Name}' was expected."), + }; + } + catch (OperationCanceledException) when (!sendTask.IsCompleted) { - (not 0, _) => throw new IOException("The dotnet test HTTP gateway returned more than one response frame."), - (0, TResponse typedResponse) => typedResponse, - _ => throw new IOException( - $"The dotnet test HTTP gateway returned '{response.GetType().Name}' when '{typeof(TResponse).Name}' was expected."), - }; + AbortTransportForIncompleteSend(); + ObserveAndDisposeIncompleteSend(sendTask, httpRequest); + disposeRequest = false; + requestLockAcquired = false; + throw; + } + finally + { + if (disposeRequest) + { + httpRequest.Dispose(); + } + } } finally { @@ -213,6 +234,41 @@ private void CompleteOperation() } } + private void AbortTransportForIncompleteSend() + { + lock (_lifecycleLock) + { + _connected = false; + } + + _disposeCancellationTokenSource.Cancel(); + _httpClient.CancelPendingRequests(); + if (_disposeHttpClient) + { + _httpClient.Dispose(); + } + } + + private static void ObserveAndDisposeIncompleteSend(Task sendTask, HttpRequestMessage request) + => _ = sendTask.ContinueWith( + static (task, state) => + { + if (task.Status == TaskStatus.RanToCompletion) + { + task.Result.Dispose(); + } + else if (task.IsFaulted) + { + _ = task.Exception; + } + + ((HttpRequestMessage)state!).Dispose(); + }, + request, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + private void TryCleanup() { if (_cleanupCompleted || !_disposed || !_disposeCancellationCompleted || _activeOperations != 0) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index c3aee6b0f7..a868ab8257 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -43,6 +43,12 @@ public void Redact_RepeatedTokenOptionDoesNotExposeValue() CommandLineArgumentsRedactor.Redact( ["--dotnet-test-http-token", "--dotnet-test-http-token", "secret"])); + [TestMethod] + public void Redact_OptionShapedTokenValueDoesNotExposeValue() + => Assert.AreEqual( + "--dotnet-test-http-token ***REDACTED***", + CommandLineArgumentsRedactor.Redact(["--dotnet-test-http-token", "-secret"])); + [TestMethod] [DataRow("not-a-url")] [DataRow("https://user:password@gateway.example/private/run-id")] diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index b8959be2b3..cb87ca7c1d 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -44,6 +44,32 @@ public async Task ParseAndValidateAsync_InvalidCommandLineArguments_ReturnsFalse Assert.Contains("Unexpected argument 'a'", result.ErrorMessage); } + [TestMethod] + public async Task ParseAndValidateAsync_InvalidCommandLineRedactsHttpTransportSecrets() + { + string[] args = + [ + "--server", "dotnettestcli", + "--dotnet-test-transport", "http", + "--dotnet-test-http-endpoint", "https://gateway.example/private/run-id", + "--dotnet-test-http-token", "secret-token", + "--unknown-option", + ]; + CommandLineParseResult parseResult = CommandLineParser.Parse(args, new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains("***REDACTED***", result.ErrorMessage); + Assert.Contains("https://gateway.example", result.ErrorMessage); + Assert.DoesNotContain("secret-token", result.ErrorMessage); + Assert.DoesNotContain("/private/run-id", result.ErrorMessage); + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index 1fe5194fb9..5534dbb29b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -108,6 +108,39 @@ await Assert.ThrowsExactlyAsync(() => cancellationTokenSource.Token)); } + [TestMethod] + public async Task RequestReplyAsync_CancellationDoesNotAllowOverlappingSend() + { + int requestCount = 0; + var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pendingResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new DelegateHttpMessageHandler((_, _) => + { + Interlocked.Increment(ref requestCount); + requestStarted.SetResult(); + return pendingResponse.Task; + }); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + using var cancellationTokenSource = new CancellationTokenSource(); + Task activeRequest = client.RequestReplyAsync( + TestRequest.Instance, + cancellationTokenSource.Token); + await requestStarted.Task; + Task waitingRequest = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + + await cancellationTokenSource.CancelAsync(); + + await Assert.ThrowsAsync(() => activeRequest); + await Assert.ThrowsAsync(() => waitingRequest); + Assert.AreEqual(1, requestCount); + Assert.IsFalse(client.IsConnected); + pendingResponse.SetResult(CreateResponse(TestResponseFrame())); + } + [TestMethod] public async Task RequestReplyAsync_UsesCallerCancellationInsteadOfHttpClientTimeout() { @@ -233,6 +266,22 @@ public async Task RequestReplyAsync_RejectsUnexpectedResponseContentType(string? Assert.Contains(mediaType ?? "missing", exception.Message); } + [TestMethod] + public async Task RequestReplyAsync_RejectsMissingResponseContent() + { + var handler = new DelegateHttpMessageHandler((_, _) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = null! })); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + + IOException exception = await Assert.ThrowsExactlyAsync(() => + client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken)); + Assert.Contains("content type 'missing'", exception.Message); + } + [TestMethod] [DataRow(false)] [DataRow(true)] From b3643465b8ea2737f292b0abf4b8528627c7cac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 16:49:28 +0200 Subject: [PATCH 05/21] Make HTTP transport tests deterministic Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../IPC/DotnetTestHttpClientTests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index 5534dbb29b..6578861f8e 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -83,9 +83,9 @@ public async Task RequestReplyAsync_SerializesConcurrentRequests() Task second = client.RequestReplyAsync( TestRequest.Instance, _testContext.CancellationToken); - await Task.Delay(50, _testContext.CancellationToken); Assert.AreEqual(1, requestCount); + Assert.IsFalse(second.IsCompleted); releaseFirstRequest.SetResult(); await Task.WhenAll(first, second); Assert.AreEqual(1, maximumActiveRequests); @@ -153,9 +153,10 @@ public async Task RequestReplyAsync_UsesCallerCancellationInsteadOfHttpClientTim using DotnetTestHttpClient client = CreateClient(handler, TimeSpan.FromMilliseconds(10)); await client.ConnectAsync(_testContext.CancellationToken); - _ = await client.RequestReplyAsync( + TestResponse response = await client.RequestReplyAsync( TestRequest.Instance, _testContext.CancellationToken); + Assert.AreSame(TestResponse.Instance, response); } [TestMethod] From 410a2c7b64bc5842dd8ec8ce7e511c9323764d24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 16:57:29 +0200 Subject: [PATCH 06/21] Redact all sensitive option values Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLineArgumentsRedactor.cs | 11 ++++++++--- .../CommandLineArgumentsRedactorTests.cs | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index e7be5deb98..5e87e86a44 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -17,6 +17,7 @@ public static string Redact(string[] args) string[] redacted = new string[args.Length]; bool redactNextValue = false; bool sanitizeNextEndpoint = false; + bool sensitiveValueConsumed = false; for (int i = 0; i < args.Length; i++) { @@ -32,6 +33,7 @@ public static string Redact(string[] args) : $"{prefix}{name}{delimiter}{RedactedPlaceholder}"; redactNextValue = inlineValue is null; sanitizeNextEndpoint = false; + sensitiveValueConsumed = inlineValue is not null; } else if (isEndpoint) { @@ -40,18 +42,21 @@ public static string Redact(string[] args) : $"{prefix}{name}{delimiter}{SanitizeEndpoint(inlineValue)}"; sanitizeNextEndpoint = inlineValue is null; redactNextValue = false; + sensitiveValueConsumed = inlineValue is not null; } - else if (redactNextValue) + else if (redactNextValue && !sensitiveValueConsumed) { redacted[i] = RedactedPlaceholder; redactNextValue = false; sanitizeNextEndpoint = false; + sensitiveValueConsumed = false; } else { redacted[i] = arg; redactNextValue = false; sanitizeNextEndpoint = false; + sensitiveValueConsumed = false; } continue; @@ -60,12 +65,12 @@ public static string Redact(string[] args) if (redactNextValue) { redacted[i] = RedactedPlaceholder; - redactNextValue = false; + sensitiveValueConsumed = true; } else if (sanitizeNextEndpoint) { redacted[i] = SanitizeEndpoint(arg); - sanitizeNextEndpoint = false; + sensitiveValueConsumed = true; } else { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index a868ab8257..cdbc291514 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -49,6 +49,25 @@ public void Redact_OptionShapedTokenValueDoesNotExposeValue() "--dotnet-test-http-token ***REDACTED***", CommandLineArgumentsRedactor.Redact(["--dotnet-test-http-token", "-secret"])); + [TestMethod] + public void Redact_MasksEveryPositionalSensitiveValueUntilNextOption() + => Assert.AreEqual( + "--dotnet-test-http-token ***REDACTED*** ***REDACTED*** --server dotnettestcli " + + "--dotnet-test-http-endpoint https://gateway.example https://other.example --list-tests", + CommandLineArgumentsRedactor.Redact( + [ + "--dotnet-test-http-token", "first-secret", "second-secret", + "--server", "dotnettestcli", + "--dotnet-test-http-endpoint", "https://gateway.example/private/run", "https://other.example/secret", + "--list-tests", + ])); + + [TestMethod] + [DataRow("--dotnet-test-http-token=", "--dotnet-test-http-token=***REDACTED***")] + [DataRow("--dotnet-test-http-endpoint=", "--dotnet-test-http-endpoint=***REDACTED***")] + public void Redact_MasksEmptyInlineSensitiveValue(string argument, string expected) + => Assert.AreEqual(expected, CommandLineArgumentsRedactor.Redact([argument])); + [TestMethod] [DataRow("not-a-url")] [DataRow("https://user:password@gateway.example/private/run-id")] From 2d20ea69aa53024f557ca4f1f75f5d49ea960c97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:04:22 +0200 Subject: [PATCH 07/21] Redact excess inline option values Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLine/CommandLineArgumentsRedactor.cs | 4 ++-- .../CommandLineArgumentsRedactorTests.cs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index 5e87e86a44..5a57268113 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -31,7 +31,7 @@ public static string Redact(string[] args) redacted[i] = inlineValue is null ? arg : $"{prefix}{name}{delimiter}{RedactedPlaceholder}"; - redactNextValue = inlineValue is null; + redactNextValue = true; sanitizeNextEndpoint = false; sensitiveValueConsumed = inlineValue is not null; } @@ -40,7 +40,7 @@ public static string Redact(string[] args) redacted[i] = inlineValue is null ? arg : $"{prefix}{name}{delimiter}{SanitizeEndpoint(inlineValue)}"; - sanitizeNextEndpoint = inlineValue is null; + sanitizeNextEndpoint = true; redactNextValue = false; sensitiveValueConsumed = inlineValue is not null; } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index cdbc291514..a2665fc192 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -68,6 +68,19 @@ public void Redact_MasksEveryPositionalSensitiveValueUntilNextOption() public void Redact_MasksEmptyInlineSensitiveValue(string argument, string expected) => Assert.AreEqual(expected, CommandLineArgumentsRedactor.Redact([argument])); + [TestMethod] + public void Redact_MasksExcessValuesAfterInlineSensitiveValue() + => Assert.AreEqual( + "--dotnet-test-http-token=***REDACTED*** ***REDACTED*** --server dotnettestcli " + + "--dotnet-test-http-endpoint=https://gateway.example https://other.example --list-tests", + CommandLineArgumentsRedactor.Redact( + [ + "--dotnet-test-http-token=first-secret", "second-secret", + "--server", "dotnettestcli", + "--dotnet-test-http-endpoint=https://gateway.example/private/run", "https://other.example/secret", + "--list-tests", + ])); + [TestMethod] [DataRow("not-a-url")] [DataRow("https://user:password@gateway.example/private/run-id")] From 040233d03a128bd7d4ae63ff41bf80bfe817fa09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:12:13 +0200 Subject: [PATCH 08/21] Redact malformed HTTP transport arguments Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLineArgumentsRedactor.cs | 7 +++++++ .../CommandLine/Parser.cs | 10 +++++++-- .../CommandLineArgumentsRedactorTests.cs | 7 +++++++ .../CommandLine/CommandLineHandlerTests.cs | 21 +++++++++++++++++++ 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index 5a57268113..f2648651b9 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -51,6 +51,13 @@ public static string Redact(string[] args) sanitizeNextEndpoint = false; sensitiveValueConsumed = false; } + else if (sanitizeNextEndpoint && !sensitiveValueConsumed) + { + redacted[i] = SanitizeEndpoint(arg); + redactNextValue = false; + sanitizeNextEndpoint = false; + sensitiveValueConsumed = false; + } else { redacted[i] = arg; diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index f4c728b247..032259e6e9 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -125,9 +125,15 @@ static bool TryUnescape(string input, string? option, IEnvironment environment, { if (input.IndexOf('\'', 1, input.Length - 2) != -1) { + const string redactedPlaceholder = "***REDACTED***"; + string displayInput = + PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(option, StringComparison.OrdinalIgnoreCase) + || PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(option, StringComparison.OrdinalIgnoreCase) + ? redactedPlaceholder + : input; error = option is null - ? string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedSingleQuoteInArgument, input) - : string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedSingleQuoteInArgumentForOption, input, option); + ? string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedSingleQuoteInArgument, displayInput) + : string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedSingleQuoteInArgumentForOption, displayInput, option); return false; } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index a2665fc192..acdd33add5 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -49,6 +49,13 @@ public void Redact_OptionShapedTokenValueDoesNotExposeValue() "--dotnet-test-http-token ***REDACTED***", CommandLineArgumentsRedactor.Redact(["--dotnet-test-http-token", "-secret"])); + [TestMethod] + public void Redact_OptionShapedEndpointValueDoesNotExposeValue() + => Assert.AreEqual( + "--dotnet-test-http-endpoint ***REDACTED***", + CommandLineArgumentsRedactor.Redact( + ["--dotnet-test-http-endpoint", "-https://gateway.example/private/run-id"])); + [TestMethod] public void Redact_MasksEveryPositionalSensitiveValueUntilNextOption() => Assert.AreEqual( diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index cb87ca7c1d..ee9bc2f0b6 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -70,6 +70,27 @@ public async Task ParseAndValidateAsync_InvalidCommandLineRedactsHttpTransportSe Assert.DoesNotContain("/private/run-id", result.ErrorMessage); } + [TestMethod] + [DataRow("--dotnet-test-http-token", "'secret'token'", "secret")] + [DataRow("--dotnet-test-http-endpoint", "'https://gateway.example/private'run'", "/private")] + public async Task ParseAndValidateAsync_ParserErrorsRedactHttpTransportSecrets( + string option, + string value, + string sensitiveFragment) + { + CommandLineParseResult parseResult = CommandLineParser.Parse([option, value], new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains("***REDACTED***", result.ErrorMessage); + Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { From d5d720ae2e5841dd9e67a50e059aac6cfb0f2476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:22:38 +0200 Subject: [PATCH 09/21] Make response cancellation terminal Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 8 +- .../Transport/DotnetTestHttpClient.cs | 16 ++-- .../IPC/DotnetTestHttpClientTests.cs | 80 +++++++++++++++++++ 3 files changed, 94 insertions(+), 10 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index 4a01d95901..092e22a661 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -636,10 +636,10 @@ Automatic redirects are disabled for the same reason: every `3xx` response fails of replaying the authenticated frame at another location. The implicit `HttpClient` timeout is disabled; cancellation is controlled by the operation token passed to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch without converting -expected cancellation into a connection-loss failure. If a handler does not complete its send after -cancellation, the transport is made terminal and the pending send is observed before its request -resources are released, so another protocol request cannot overlap it. Disposal cancels no completed -messages and prevents later use. +expected cancellation into a connection-loss failure. Cancellation after a request starts makes the +transport terminal so another protocol request cannot overlap a partially received reply. If a handler +does not complete its send after cancellation, the pending send is observed before its request resources +are released. Disposal cancels no completed messages and prevents later use. **Server-control pipe (`exitProcessOnConnectionLoss: false`).** A dropped control pipe must **not** kill the test host. This listener runs *inside the test host* as the control-pipe **client**, so an diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index 298e237bce..8b27126e6c 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -170,12 +170,16 @@ await WriteMessageAsync( $"The dotnet test HTTP gateway returned '{response.GetType().Name}' when '{typeof(TResponse).Name}' was expected."), }; } - catch (OperationCanceledException) when (!sendTask.IsCompleted) + catch (OperationCanceledException) { - AbortTransportForIncompleteSend(); - ObserveAndDisposeIncompleteSend(sendTask, httpRequest); - disposeRequest = false; - requestLockAcquired = false; + AbortTransportAfterCancellation(); + if (!sendTask.IsCompleted) + { + ObserveAndDisposeIncompleteSend(sendTask, httpRequest); + disposeRequest = false; + requestLockAcquired = false; + } + throw; } finally @@ -234,7 +238,7 @@ private void CompleteOperation() } } - private void AbortTransportForIncompleteSend() + private void AbortTransportAfterCancellation() { lock (_lifecycleLock) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index 6578861f8e..ad152c229e 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -141,6 +141,38 @@ public async Task RequestReplyAsync_CancellationDoesNotAllowOverlappingSend() pendingResponse.SetResult(CreateResponse(TestResponseFrame())); } + [TestMethod] + public async Task RequestReplyAsync_ResponseBodyCancellationDoesNotAllowOverlappingSend() + { + int requestCount = 0; + var readStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new DelegateHttpMessageHandler((_, _) => + { + Interlocked.Increment(ref requestCount); + var content = new StreamContent(new CancellationBlockingReadStream(readStarted)); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); + }); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + using var cancellationTokenSource = new CancellationTokenSource(); + Task activeRequest = client.RequestReplyAsync( + TestRequest.Instance, + cancellationTokenSource.Token); + await readStarted.Task; + Task waitingRequest = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + + await cancellationTokenSource.CancelAsync(); + + await Assert.ThrowsAsync(() => activeRequest); + await Assert.ThrowsAsync(() => waitingRequest); + Assert.AreEqual(1, requestCount); + Assert.IsFalse(client.IsConnected); + } + [TestMethod] public async Task RequestReplyAsync_UsesCallerCancellationInsteadOfHttpClientTimeout() { @@ -443,4 +475,52 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } + + private sealed class CancellationBlockingReadStream(TaskCompletionSource readStarted) : Stream + { + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set + { + _ = value; + throw new NotSupportedException(); + } + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + => throw new NotSupportedException(); + + public override async Task ReadAsync( + byte[] buffer, + int offset, + int count, + CancellationToken cancellationToken) + { + readStarted.SetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return 0; + } + + public override long Seek(long offset, SeekOrigin origin) + => throw new NotSupportedException(); + + public override void SetLength(long value) + => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) + => throw new NotSupportedException(); + } } From 5c1d5de0bd953a7554426697fd3c5293eb9ac92d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:30:43 +0200 Subject: [PATCH 10/21] Validate HTTP transport option dependencies Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLineArgumentsRedactor.cs | 45 +++++++++++++---- .../CommandLine/Parser.cs | 6 ++- .../PlatformCommandLineProvider.cs | 50 +++++++++---------- .../CommandLineArgumentsRedactorTests.cs | 6 +++ .../CommandLine/CommandLineHandlerTests.cs | 21 ++++++++ .../PlatformCommandLineProviderTests.cs | 25 +++++++++- 6 files changed, 114 insertions(+), 39 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index f2648651b9..5b7a726f91 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -24,8 +24,8 @@ public static string Redact(string[] args) string arg = args[i]; if (TryParseOption(arg, out string? prefix, out string? name, out string? delimiter, out string? inlineValue)) { - bool isToken = PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); - bool isEndpoint = PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); + bool isToken = IsTokenOption(name); + bool isEndpoint = IsEndpointOption(name); if (isToken) { redacted[i] = inlineValue is null @@ -100,28 +100,51 @@ private static bool TryParseOption( delimiter = null; inlineValue = null; - bool isDoubleDash = arg.Length > 2 && arg[0] == '-' && arg[1] == '-' && arg[2] != '-'; - bool isSingleDash = !isDoubleDash && arg.Length > 1 && arg[0] == '-' && arg[1] != '-'; - if (!isDoubleDash && !isSingleDash) + int prefixLength = 0; + while (prefixLength < arg.Length && arg[prefixLength] == '-') + { + prefixLength++; + } + + bool isValidPrefix = prefixLength is 1 or 2; + bool isMalformedPrefix = prefixLength >= 3; + if ((!isValidPrefix && !isMalformedPrefix) || prefixLength == arg.Length) { return false; } - prefix = isDoubleDash ? "--" : "-"; - string withoutPrefix = arg[prefix.Length..]; + prefix = arg[..prefixLength]; + string withoutPrefix = arg[prefixLength..]; int delimiterIndex = withoutPrefix.IndexOfAny(['=', ':']); if (delimiterIndex == -1) { name = withoutPrefix; + } + else + { + name = withoutPrefix[..delimiterIndex]; + delimiter = withoutPrefix[delimiterIndex].ToString(); + inlineValue = withoutPrefix[(delimiterIndex + 1)..]; + } + + if (!isMalformedPrefix || IsTokenOption(name) || IsEndpointOption(name)) + { return true; } - name = withoutPrefix[..delimiterIndex]; - delimiter = withoutPrefix[delimiterIndex].ToString(); - inlineValue = withoutPrefix[(delimiterIndex + 1)..]; - return true; + prefix = null; + name = null; + delimiter = null; + inlineValue = null; + return false; } + private static bool IsTokenOption(string name) + => PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); + + private static bool IsEndpointOption(string name) + => PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(name, StringComparison.OrdinalIgnoreCase); + private static string SanitizeEndpoint(string endpoint) => Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) && uri.Scheme is "http" or "https" diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 032259e6e9..1ddd324508 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -80,7 +80,11 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi { if (currentOption is null) { - errors.Add(string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedArgument, args[i])); + errors.Add( + string.Format( + CultureInfo.InvariantCulture, + PlatformResources.CommandLineParserUnexpectedArgument, + CommandLineArgumentsRedactor.Redact([args[i]]))); } else { diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index f1f742596f..8fd1b1c04d 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -279,32 +279,37 @@ public override Task ValidateCommandLineOptionsAsync(ICommandL return ValidationResult.InvalidTask(PlatformResources.OnlyOneFilterSupported); } + bool hasPipe = commandLineOptions.IsOptionSet(DotNetTestPipeOptionKey); + bool hasTransport = commandLineOptions.TryGetOptionArgumentList(DotNetTestTransportOptionKey, out string[]? transportArguments) + && transportArguments is { Length: 1 }; + bool isPipeTransport = hasTransport + && DotNetTestTransportPipeArgument.Equals(transportArguments![0], StringComparison.OrdinalIgnoreCase); + bool isHttpTransport = hasTransport + && DotNetTestTransportHttpArgument.Equals(transportArguments![0], StringComparison.OrdinalIgnoreCase); + bool hasHttpEndpoint = commandLineOptions.IsOptionSet(DotNetTestHttpEndpointOptionKey); + bool hasHttpToken = commandLineOptions.IsOptionSet(DotNetTestHttpTokenOptionKey); + + if (hasPipe && (isHttpTransport || hasHttpEndpoint || hasHttpToken)) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestTransportConflict); + } + + if (!isHttpTransport && (hasHttpEndpoint || hasHttpToken)) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpOptionsRequireTransport); + } + + if (isHttpTransport && (!hasHttpEndpoint || !hasHttpToken)) + { + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken); + } + // The '--server dotnettestcli' protocol path requires exactly one pre-launch transport: either the // legacy named pipe (implied by '--dotnet-test-pipe') or authenticated HTTP. if (commandLineOptions.TryGetOptionArgumentList(ServerOptionKey, out string[]? serverProtocolArgs) && serverProtocolArgs is { Length: 1 } && DotnetTestCliProtocolName.Equals(serverProtocolArgs[0], StringComparison.OrdinalIgnoreCase)) { - bool hasPipe = commandLineOptions.IsOptionSet(DotNetTestPipeOptionKey); - bool hasTransport = commandLineOptions.TryGetOptionArgumentList(DotNetTestTransportOptionKey, out string[]? transportArguments) - && transportArguments is { Length: 1 }; - bool isPipeTransport = hasTransport - && DotNetTestTransportPipeArgument.Equals(transportArguments![0], StringComparison.OrdinalIgnoreCase); - bool isHttpTransport = hasTransport - && DotNetTestTransportHttpArgument.Equals(transportArguments![0], StringComparison.OrdinalIgnoreCase); - bool hasHttpEndpoint = commandLineOptions.IsOptionSet(DotNetTestHttpEndpointOptionKey); - bool hasHttpToken = commandLineOptions.IsOptionSet(DotNetTestHttpTokenOptionKey); - - if (hasPipe && (isHttpTransport || hasHttpEndpoint || hasHttpToken)) - { - return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestTransportConflict); - } - - if (!isHttpTransport && (hasHttpEndpoint || hasHttpToken)) - { - return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpOptionsRequireTransport); - } - if (!hasPipe && !isHttpTransport) { return ValidationResult.InvalidTask( @@ -313,11 +318,6 @@ public override Task ValidateCommandLineOptionsAsync(ICommandL : PlatformResources.PlatformCommandLineDotnetTestCliRequiresTransport); } - if (isHttpTransport && (!hasHttpEndpoint || !hasHttpToken)) - { - return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken); - } - if (hasPipe && OperatingSystem.IsBrowser()) { return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLinePipeTransportNotSupportedOnBrowser); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index acdd33add5..7e24bb2982 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -56,6 +56,12 @@ public void Redact_OptionShapedEndpointValueDoesNotExposeValue() CommandLineArgumentsRedactor.Redact( ["--dotnet-test-http-endpoint", "-https://gateway.example/private/run-id"])); + [TestMethod] + [DataRow("---dotnet-test-http-token=secret", "---dotnet-test-http-token=***REDACTED***")] + [DataRow("---dotnet-test-http-endpoint=https://gateway.example/private/run", "---dotnet-test-http-endpoint=https://gateway.example")] + public void Redact_MalformedSensitiveOptionPrefixDoesNotExposeValue(string argument, string expected) + => Assert.AreEqual(expected, CommandLineArgumentsRedactor.Redact([argument])); + [TestMethod] public void Redact_MasksEveryPositionalSensitiveValueUntilNextOption() => Assert.AreEqual( diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index ee9bc2f0b6..0fe7142408 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -91,6 +91,27 @@ public async Task ParseAndValidateAsync_ParserErrorsRedactHttpTransportSecrets( Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); } + [TestMethod] + [DataRow("---dotnet-test-http-token=secret-token", "secret-token", "***REDACTED***")] + [DataRow("---dotnet-test-http-endpoint=https://gateway.example/private/run", "/private/run", "https://gateway.example")] + public async Task ParseAndValidateAsync_MalformedSensitiveOptionPrefixIsRedacted( + string argument, + string sensitiveFragment, + string expectedSafeFragment) + { + CommandLineParseResult parseResult = CommandLineParser.Parse([argument], new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains(expectedSafeFragment, result.ErrorMessage); + Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs index 8a951d584e..fa416546e6 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs @@ -406,21 +406,42 @@ public async Task DotnetTestHttpToken_ValidatesBearerSyntax(string token, bool e } [TestMethod] - public async Task IsInvalid_When_HttpTransport_IsIncomplete() + [DataRow(true)] + [DataRow(false)] + public async Task IsInvalid_When_HttpTransport_IsIncomplete(bool includeServer) { var provider = new PlatformCommandLineProvider(); var options = new Dictionary { - [PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"], [PlatformCommandLineProvider.DotNetTestTransportOptionKey] = ["http"], [PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey] = ["https://localhost:1234/dotnettest"], }; + if (includeServer) + { + options[PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"]; + } ValidationResult result = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); Assert.IsFalse(result.IsValid); Assert.AreEqual(PlatformResources.PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken, result.ErrorMessage); } + [TestMethod] + [DataRow(PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey, "https://localhost:1234/dotnettest")] + [DataRow(PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey, "valid-token")] + public async Task IsInvalid_When_HttpOptionHasNoHttpTransport(string optionName, string optionValue) + { + var provider = new PlatformCommandLineProvider(); + var options = new Dictionary + { + [optionName] = [optionValue], + }; + + ValidationResult result = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); + Assert.IsFalse(result.IsValid); + Assert.AreEqual(PlatformResources.PlatformCommandLineDotnetTestHttpOptionsRequireTransport, result.ErrorMessage); + } + [TestMethod] public async Task IsInvalid_When_HttpAndPipeTransportsAreCombined() { From c9281309cc82f285e3370ef89f46fe4e1e40db29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:39:05 +0200 Subject: [PATCH 11/21] Avoid redirect configuration on WASI Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 4 +++- .../DotnetTest/Transport/DotnetTestHttpClient.cs | 13 ++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index 092e22a661..cbeb9d9bf9 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -633,7 +633,9 @@ Gateway loss, DNS/network failure, authentication expiry, or a malformed respons current POST, or by the next POST if the host was idle. A failed request fails the host operation; there is no transparent retry because retrying after an ambiguous network failure could duplicate a message. Automatic redirects are disabled for the same reason: every `3xx` response fails the operation instead -of replaying the authenticated frame at another location. +of replaying the authenticated frame at another location. The WASI handler does not implement automatic +redirects and does not support configuring that property, so the host leaves its default untouched and +still rejects any returned `3xx` status. The implicit `HttpClient` timeout is disabled; cancellation is controlled by the operation token passed to `HttpClient.SendAsync` and response-body reads, aborting the in-flight fetch without converting expected cancellation into a connection-loss failure. Cancellation after a request starts makes the diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index 8b27126e6c..034d4f6181 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -41,7 +41,7 @@ public DotnetTestHttpClient(Uri endpoint, string authToken) : this( endpoint, authToken, - new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }), + CreateHttpClient(), disposeHttpClient: true) { } @@ -238,6 +238,17 @@ private void CompleteOperation() } } + private static HttpClient CreateHttpClient() + { + var handler = new HttpClientHandler(); + if (!OperatingSystem.IsWasi()) + { + handler.AllowAutoRedirect = false; + } + + return new HttpClient(handler); + } + private void AbortTransportAfterCancellation() { lock (_lifecycleLock) From 9b71119c5ef64c012a96396337185463b626d968 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:48:48 +0200 Subject: [PATCH 12/21] Close remaining diagnostic leaks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 7 +++--- .../CommandLineArgumentsRedactor.cs | 10 +++++++-- .../CommandLine/Parser.cs | 2 +- .../InternalAPI/InternalAPI.Unshipped.txt | 1 + .../Transport/DotnetTestHttpClient.cs | 4 +++- .../CommandLine/CommandLineHandlerTests.cs | 22 +++++++++++++++++++ .../IPC/DotnetTestHttpClientTests.cs | 9 ++++++-- 7 files changed, 46 insertions(+), 9 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index cbeb9d9bf9..fd059781f2 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -8,12 +8,12 @@ named-pipe transport or over authenticated HTTP request/reply for environments s It is a *different* protocol from the [JSON-RPC server-mode protocol](./001-protocol-intro.md): -| | JSON-RPC server mode | `dotnet test` pipe protocol (this doc) | +| | JSON-RPC server mode | `dotnet test` binary protocol (this doc) | | --- | --- | --- | | Activation | `--server` (or `--server jsonrpc`) | `--server dotnettestcli` plus named-pipe or HTTP bootstrap options | | Wire format | JSON-RPC 2.0 over stdio / TCP | Custom length-prefixed **binary** frames over a named pipe or HTTP POST bodies | | Shape | Full request/response + notifications, bidirectional | **Push-only** data channel (host → SDK) + auxiliary reverse control channel | -| Role of the runner | Server | Client (connects out to the SDK's pipe server) | +| Role of the runner | Server | Client (connects to the SDK's named-pipe server or HTTP gateway) | > [!IMPORTANT] > **Source of truth.** The wire contract (serializer IDs, field IDs, handshake/session/state @@ -40,7 +40,8 @@ It is a *different* protocol from the [JSON-RPC server-mode protocol](./001-prot - **Test application / test host** — the MTP-based test executable (the process being run by `dotnet test`). In this protocol it is the named-pipe or HTTP **client**. - **SDK / `dotnet test`** — the .NET SDK component that launches test applications and renders their - output. It is the **pipe server** (it creates and listens on the data pipe). + output. It is the named-pipe **server** (creating and listening on the data pipe) or the HTTP + **gateway** (hosting the per-run request/reply endpoint). - **Primary channel** — the host-initiated request/reply channel carrying all handshakes and test data. It is either the data pipe or the HTTP gateway endpoint. - **Data pipe** — the legacy primary-channel named pipe, whose OS name is supplied via diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index 5b7a726f91..f96dc802e2 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -8,10 +8,16 @@ internal static class CommandLineArgumentsRedactor private const string RedactedPlaceholder = "***REDACTED***"; public static string Redact(string[] args) + => string.Join(" ", RedactArguments(args)); + + public static string RedactArgument(string[] args, int index) + => RedactArguments(args)[index]; + + private static string[] RedactArguments(string[] args) { if (args.Length == 0) { - return string.Empty; + return []; } string[] redacted = new string[args.Length]; @@ -85,7 +91,7 @@ public static string Redact(string[] args) } } - return string.Join(" ", redacted); + return redacted; } private static bool TryParseOption( diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 1ddd324508..d0b458f418 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -84,7 +84,7 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi string.Format( CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedArgument, - CommandLineArgumentsRedactor.Redact([args[i]]))); + CommandLineArgumentsRedactor.RedactArgument(originalArgs, i))); } else { diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index 8a456f47d6..8efaa45049 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -198,6 +198,7 @@ Microsoft.Testing.Platform.IPC.DotnetTestHttpClient.RequestReplyAsync System.Threading.Tasks.Task! Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! static Microsoft.Testing.Platform.CommandLine.CommandLineArgumentsRedactor.Redact(string![]! args) -> string! +static Microsoft.Testing.Platform.CommandLine.CommandLineArgumentsRedactor.RedactArgument(string![]! args, int index) -> string! static Microsoft.Testing.Platform.DotnetTestHelper.TryGetDotnetTestTransport(this Microsoft.Testing.Platform.CommandLine.CommandLineHandler! commandLineHandler, out Microsoft.Testing.Platform.DotnetTestTransportKind transport) -> bool *REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! *REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index 034d4f6181..068f41a8d0 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -136,7 +136,9 @@ await WriteMessageAsync( if (responseContent is null || !MediaType.Equals(responseMediaType, StringComparison.OrdinalIgnoreCase)) { throw new IOException( - $"The dotnet test HTTP gateway returned content type '{responseMediaType ?? "missing"}' instead of '{MediaType}'."); + responseMediaType is null + ? $"The dotnet test HTTP gateway returned no content type; expected '{MediaType}'." + : $"The dotnet test HTTP gateway returned an unexpected content type; expected '{MediaType}'."); } if (responseContent.Headers.ContentLength is long contentLength diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index 0fe7142408..743299b250 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -112,6 +112,28 @@ public async Task ParseAndValidateAsync_MalformedSensitiveOptionPrefixIsRedacted Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); } + [TestMethod] + [DataRow("---dotnet-test-http-token", "secret-token", "secret-token", "***REDACTED***")] + [DataRow("---dotnet-test-http-endpoint", "https://gateway.example/private/run", "/private/run", "https://gateway.example")] + public async Task ParseAndValidateAsync_SeparatedMalformedSensitiveOptionValueIsRedacted( + string option, + string value, + string sensitiveFragment, + string expectedSafeFragment) + { + CommandLineParseResult parseResult = CommandLineParser.Parse([option, value], new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains(expectedSafeFragment, result.ErrorMessage); + Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index ad152c229e..f96a1856ac 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -282,6 +282,7 @@ public async Task RequestReplyAsync_RejectsRedirectResponses(HttpStatusCode stat [TestMethod] [DataRow(null)] [DataRow("text/plain")] + [DataRow("application/test-only-256-bit-style-token-value")] public async Task RequestReplyAsync_RejectsUnexpectedResponseContentType(string? mediaType) { HttpResponseMessage response = CreateResponse(TestResponseFrame()); @@ -296,7 +297,11 @@ public async Task RequestReplyAsync_RejectsUnexpectedResponseContentType(string? TestRequest.Instance, _testContext.CancellationToken)); Assert.Contains("content type", exception.Message); - Assert.Contains(mediaType ?? "missing", exception.Message); + Assert.Contains(mediaType is null ? "no content type" : "unexpected content type", exception.Message); + if (mediaType is not null) + { + Assert.DoesNotContain(mediaType, exception.Message); + } } [TestMethod] @@ -312,7 +317,7 @@ public async Task RequestReplyAsync_RejectsMissingResponseContent() client.RequestReplyAsync( TestRequest.Instance, _testContext.CancellationToken)); - Assert.Contains("content type 'missing'", exception.Message); + Assert.Contains("no content type", exception.Message); } [TestMethod] From df4ebb29a7ed1858bb1df67b32dbfcb58bba7379 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 17:54:27 +0200 Subject: [PATCH 13/21] Make failed HTTP requests terminal Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../004-protocol-dotnet-test-pipe.md | 2 ++ .../Transport/DotnetTestHttpClient.cs | 17 +++++----- .../IPC/DotnetTestHttpClientTests.cs | 32 +++++++++++++++++++ 3 files changed, 43 insertions(+), 8 deletions(-) diff --git a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md index fd059781f2..fe9fb4cf1d 100644 --- a/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md +++ b/docs/mstest-runner-protocol/004-protocol-dotnet-test-pipe.md @@ -633,6 +633,8 @@ This is deliberate: if the user kills `dotnet.exe`, the test host must die too r Gateway loss, DNS/network failure, authentication expiry, or a malformed response is detected by the current POST, or by the next POST if the host was idle. A failed request fails the host operation; there is no transparent retry because retrying after an ambiguous network failure could duplicate a message. +Once a POST starts, any transport, authentication, framing, or response failure makes the transport +terminal and cancels queued callers because the SDK and host protocol states may be ambiguous. Automatic redirects are disabled for the same reason: every `3xx` response fails the operation instead of replaying the authenticated frame at another location. The WASI handler does not implement automatic redirects and does not support configuring that property, so the host leaves its default untouched and diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs index 068f41a8d0..f6ca22b7d0 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/Transport/DotnetTestHttpClient.cs @@ -116,13 +116,14 @@ await WriteMessageAsync( }; httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authToken); - Task sendTask = _httpClient.SendAsync( - httpRequest, - HttpCompletionOption.ResponseHeadersRead, - operationCancellationTokenSource.Token); + Task? sendTask = null; bool disposeRequest = true; try { + sendTask = _httpClient.SendAsync( + httpRequest, + HttpCompletionOption.ResponseHeadersRead, + operationCancellationTokenSource.Token); using HttpResponseMessage httpResponse = await sendTask.WaitAsync(operationCancellationTokenSource.Token).ConfigureAwait(false); if (!httpResponse.IsSuccessStatusCode) @@ -172,10 +173,10 @@ responseMediaType is null $"The dotnet test HTTP gateway returned '{response.GetType().Name}' when '{typeof(TResponse).Name}' was expected."), }; } - catch (OperationCanceledException) + catch { - AbortTransportAfterCancellation(); - if (!sendTask.IsCompleted) + AbortTransportAfterFailure(); + if (sendTask is { IsCompleted: false }) { ObserveAndDisposeIncompleteSend(sendTask, httpRequest); disposeRequest = false; @@ -251,7 +252,7 @@ private static HttpClient CreateHttpClient() return new HttpClient(handler); } - private void AbortTransportAfterCancellation() + private void AbortTransportAfterFailure() { lock (_lifecycleLock) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index f96a1856ac..6774736124 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -173,6 +173,38 @@ public async Task RequestReplyAsync_ResponseBodyCancellationDoesNotAllowOverlapp Assert.IsFalse(client.IsConnected); } + [TestMethod] + public async Task RequestReplyAsync_FailureCancelsQueuedRequest() + { + int requestCount = 0; + var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new DelegateHttpMessageHandler(async (_, cancellationToken) => + { + Interlocked.Increment(ref requestCount); + requestStarted.SetResult(); + await releaseResponse.Task.WaitAsync(cancellationToken); + return new HttpResponseMessage(HttpStatusCode.Unauthorized); + }); + + using DotnetTestHttpClient client = CreateClient(handler); + await client.ConnectAsync(_testContext.CancellationToken); + Task activeRequest = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + await requestStarted.Task; + Task waitingRequest = client.RequestReplyAsync( + TestRequest.Instance, + _testContext.CancellationToken); + + releaseResponse.SetResult(); + + await Assert.ThrowsExactlyAsync(() => activeRequest); + await Assert.ThrowsAsync(() => waitingRequest); + Assert.AreEqual(1, requestCount); + Assert.IsFalse(client.IsConnected); + } + [TestMethod] public async Task RequestReplyAsync_UsesCallerCancellationInsteadOfHttpClientTimeout() { From caad62e31618e2270f963c387a9424f57f14275b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:01:28 +0200 Subject: [PATCH 14/21] Validate explicit pipe transport dependency Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLine/PlatformCommandLineProvider.cs | 15 +++++++++++---- .../PlatformCommandLineProviderTests.cs | 10 ++++++++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index 8fd1b1c04d..d4e2780791 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -304,6 +304,16 @@ public override Task ValidateCommandLineOptionsAsync(ICommandL return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestHttpRequiresEndpointAndToken); } + if (isPipeTransport && !hasPipe) + { + return ValidationResult.InvalidTask( + string.Format( + CultureInfo.InvariantCulture, + PlatformResources.PlatformCommandLineDotnetTestCliRequiresPipe, + DotnetTestCliProtocolName, + DotNetTestPipeOptionKey)); + } + // The '--server dotnettestcli' protocol path requires exactly one pre-launch transport: either the // legacy named pipe (implied by '--dotnet-test-pipe') or authenticated HTTP. if (commandLineOptions.TryGetOptionArgumentList(ServerOptionKey, out string[]? serverProtocolArgs) @@ -312,10 +322,7 @@ public override Task ValidateCommandLineOptionsAsync(ICommandL { if (!hasPipe && !isHttpTransport) { - return ValidationResult.InvalidTask( - isPipeTransport - ? string.Format(CultureInfo.InvariantCulture, PlatformResources.PlatformCommandLineDotnetTestCliRequiresPipe, DotnetTestCliProtocolName, DotNetTestPipeOptionKey) - : PlatformResources.PlatformCommandLineDotnetTestCliRequiresTransport); + return ValidationResult.InvalidTask(PlatformResources.PlatformCommandLineDotnetTestCliRequiresTransport); } if (hasPipe && OperatingSystem.IsBrowser()) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs index fa416546e6..56b2e45d72 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/PlatformCommandLineProviderTests.cs @@ -461,14 +461,20 @@ public async Task IsInvalid_When_HttpAndPipeTransportsAreCombined() } [TestMethod] - public async Task IsInvalid_When_ExplicitPipeTransportHasNoPipeName() + [DataRow(null)] + [DataRow("dotnettestcli")] + [DataRow("jsonrpc")] + public async Task IsInvalid_When_ExplicitPipeTransportHasNoPipeName(string? serverProtocol) { var provider = new PlatformCommandLineProvider(); var options = new Dictionary { - [PlatformCommandLineProvider.ServerOptionKey] = ["dotnettestcli"], [PlatformCommandLineProvider.DotNetTestTransportOptionKey] = ["pipe"], }; + if (serverProtocol is not null) + { + options[PlatformCommandLineProvider.ServerOptionKey] = [serverProtocol]; + } ValidationResult result = await provider.ValidateCommandLineOptionsAsync(new TestCommandLineOptions(options)).ConfigureAwait(false); Assert.IsFalse(result.IsValid); From d8862c197ab77af3da016260cb3771faa54c19d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:04:59 +0200 Subject: [PATCH 15/21] Redact expanded response-file arguments Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLine/Parser.cs | 2 +- .../IPC/NamedPipeConnectionBase.cs | 2 +- .../CommandLine/CommandLineHandlerTests.cs | 30 +++++++++++++++++++ .../IPC/DotnetTestHttpClientTests.cs | 2 +- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index d0b458f418..4c877f7842 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -84,7 +84,7 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi string.Format( CultureInfo.InvariantCulture, PlatformResources.CommandLineParserUnexpectedArgument, - CommandLineArgumentsRedactor.RedactArgument(originalArgs, i))); + CommandLineArgumentsRedactor.RedactArgument([.. args], i))); } else { diff --git a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs index 02870a0420..59071045ec 100644 --- a/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs +++ b/src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeConnectionBase.cs @@ -148,7 +148,7 @@ protected async Task WriteMessageAsync(Stream stream, INamedPipeSerializer seria int currentMessageSize = BitConverter.ToInt32(_readBuffer, 0); if (currentMessageSize < sizeof(int) || currentMessageSize > maximumFrameSize - sizeof(int)) { - throw new IOException($"The transport returned an invalid response payload length of {currentMessageSize} bytes."); + throw new IOException($"The transport returned an invalid frame payload length of {currentMessageSize} bytes."); } int missingBytesToReadOfWholeMessage = currentMessageSize; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index 743299b250..cf443fcd93 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -134,6 +134,36 @@ public async Task ParseAndValidateAsync_SeparatedMalformedSensitiveOptionValueIs Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); } + [TestMethod] + [DataRow("---dotnet-test-http-token secret-token", "secret-token", "***REDACTED***")] + [DataRow("---dotnet-test-http-endpoint https://gateway.example/private/run", "/private/run", "https://gateway.example")] + public async Task ParseAndValidateAsync_ResponseFileParserErrorsRedactExpandedSensitiveValues( + string responseFileContent, + string sensitiveFragment, + string expectedSafeFragment) + { + string responseFilePath = Path.GetTempFileName(); + try + { + File.WriteAllText(responseFilePath, responseFileContent); + CommandLineParseResult parseResult = CommandLineParser.Parse([$"@{responseFilePath}"], new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains(expectedSafeFragment, result.ErrorMessage); + Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); + } + finally + { + File.Delete(responseFilePath); + } + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs index 6774736124..6df96227b2 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/DotnetTestHttpClientTests.cs @@ -267,7 +267,7 @@ public async Task RequestReplyAsync_RejectsInvalidChunkedFramePayloadLength(int client.RequestReplyAsync( TestRequest.Instance, _testContext.CancellationToken)); - Assert.Contains("invalid response payload length", exception.Message); + Assert.Contains("invalid frame payload length", exception.Message); } [TestMethod] From 3ff029b4ff2d13bda51598b593a6926e6a4b14b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:10:51 +0200 Subject: [PATCH 16/21] Redact sensitive response-file errors Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLine/Parser.cs | 14 +++++++-- .../CommandLine/ResponseFileHelper.cs | 31 ++++++++++++++++--- .../CommandLine/CommandLineHandlerTests.cs | 23 ++++++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 4c877f7842..b949556372 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -47,10 +47,18 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi { string? currentArg = args[i]; - if (currentArg.StartsWith("@", StringComparison.Ordinal) && ResponseFileHelper.TryReadResponseFile(currentArg.Substring(1), errors, out string[]? newArguments)) + if (currentArg.StartsWith("@", StringComparison.Ordinal)) { - args.InsertRange(i + 1, newArguments); - continue; + string responseFilePath = currentArg.Substring(1); + bool containsSensitiveValue = + PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(currentOption, StringComparison.OrdinalIgnoreCase) + || PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(currentOption, StringComparison.OrdinalIgnoreCase); + string diagnosticPath = containsSensitiveValue ? "***REDACTED***" : responseFilePath; + if (ResponseFileHelper.TryReadResponseFile(responseFilePath, diagnosticPath, errors, out string[]? newArguments)) + { + args.InsertRange(i + 1, newArguments); + continue; + } } // If it's the first argument and it doesn't start with - then it's the tool name diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs index 1850942efb..a0674b3326 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs @@ -8,7 +8,17 @@ // - https://github.com/dotnet/command-line-api/blob/fa1991f84bc8c384aa636a251398a40e56ee1702/src/System.CommandLine/Parsing/StringExtensions.cs#L316 internal static class ResponseFileHelper { - internal static bool TryReadResponseFile(string rspFilePath, ICollection errors, [NotNullWhen(true)] out string[]? newArguments) + internal static bool TryReadResponseFile( + string rspFilePath, + ICollection errors, + [NotNullWhen(true)] out string[]? newArguments) + => TryReadResponseFile(rspFilePath, rspFilePath, errors, out newArguments); + + internal static bool TryReadResponseFile( + string rspFilePath, + string diagnosticPath, + ICollection errors, + [NotNullWhen(true)] out string[]? newArguments) { try { @@ -17,24 +27,37 @@ internal static bool TryReadResponseFile(string rspFilePath, ICollection } catch (FileNotFoundException) { - errors.Add(string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserResponseFileNotFound, rspFilePath)); + errors.Add(string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserResponseFileNotFound, diagnosticPath)); } catch (IOException e) { - errors.Add(string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserFailedToReadResponseFile, rspFilePath, e.ToString())); + errors.Add( + string.Format( + CultureInfo.InvariantCulture, + PlatformResources.CommandLineParserFailedToReadResponseFile, + diagnosticPath, + GetExceptionDetail(e, rspFilePath, diagnosticPath))); } catch (FormatException e) { // Use the full exception detail (not just Message) for consistency with the IOException // branch above; the response file content that triggered a parsing failure (e.g. an // unclosed quote) is easier to diagnose with the complete exception information. - errors.Add(string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserFailedToReadResponseFile, rspFilePath, e.ToString())); + errors.Add( + string.Format( + CultureInfo.InvariantCulture, + PlatformResources.CommandLineParserFailedToReadResponseFile, + diagnosticPath, + GetExceptionDetail(e, rspFilePath, diagnosticPath))); } newArguments = null; return false; // Local functions + static string GetExceptionDetail(Exception exception, string actualPath, string diagnosticPath) + => actualPath == diagnosticPath ? exception.ToString() : exception.GetType().Name; + static IEnumerable ExpandResponseFile(string filePath) { string[] lines = File.ReadAllLines(filePath); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index cf443fcd93..11d6ad5ce1 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -164,6 +164,29 @@ public async Task ParseAndValidateAsync_ResponseFileParserErrorsRedactExpandedSe } } + [TestMethod] + [DataRow("--dotnet-test-http-token", "@secret-token", "secret-token")] + [DataRow("--dotnet-test-http-endpoint", "@private/run-id", "private/run-id")] + public async Task ParseAndValidateAsync_ResponseFileErrorsRedactSensitivePath( + string option, + string responseFileArgument, + string sensitiveFragment) + { + CommandLineParseResult parseResult = CommandLineParser.Parse( + [option, responseFileArgument], + new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains("***REDACTED***", result.ErrorMessage); + Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { From 94e0b13a065b4fb5e98665a7d20da10672fcfe2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:18:16 +0200 Subject: [PATCH 17/21] Redact whitespace-prefixed sensitive options Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLineArgumentsRedactor.cs | 19 +++++++++++----- .../CommandLineArgumentsRedactorTests.cs | 2 ++ .../CommandLine/CommandLineHandlerTests.cs | 22 +++++++++++++++++++ 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs index f96dc802e2..9a5b890153 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineArgumentsRedactor.cs @@ -106,21 +106,28 @@ private static bool TryParseOption( delimiter = null; inlineValue = null; + int optionStart = 0; + while (optionStart < arg.Length && char.IsWhiteSpace(arg[optionStart])) + { + optionStart++; + } + int prefixLength = 0; - while (prefixLength < arg.Length && arg[prefixLength] == '-') + while (optionStart + prefixLength < arg.Length && arg[optionStart + prefixLength] == '-') { prefixLength++; } - bool isValidPrefix = prefixLength is 1 or 2; - bool isMalformedPrefix = prefixLength >= 3; - if ((!isValidPrefix && !isMalformedPrefix) || prefixLength == arg.Length) + bool hasLeadingWhitespace = optionStart > 0; + bool isValidPrefix = !hasLeadingWhitespace && prefixLength is 1 or 2; + bool isMalformedPrefix = hasLeadingWhitespace || prefixLength >= 3; + if ((!isValidPrefix && !isMalformedPrefix) || optionStart + prefixLength == arg.Length) { return false; } - prefix = arg[..prefixLength]; - string withoutPrefix = arg[prefixLength..]; + prefix = arg[..(optionStart + prefixLength)]; + string withoutPrefix = arg[(optionStart + prefixLength)..]; int delimiterIndex = withoutPrefix.IndexOfAny(['=', ':']); if (delimiterIndex == -1) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs index 7e24bb2982..68f1a79d54 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineArgumentsRedactorTests.cs @@ -59,6 +59,8 @@ public void Redact_OptionShapedEndpointValueDoesNotExposeValue() [TestMethod] [DataRow("---dotnet-test-http-token=secret", "---dotnet-test-http-token=***REDACTED***")] [DataRow("---dotnet-test-http-endpoint=https://gateway.example/private/run", "---dotnet-test-http-endpoint=https://gateway.example")] + [DataRow(" --dotnet-test-http-token=secret", " --dotnet-test-http-token=***REDACTED***")] + [DataRow(" --dotnet-test-http-endpoint=https://gateway.example/private/run", " --dotnet-test-http-endpoint=https://gateway.example")] public void Redact_MalformedSensitiveOptionPrefixDoesNotExposeValue(string argument, string expected) => Assert.AreEqual(expected, CommandLineArgumentsRedactor.Redact([argument])); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index 11d6ad5ce1..0071e64777 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -134,6 +134,28 @@ public async Task ParseAndValidateAsync_SeparatedMalformedSensitiveOptionValueIs Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); } + [TestMethod] + [DataRow(" --dotnet-test-http-token", "secret-token", "secret-token", "***REDACTED***")] + [DataRow(" --dotnet-test-http-endpoint", "https://gateway.example/private/run", "/private/run", "https://gateway.example")] + public async Task ParseAndValidateAsync_LeadingWhitespaceSensitiveOptionIsRedacted( + string option, + string value, + string sensitiveFragment, + string expectedSafeFragment) + { + CommandLineParseResult parseResult = CommandLineParser.Parse([option, value], new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains(expectedSafeFragment, result.ErrorMessage); + Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); + } + [TestMethod] [DataRow("---dotnet-test-http-token secret-token", "secret-token", "***REDACTED***")] [DataRow("---dotnet-test-http-endpoint https://gateway.example/private/run", "/private/run", "https://gateway.example")] From 4b2ed239526f02fd946162a3cd18b04015be1dfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:24:44 +0200 Subject: [PATCH 18/21] Declare response-file helper overload Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../InternalAPI/InternalAPI.Unshipped.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt index 8efaa45049..3d036b27b5 100644 --- a/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt +++ b/src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt @@ -199,6 +199,7 @@ Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(Syst Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Stream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! static Microsoft.Testing.Platform.CommandLine.CommandLineArgumentsRedactor.Redact(string![]! args) -> string! static Microsoft.Testing.Platform.CommandLine.CommandLineArgumentsRedactor.RedactArgument(string![]! args, int index) -> string! +static ResponseFileHelper.TryReadResponseFile(string! rspFilePath, string! diagnosticPath, System.Collections.Generic.ICollection! errors, out string![]? newArguments) -> bool static Microsoft.Testing.Platform.DotnetTestHelper.TryGetDotnetTestTransport(this Microsoft.Testing.Platform.CommandLine.CommandLineHandler! commandLineHandler, out Microsoft.Testing.Platform.DotnetTestTransportKind transport) -> bool *REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.ReadNextMessageAsync(System.IO.Pipes.PipeStream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! *REMOVED*Microsoft.Testing.Platform.IPC.NamedPipeConnectionBase.WriteMessageAsync(System.IO.Pipes.PipeStream! stream, Microsoft.Testing.Platform.IPC.INamedPipeSerializer! serializer, object! message, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! From e2fbf0dd011184d0beadbe489ec05156ecd6f271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:33:41 +0200 Subject: [PATCH 19/21] Sanitize response-file access errors Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../CommandLine/ResponseFileHelper.cs | 2 +- .../BrowserWasmExecutionTests.cs | 9 +++++- .../CommandLine/CommandLineHandlerTests.cs | 29 +++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs index a0674b3326..80d6b5b8cd 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs @@ -29,7 +29,7 @@ internal static bool TryReadResponseFile( { errors.Add(string.Format(CultureInfo.InvariantCulture, PlatformResources.CommandLineParserResponseFileNotFound, diagnosticPath)); } - catch (IOException e) + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { errors.Add( string.Format( diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs index 8c6deba164..c6a0e178e7 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/BrowserWasmExecutionTests.cs @@ -18,7 +18,7 @@ namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests; /// node via the same loader, which is what this test uses instead of a real browser. /// /// -/// Five complementary assertions, mirroring : +/// Six complementary assertions, mirroring : /// /// /// builds for @@ -28,6 +28,12 @@ namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests; /// a local machine that has not run the bootstrap), and otherwise a build failure fails the test. /// /// +/// publishes a +/// browser-WASM test application and exercises the authenticated HTTP gateway under Node, +/// covering handshake, help, discovery, execution, authorization, ordering, disconnect, and +/// cancellation behavior. +/// +/// /// publishes a real MSTest project for /// browser-wasm and boots it end-to-end under node via a small /// dotnet.js runner, asserting the passing tests report success and the failing test is @@ -981,6 +987,7 @@ private sealed record HttpGatewayScenarioResult( int ValidFrames, int CancelledRequests, int CancellationSafetyTimerExpirations); + private Task GenerateBrowserWasmCustomHostAssetAsync() { var versions = XDocument.Load(Path.Combine(RootFinder.Find(), "eng", "Versions.props")); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index 0071e64777..42104c2489 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -209,6 +209,35 @@ public async Task ParseAndValidateAsync_ResponseFileErrorsRedactSensitivePath( Assert.DoesNotContain(sensitiveFragment, result.ErrorMessage); } + [TestMethod] + [DataRow("--dotnet-test-http-token")] + [DataRow("--dotnet-test-http-endpoint")] + public async Task ParseAndValidateAsync_ResponseFileAccessErrorsRedactSensitivePath(string option) + { + string directoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directoryPath); + try + { + CommandLineParseResult parseResult = CommandLineParser.Parse( + [option, $"@{directoryPath}"], + new SystemEnvironment()); + + ValidationResult result = await CommandLineOptionsValidator.ValidateAsync( + parseResult, + _systemCommandLineOptionsProviders, + _extensionCommandLineOptionsProviders, + new Mock().Object); + + Assert.IsFalse(result.IsValid); + Assert.Contains("***REDACTED***", result.ErrorMessage); + Assert.DoesNotContain(directoryPath, result.ErrorMessage); + } + finally + { + Directory.Delete(directoryPath); + } + } + [TestMethod] public async Task ParseAndValidateAsync_ValidArgumentWithColonFollowedByValidArgumentWithoutColon_ReturnsTrue() { From eae02311c4cf387837c1d2b533a309fc2e2a2fec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:40:33 +0200 Subject: [PATCH 20/21] Redact relaunched process diagnostics Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../Services/ExecutableInfo.cs | 4 +++- .../CurrentTestApplicationModuleInfoTests.cs | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs b/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs index 80b35d1441..8fed7a0725 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/ExecutableInfo.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Testing.Platform.CommandLine; + namespace Microsoft.Testing.Platform.Services; internal sealed class ExecutableInfo(string filePath, IEnumerable arguments, string workspace) @@ -12,5 +14,5 @@ internal sealed class ExecutableInfo(string filePath, IEnumerable argume public string Workspace { get; } = workspace; public override string ToString() - => $"Process: {FilePath}, Arguments: {string.Join(" ", Arguments)}, Workspace: {Workspace}"; + => $"Process: {FilePath}, Arguments: {CommandLineArgumentsRedactor.Redact([.. Arguments])}, Workspace: {Workspace}"; } diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/CurrentTestApplicationModuleInfoTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/CurrentTestApplicationModuleInfoTests.cs index 2b1328da4d..cdde683c91 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/CurrentTestApplicationModuleInfoTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/CurrentTestApplicationModuleInfoTests.cs @@ -12,6 +12,25 @@ namespace Microsoft.Testing.Platform.UnitTests; [UnsupportedOSPlatform("browser")] public sealed class CurrentTestApplicationModuleInfoTests { + [TestMethod] + public void ExecutableInfo_ToStringRedactsHttpTransportSecrets() + { + var executable = new ExecutableInfo( + "testhost.exe", + [ + "--dotnet-test-http-endpoint", "https://gateway.example/private/run-id", + "--dotnet-test-http-token", "secret-token", + ], + "workspace"); + + string diagnostic = executable.ToString(); + + Assert.Contains("https://gateway.example", diagnostic); + Assert.Contains("***REDACTED***", diagnostic); + Assert.DoesNotContain("/private/run-id", diagnostic); + Assert.DoesNotContain("secret-token", diagnostic); + } + [TestMethod] public void GetCurrentExecutableInfo_AppHost_NoPassedArgs_UsesEnvironmentArgsSkippingProcessPath() { From 7cd0694f87754d8972256a5e39ac3d0907984cc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 23 Jul 2026 18:54:31 +0200 Subject: [PATCH 21/21] Redact malformed response-file paths Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9cf9bdca-8f9a-436e-a367-6689c3fe8fa3 --- .../Microsoft.Testing.Platform/CommandLine/Parser.cs | 8 ++++---- .../CommandLine/CommandLineHandlerTests.cs | 4 ++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index b949556372..a8c0a0832a 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -50,10 +50,10 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi if (currentArg.StartsWith("@", StringComparison.Ordinal)) { string responseFilePath = currentArg.Substring(1); - bool containsSensitiveValue = - PlatformCommandLineProvider.DotNetTestHttpTokenOptionKey.Equals(currentOption, StringComparison.OrdinalIgnoreCase) - || PlatformCommandLineProvider.DotNetTestHttpEndpointOptionKey.Equals(currentOption, StringComparison.OrdinalIgnoreCase); - string diagnosticPath = containsSensitiveValue ? "***REDACTED***" : responseFilePath; + string redactedResponseFileArgument = CommandLineArgumentsRedactor.RedactArgument([.. args], i); + string diagnosticPath = redactedResponseFileArgument.StartsWith("@", StringComparison.Ordinal) + ? redactedResponseFileArgument.Substring(1) + : redactedResponseFileArgument; if (ResponseFileHelper.TryReadResponseFile(responseFilePath, diagnosticPath, errors, out string[]? newArguments)) { args.InsertRange(i + 1, newArguments); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs index 42104c2489..9a3133dddb 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/CommandLine/CommandLineHandlerTests.cs @@ -189,6 +189,10 @@ public async Task ParseAndValidateAsync_ResponseFileParserErrorsRedactExpandedSe [TestMethod] [DataRow("--dotnet-test-http-token", "@secret-token", "secret-token")] [DataRow("--dotnet-test-http-endpoint", "@private/run-id", "private/run-id")] + [DataRow("---dotnet-test-http-token", "@secret-token", "secret-token")] + [DataRow("---dotnet-test-http-endpoint", "@private/run-id", "private/run-id")] + [DataRow(" --dotnet-test-http-token", "@secret-token", "secret-token")] + [DataRow(" --dotnet-test-http-endpoint", "@private/run-id", "private/run-id")] public async Task ParseAndValidateAsync_ResponseFileErrorsRedactSensitivePath( string option, string responseFileArgument,