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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,11 @@ private async Task HandleRequestAsync(RequestMessage request, CancellationToken
await SendErrorAsync(reqId: request.Id, errorCode: errorCode, message: errorMessage, data: null, cancellationToken).ConfigureAwait(false);
CompleteRequest(ref _clientToServerRequests, request.Id, completion => completion.TrySetCanceled());
}
catch (JsonRpcException e)
{
await SendErrorAsync(reqId: request.Id, errorCode: e.ErrorCode, message: e.Message, data: null, cancellationToken).ConfigureAwait(false);
CompleteRequest(ref _clientToServerRequests, request.Id, completion => completion.TrySetException(e));
}
catch (Exception e)
{
await SendErrorAsync(reqId: request.Id, errorCode: 0, message: e.ToString(), data: null, cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -420,6 +425,11 @@ private async Task<object> HandleRequestCoreAsync(RequestMessage message, RpcInv

switch (message.Method, message.Params)
{
case (_, InvalidRequestParamsArgs invalidParams):
{
throw new JsonRpcException(invalidParams.ErrorCode, invalidParams.ErrorMessage);
}

case (JsonRpcMethods.Initialize, InitializeRequestArgs args):
{
_client = new(args.ClientInfo.Name, args.ClientInfo.Version);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,24 +405,41 @@ public Json(Dictionary<Type, JsonSerializer>? serializers = null, Dictionary<Typ

if (json.TryBind(jsonElement, out string? method, JsonRpcStrings.Method))
{
bool hasId = json.TryBind(jsonElement, out int id, JsonRpcStrings.Id);

object? @params = null;
if (jsonElement.TryGetProperty(JsonRpcStrings.Params, out JsonElement value))
{
// Parse the specific methods
@params = method switch
try
{
// Parse the specific methods
@params = method switch
{
JsonRpcMethods.Initialize => json.Bind<InitializeRequestArgs>(value),
JsonRpcMethods.TestingDiscoverTests => json.Bind<DiscoverRequestArgs>(value),
JsonRpcMethods.TestingRunTests => json.Bind<RunRequestArgs>(value),
JsonRpcMethods.CancelRequest => json.Bind<CancelRequestArgs>(value),
JsonRpcMethods.Exit => json.Bind<ExitRequestArgs>(value),

// Note: Let the server report unknown RPC request back to the client.
_ => null,
};
}
catch (Exception ex) when (ex is MessageFormatException or InvalidOperationException or JsonException)
{
JsonRpcMethods.Initialize => json.Bind<InitializeRequestArgs>(value),
JsonRpcMethods.TestingDiscoverTests => json.Bind<DiscoverRequestArgs>(value),
JsonRpcMethods.TestingRunTests => json.Bind<RunRequestArgs>(value),
JsonRpcMethods.CancelRequest => json.Bind<CancelRequestArgs>(value),
JsonRpcMethods.Exit => json.Bind<ExitRequestArgs>(value),

// Note: Let the server report unknown RPC request back to the client.
_ => null,
};
// If params can't be deserialized for a request, capture the failure so
// we can later send back a properly coded JSON-RPC error using the request id.
// For notifications there's no one to respond to, but we still avoid
// crashing the message-handling loop by swallowing into the sentinel.
// We catch the broader set of deserialization-related exceptions because the
// request payload is untrusted client input and the lower-level helpers
// (e.g. JsonElement.GetString() on a non-string element) can throw types
// other than MessageFormatException.
@params = new InvalidRequestParamsArgs(ErrorCodes.InvalidParams, ex.Message);
}
}

return json.TryBind(jsonElement, out int id, JsonRpcStrings.Id)
return hasId
? new RequestMessage(id, method!, @params)
: new NotificationMessage(method!, @params);
}
Expand Down Expand Up @@ -486,7 +503,10 @@ public Json(Dictionary<Type, JsonSerializer>? serializers = null, Dictionary<Typ
_deserializers[typeof(DiscoverRequestArgs)] = new JsonElementDeserializer<DiscoverRequestArgs>((json, jsonElement) =>
{
string runId = json.Bind<string>(jsonElement, JsonRpcStrings.RunId);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
_ = Guid.TryParse(runId, out Guid result);
if (!Guid.TryParse(runId, out Guid result))
{
throw new MessageFormatException(JsonRpcStrings.InvalidRunIdErrorMessage);
}

json.TryArrayBind(jsonElement, out TestNode[]? testNodes, JsonRpcStrings.Tests);
json.TryBind(jsonElement, out string? graphFilter, JsonRpcStrings.Filter);
Expand All @@ -500,7 +520,10 @@ public Json(Dictionary<Type, JsonSerializer>? serializers = null, Dictionary<Typ
_deserializers[typeof(RunRequestArgs)] = new JsonElementDeserializer<RunRequestArgs>((json, jsonElement) =>
{
string runId = json.Bind<string>(jsonElement, JsonRpcStrings.RunId);
_ = Guid.TryParse(runId, out Guid result);
if (!Guid.TryParse(runId, out Guid result))
{
throw new MessageFormatException(JsonRpcStrings.InvalidRunIdErrorMessage);
}

json.TryArrayBind(jsonElement, out TestNode[]? testNodes, JsonRpcStrings.Tests);
json.TryBind(jsonElement, out string? graphFilter, JsonRpcStrings.Filter);
Expand Down Expand Up @@ -624,21 +647,9 @@ public T Deserialize<T>(ReadOnlyMemory<char> utf8Json)
}

internal T Bind<T>(JsonElement element, string? property = null)
{
if (property is not null)
{
try
{
element = element.GetProperty(property);
}
catch (KeyNotFoundException ex)
{
throw new KeyNotFoundException($"Key '{property}' was not found in the dictionary.", ex);
}
}

return Deserialize<T>(element);
}
=> property is not null && !element.TryGetProperty(property, out element)
? throw new MessageFormatException($"'{property}' field is missing")
: Deserialize<T>(element);

internal bool TryBind<T>(JsonElement element, out T? value, string? property = null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// 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.ServerMode;

/// <summary>
/// Exception used to surface a JSON-RPC error from request handling so that the
/// server message loop can convert it into a properly coded JSON-RPC error
/// response instead of a generic exception payload.
/// </summary>
internal sealed class JsonRpcException : Exception
{
public JsonRpcException(int errorCode, string message)
: base(message)
=> ErrorCode = errorCode;

public int ErrorCode { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ internal static class JsonRpcStrings
public const string Tests = "tests";
public const string Filter = "filter";

// Shared error messages
public const string InvalidRunIdErrorMessage = "'" + RunId + "' field is not a valid Guid";

// Test change message and test change properties
internal const string Parent = "parent";
internal const string Node = "node";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ internal sealed record CancelRequestArgs(int CancelRequestId);

internal sealed record ExitRequestArgs;

/// <summary>
/// Sentinel params type used when a request's params failed to deserialize.
/// The request reaches the handler so a proper JSON-RPC error can be sent back
/// using the request's id rather than crashing the message-handling loop.
/// </summary>
internal sealed record InvalidRequestParamsArgs(int ErrorCode, string ErrorMessage);

internal sealed record ClientInfo(string Name, string Version);

internal sealed record ClientCapabilities(bool DebuggerProvider);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -482,22 +482,33 @@ static SerializerUtilities()
? null
: GetIdFromJson(idObj) ?? throw new MessageFormatException("id field should be a string or an int");

// TODO: Should we be forgiving in the deserialization (if it throws)?
// This way we'd be able to send an ErrorMessage back to the client,
// rather than send a log notification.

// Parse the specific methods
object? @params = method switch
object? @params;
try
{
JsonRpcMethods.Initialize => Deserialize<InitializeRequestArgs>(paramsObj),
JsonRpcMethods.TestingDiscoverTests => Deserialize<DiscoverRequestArgs>(paramsObj),
JsonRpcMethods.TestingRunTests => Deserialize<RunRequestArgs>(paramsObj),
JsonRpcMethods.CancelRequest => Deserialize<CancelRequestArgs>(paramsObj),
JsonRpcMethods.Exit => Deserialize<ExitRequestArgs>(paramsObj),

// Note: Let the server report unknown RPC request back to the client.
_ => null,
};
// Parse the specific methods
@params = method switch
{
JsonRpcMethods.Initialize => Deserialize<InitializeRequestArgs>(paramsObj),
JsonRpcMethods.TestingDiscoverTests => Deserialize<DiscoverRequestArgs>(paramsObj),
JsonRpcMethods.TestingRunTests => Deserialize<RunRequestArgs>(paramsObj),
JsonRpcMethods.CancelRequest => Deserialize<CancelRequestArgs>(paramsObj),
JsonRpcMethods.Exit => Deserialize<ExitRequestArgs>(paramsObj),

// Note: Let the server report unknown RPC request back to the client.
_ => null,
};
}
catch (Exception ex) when (ex is MessageFormatException or InvalidCastException)
{
// If params can't be deserialized for a request, capture the failure so
// we can later send back a properly coded JSON-RPC error using the request id.
// For notifications there's no one to respond to, but we still avoid
// crashing the message-handling loop by swallowing into the sentinel.
// We catch the broader set of deserialization-related exceptions because the
// request payload is untrusted client input and the lower-level helpers can
// throw types other than MessageFormatException.
@params = new InvalidRequestParamsArgs(ErrorCodes.InvalidParams, ex.Message);
}

return id.HasValue
? new RequestMessage(id.Value, method, @params)
Expand Down Expand Up @@ -587,7 +598,11 @@ static SerializerUtilities()

Deserializers[typeof(DiscoverRequestArgs)] = new ObjectDeserializer<DiscoverRequestArgs>(properties =>
{
_ = Guid.TryParse(GetRequiredPropertyFromJson<string>(properties, JsonRpcStrings.RunId), out Guid runId);
string runIdString = GetRequiredPropertyFromJson<string>(properties, JsonRpcStrings.RunId);
if (!Guid.TryParse(runIdString, out Guid runId))
{
throw new MessageFormatException(JsonRpcStrings.InvalidRunIdErrorMessage);
}

var testsJson = GetOptionalPropertyFromJson(properties, JsonRpcStrings.Tests) as ICollection<object>;

Expand All @@ -600,7 +615,11 @@ static SerializerUtilities()

Deserializers[typeof(RunRequestArgs)] = new ObjectDeserializer<RunRequestArgs>(properties =>
{
_ = Guid.TryParse(GetRequiredPropertyFromJson<string>(properties, JsonRpcStrings.RunId), out Guid runId);
string runIdString = GetRequiredPropertyFromJson<string>(properties, JsonRpcStrings.RunId);
if (!Guid.TryParse(runIdString, out Guid runId))
{
throw new MessageFormatException(JsonRpcStrings.InvalidRunIdErrorMessage);
}

var testsJson = GetOptionalPropertyFromJson(properties, JsonRpcStrings.Tests) as ICollection<object>;

Expand Down Expand Up @@ -746,7 +765,14 @@ private static void ValidateJsonRpcHeader(IDictionary<string, object?> propertie
=> properties.TryGetValue(propertyName, out object? propObj) ? propObj : null;

private static T GetRequiredPropertyFromJson<T>(IDictionary<string, object?> properties, string propertyName)
=> (T)(GetOptionalPropertyFromJson(properties, propertyName) ?? throw new MessageFormatException($"'{propertyName}' field is missing"));
{
object? value = GetOptionalPropertyFromJson(properties, propertyName)
?? throw new MessageFormatException($"'{propertyName}' field is missing");

return value is T typed
? typed
: throw new MessageFormatException($"'{propertyName}' field has wrong type (expected {typeof(T).Name})");
}

private static int? GetIdFromJson(object? idObj)
=> idObj switch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,89 @@ public void DeserializeSpecificTypes(Type type)
}
}

[DataRow(typeof(DiscoverRequestArgs))]
[DataRow(typeof(RunRequestArgs))]
[TestMethod]
public void Deserialize_InvalidRunId_ThrowsMessageFormatException(Type type)
{
const string json = """
{
"runId": "not-a-guid"
}
""";

Assert.Throws<MessageFormatException>(() => Deserialize(type, json));
}

[DataRow("testing/discoverTests", "\"runId\": 42")]
[DataRow("testing/runTests", "\"runId\": 42")]
[DataRow("testing/discoverTests", "")]
[DataRow("testing/runTests", "")]
[TestMethod]
public void DeserializeRpcMessage_InvalidRunIdShape_CapturesInvalidParamsSentinel(string method, string runIdProperty)
{
string json = $$"""
{
"jsonrpc": "2.0",
"id": 42,
"method": "{{method}}",
"params": {
{{runIdProperty}}
}
}
""";

#pragma warning disable SA1009 // Closing parenthesis should be spaced correctly
#pragma warning disable SA1111 // Closing parenthesis should be on line of last parameter
RpcMessage msg = _formatter.Deserialize<RpcMessage>(json
#if NETCOREAPP
.AsMemory()
#endif
);
#pragma warning restore SA1111 // Closing parenthesis should be on line of last parameter
#pragma warning restore SA1009 // Closing parenthesis should be spaced correctly

var request = (RequestMessage)msg;
Assert.AreEqual(42, request.Id);
Assert.AreEqual(method, request.Method);
var invalid = (InvalidRequestParamsArgs)request.Params!;
Assert.AreEqual(ErrorCodes.InvalidParams, invalid.ErrorCode);
}

[DataRow("testing/discoverTests")]
[DataRow("testing/runTests")]
[TestMethod]
public void DeserializeRpcMessage_InvalidRunId_CapturesInvalidParamsSentinel(string method)
{
string json = $$"""
{
"jsonrpc": "2.0",
"id": 42,
"method": "{{method}}",
"params": {
"runId": "not-a-guid"
}
}
""";

#pragma warning disable SA1009 // Closing parenthesis should be spaced correctly
#pragma warning disable SA1111 // Closing parenthesis should be on line of last parameter
RpcMessage msg = _formatter.Deserialize<RpcMessage>(json
#if NETCOREAPP
.AsMemory()
#endif
);
#pragma warning restore SA1111 // Closing parenthesis should be on line of last parameter
#pragma warning restore SA1009 // Closing parenthesis should be spaced correctly

var request = (RequestMessage)msg;
Assert.AreEqual(42, request.Id);
Assert.AreEqual(method, request.Method);
var invalid = (InvalidRequestParamsArgs)request.Params!;
Assert.AreEqual(ErrorCodes.InvalidParams, invalid.ErrorCode);
Assert.Contains("runId", invalid.ErrorMessage);
}

private static void AssertRequestArgs<TRequestArgs>(Type type, TRequestArgs actualRequest, TRequestArgs expectedRequest)
where TRequestArgs : RequestArgsBase
{
Expand Down
Loading
Loading