Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,14 @@ public async Task<TResponse> RequestReplyAsync<TRequest, TResponse>(TRequest req
_namedPipeClientStream.WaitForPipeDrain();
}
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
// The server disconnected while we were writing the request. Mirror the read-EOF handling
// below: if we cannot deliver the request there's no way to recover, so exit abnormally
// instead of surfacing a raw IPC error to the caller.
_environment.Exit((int)ExitCode.GenericFailure);
throw;
}
finally
{
// Reset the buffers
Expand Down Expand Up @@ -190,8 +198,35 @@ public async Task<TResponse> RequestReplyAsync<TRequest, TResponse>(TRequest req
// If currentRequestSize is 0, we need to read the message size
if (currentMessageSize == 0)
{
// We need at least sizeof(int) bytes to parse the message-size header. A pipe read can

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is adding a lot of additional code. Is there a concrete bug that makes it worth adding this?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Reading this as a question rather than a request to revert — happy to do either.)

No specific user-visible repro for the write-side hardening, but it's there to keep the client symmetric with the existing read-EOF path right below it: today, if the server disconnects mid-write the client surfaces a raw IOException/ObjectDisposedException to whoever called RequestReplyAsync (e.g. the test host orchestration code) instead of the deterministic _environment.Exit(GenericFailure) we already use for read-EOF. Two cases this matters in practice:

  1. dotnet test orchestration tears down the test host process mid-RPC — caller gets a raw IO exception instead of the documented exit code.
  2. The MTP host crashes/FailFasts on its end while the client is flushing — same thing.

The concrete server-side bug fixed in this PR (the one with the regression test) is the ApplicationStateGuard.Unreachable() -> FailFast crash on a corrupt/short header byte. The client write-side changes are essentially: 3 lines of catch (Exception ex) when (ex is IOException or ObjectDisposedException) doing what the read-EOF block 30 lines above already does.

If you'd rather I scope this PR down to just the server-side crash + the matching read-side tightening and pull the write-side symmetry into a separate PR (or just drop it), happy to do that — let me know.

// legitimately return fewer bytes on partial frames; keep reading until we have a full
// header or the peer disconnects.
while (currentReadBytes < sizeof(int))
{
#if NETCOREAPP
int additionalBytes = await _namedPipeClientStream.ReadAsync(_readBuffer.AsMemory(currentReadBytes, _readBuffer.Length - currentReadBytes), cancellationToken).ConfigureAwait(false);
#else
int additionalBytes = await _namedPipeClientStream.ReadAsync(_readBuffer, currentReadBytes, _readBuffer.Length - currentReadBytes, cancellationToken).ConfigureAwait(false);
#endif
if (additionalBytes == 0)
{
// Server disconnected mid-header. Treat as the read-EOF case above.
_environment.Exit((int)ExitCode.GenericFailure);
throw new IOException("Pipe closed while reading message header.");
}

currentReadBytes += additionalBytes;
}

// We need to read the message size, first 4 bytes
currentMessageSize = BitConverter.ToInt32(_readBuffer, 0);
if (currentMessageSize < sizeof(int))
{
// Protocol corruption: payload must contain at least a 4-byte serializer id.
_environment.Exit((int)ExitCode.GenericFailure);
throw new InvalidOperationException($"Received invalid IPC message size {currentMessageSize}.");
}

missingBytesToReadOfCurrentChunk = currentReadBytes - sizeof(int);
missingBytesToReadOfWholeMessage = currentMessageSize;
currentReadIndex = sizeof(int);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
Expand All @@ -208,6 +243,13 @@ public async Task<TResponse> RequestReplyAsync<TRequest, TResponse>(TRequest req
missingBytesToReadOfWholeMessage -= missingBytesToReadOfCurrentChunk;
}

if (missingBytesToReadOfWholeMessage < 0)
{
// Protocol corruption: we read more body bytes than the declared message size.
_environment.Exit((int)ExitCode.GenericFailure);
throw new InvalidOperationException("Read more bytes than the declared IPC message size.");
}

// If we have read all the message, we can deserialize it
if (missingBytesToReadOfWholeMessage == 0)
{
Expand All @@ -226,6 +268,14 @@ public async Task<TResponse> RequestReplyAsync<TRequest, TResponse>(TRequest req
{
return (TResponse)responseNamedPipeSerializer.Deserialize(_messageBuffer);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// The response payload is unparseable. Mirror the read-EOF handling: there's no way to
// recover the IPC session, so exit abnormally rather than bubbling a serializer
// exception to the caller.
_environment.Exit((int)ExitCode.GenericFailure);
throw;
}
finally
{
// Reset the message buffer
Expand Down
46 changes: 42 additions & 4 deletions src/Platform/Microsoft.Testing.Platform/IPC/NamedPipeServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,34 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken)
// If currentRequestSize is 0, we need to read the message size
if (currentMessageSize == 0)
{
// We need to read the message size, first 4 bytes
if (currentReadBytes < sizeof(int))
// We need at least sizeof(int) bytes to parse the message-size header. A pipe read can
// legitimately return fewer bytes on partial frames; keep reading until we have a full
// header or the peer disconnects.
while (currentReadBytes < sizeof(int))
{
throw ApplicationStateGuard.Unreachable();
#if NET
int additionalBytes = await _namedPipeServerStream.ReadAsync(_readBuffer.AsMemory(currentReadBytes, _readBuffer.Length - currentReadBytes), cancellationToken).ConfigureAwait(false);
#else
int additionalBytes = await _namedPipeServerStream.ReadAsync(_readBuffer, currentReadBytes, _readBuffer.Length - currentReadBytes, cancellationToken).ConfigureAwait(false);
#endif
if (additionalBytes == 0)
{
// The client disconnected mid-header.
await _logger.LogDebugAsync($"Pipe {PipeName.Name} closed while reading message header; treating as client disconnect.").ConfigureAwait(false);
return;
}

currentReadBytes += additionalBytes;
}

currentMessageSize = BitConverter.ToInt32(_readBuffer, 0);
if (currentMessageSize < sizeof(int))
{
// Protocol corruption: payload must contain at least a 4-byte serializer id. Drop the connection.
await _logger.LogWarningAsync($"Pipe {PipeName.Name} received invalid message size {currentMessageSize}; closing connection.").ConfigureAwait(false);
return;
}

missingBytesToReadOfCurrentChunk = currentReadBytes - sizeof(int);
missingBytesToReadOfWholeMessage = currentMessageSize;
currentReadIndex = sizeof(int);
Expand All @@ -175,7 +196,10 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken)

if (missingBytesToReadOfWholeMessage < 0)
{
throw ApplicationStateGuard.Unreachable();
// Protocol corruption: we read more body bytes than the declared message size. Drop
// the connection rather than fail fast — the peer is misbehaving but the host shouldn't crash.
await _logger.LogWarningAsync($"Pipe {PipeName.Name} read more bytes than the declared message size; closing connection.").ConfigureAwait(false);
return;
}

// If we have read all the message, we can deserialize it
Expand Down Expand Up @@ -250,6 +274,7 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken)
#endif

// Send the message
bool clientDisconnected = false;
try
{
#if NET
Expand All @@ -263,13 +288,26 @@ private async Task InternalLoopAsync(CancellationToken cancellationToken)
_namedPipeServerStream.WaitForPipeDrain();
}
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
// The client disconnected while we were writing the reply. Treat it as a graceful disconnect
// (symmetric with the read-side EOF handling above) so the server loop exits without crashing
// the host.
await _logger.LogDebugAsync($"Pipe {PipeName.Name} broken while writing reply; treating as client disconnect: {ex.Message}").ConfigureAwait(false);
clientDisconnected = true;
}
finally
{
// Reset the buffers
_messageBuffer.Position = 0;
_serializationBuffer.Position = 0;
}

if (clientDisconnected)
{
return;
}

// Reset the control variables
currentMessageSize = 0;
missingBytesToReadOfWholeMessage = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,58 @@
#pragma warning restore VSTHRD103 // Call async methods when in an async method
}

[TestMethod]
public async Task NamedPipeServer_InvalidMessageSizeHeader_DoesNotCrashHost()
{
// Regression: a misbehaving peer that sends a non-positive message-size header used to throw
// ApplicationStateGuard.Unreachable() on the server, which the loop translated into FailFast.
// The server must now close the connection gracefully instead.
PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"));
var serverEnvironment = new SystemEnvironment();
var callbackInvoked = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

NamedPipeServer server = new(
pipeNameDescription,
_ =>
{
callbackInvoked.TrySetResult(true);
return Task.FromResult<IResponse>(VoidResponse.CachedInstance);
},
serverEnvironment,
new Mock<ILogger>().Object,
new SystemTask(),
_testContext.CancellationToken);

try
{
Task waitConnection = server.WaitConnectionAsync(_testContext.CancellationToken);

using (var raw = new System.IO.Pipes.NamedPipeClientStream(".", pipeNameDescription.Name, System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.Asynchronous))

Check failure on line 261 in test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs

View workflow job for this annotation

GitHub Actions / agent

'using' statement can be simplified (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0063)

Check failure on line 261 in test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs

View workflow job for this annotation

GitHub Actions / agent

'using' statement can be simplified (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0063)

Check failure on line 261 in test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs

View workflow job for this annotation

GitHub Actions / agent

'using' statement can be simplified (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0063)

Check failure on line 261 in test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs

View workflow job for this annotation

GitHub Actions / agent

'using' statement can be simplified (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0063)
Comment thread
Evangelink marked this conversation as resolved.
Resolved
{
await raw.ConnectAsync(_testContext.CancellationToken);
await waitConnection;

// Write a zero-length message size header (invalid per protocol).
byte[] invalidHeader = BitConverter.GetBytes(0);
await raw.WriteAsync(invalidHeader, 0, invalidHeader.Length, _testContext.CancellationToken);
await raw.FlushAsync(_testContext.CancellationToken);
}
}
finally
{
#if NETCOREAPP
await server.DisposeAsync();
#else
server.Dispose();
#endif
}

// After the server has been disposed (so the loop task has definitely completed), the callback
// must not have been invoked because the invalid header should be rejected before deserialization.
// If the loop instead crashed via FailFast, the test process would have been terminated.
Assert.IsFalse(callbackInvoked.Task.IsCompleted, "Server callback must not run for an invalid message header.");
}

private static string RandomString(int length, Random random)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Expand Down
Loading