Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import org.msgpack.core.MessageBufferPacker;
import org.msgpack.core.MessageFormat;
import org.msgpack.core.MessageInsufficientBufferException;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePackException;
import org.msgpack.core.MessagePacker;
Expand Down Expand Up @@ -85,6 +86,10 @@ public List<HubMessage> parseMessages(ByteBuffer payload, InvocationBinder binde
} catch (IOException ex) {
throw new RuntimeException("Error reading length header.", ex);
}
int payloadStart = payload.position();
int payloadLimit = payload.limit();
int messageEnd = payloadStart + length;
payload.limit(messageEnd);
// Instantiate MessageUnpacker
try(MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(payload)) {

Expand All @@ -93,16 +98,16 @@ public List<HubMessage> parseMessages(ByteBuffer payload, InvocationBinder binde

switch (messageType) {
case INVOCATION:
hubMessages.add(createInvocationMessage(unpacker, binder, itemCount, payload));
hubMessages.add(createInvocationMessage(unpacker, binder, itemCount, payload, length));
break;
case STREAM_ITEM:
hubMessages.add(createStreamItemMessage(unpacker, binder, payload));
hubMessages.add(createStreamItemMessage(unpacker, binder, payload, length));
break;
case COMPLETION:
hubMessages.add(createCompletionMessage(unpacker, binder, payload));
hubMessages.add(createCompletionMessage(unpacker, binder, payload, length));
break;
case STREAM_INVOCATION:
hubMessages.add(createStreamInvocationMessage(unpacker, binder, itemCount, payload));
hubMessages.add(createStreamInvocationMessage(unpacker, binder, itemCount, payload, length));
break;
case CANCEL_INVOCATION:
hubMessages.add(createCancelInvocationMessage(unpacker));
Expand All @@ -120,8 +125,9 @@ public List<HubMessage> parseMessages(ByteBuffer payload, InvocationBinder binde
int readBytes = (int) unpacker.getTotalReadBytes();
if (readBytes != length) {
// Check what the last message was
// If it was an invocation binding failure, we have to correct the position of the buffer
if (hubMessages.get(hubMessages.size() - 1).getMessageType() == HubMessageType.INVOCATION_BINDING_FAILURE) {
// If it was a binding failure, we have to correct the position of the buffer
if (hubMessages.get(hubMessages.size() - 1).getMessageType() == HubMessageType.INVOCATION_BINDING_FAILURE
|| hubMessages.get(hubMessages.size() - 1).getMessageType() == HubMessageType.STREAM_BINDING_FAILURE) {
// Cast to a Buffer to avoid the Java 9+ behavior where ByteBuffer.position(int) overrides Buffer.position(int),
// Returning a ByteBuffer rather than a Buffer. This causes issues on Android - see https://github.com/dotnet/aspnetcore/pull/26614
((Buffer) payload).position(payload.position() + (length - readBytes));
Expand All @@ -134,12 +140,32 @@ public List<HubMessage> parseMessages(ByteBuffer payload, InvocationBinder binde
// Returning a ByteBuffer rather than a Buffer. This causes issues on Android - see https://github.com/dotnet/aspnetcore/pull/26614
((Buffer) payload).position(payload.position() + readBytes);
} catch (MessagePackException | IOException ex) {
if (ex instanceof MessageInsufficientBufferException && payloadLimit > messageEnd
&& !hasCompleteMessageAt(payload, messageEnd, payloadLimit)) {
throw new RuntimeException(String.format("MessagePack message was length %d but claimed to be length %d.", length + 1, length));
}
throw new RuntimeException("Error reading MessagePack data.", ex);
} finally {
payload.limit(payloadLimit);
}
}
return hubMessages;
}

private boolean hasCompleteMessageAt(ByteBuffer payload, int position, int limit) {
ByteBuffer remaining = payload.duplicate();
remaining.clear();
remaining.limit(limit);
remaining.position(position);

try {
int length = Utils.readLengthHeader(remaining);
return remaining.remaining() >= length;
} catch (IOException | RuntimeException ex) {
return false;
}
}

@Override
public ByteBuffer writeMessage(HubMessage hubMessage) {
HubMessageType messageType = hubMessage.getMessageType();
Expand Down Expand Up @@ -190,7 +216,7 @@ public ByteBuffer writeMessage(HubMessage hubMessage) {
}
}

private HubMessage createInvocationMessage(MessageUnpacker unpacker, InvocationBinder binder, int itemCount, ByteBuffer payload) throws IOException {
private HubMessage createInvocationMessage(MessageUnpacker unpacker, InvocationBinder binder, int itemCount, ByteBuffer payload, int messageLength) throws IOException {
Map<String, String> headers = readHeaders(unpacker);

// invocationId may be nil
Expand All @@ -210,7 +236,7 @@ private HubMessage createInvocationMessage(MessageUnpacker unpacker, InvocationB
Object[] arguments = null;
try {
List<Type> types = binder.getParameterTypes(target);
arguments = bindArguments(unpacker, types, payload);
arguments = bindArguments(unpacker, types, payload, messageLength);
} catch (Exception ex) {
return new InvocationBindingFailureMessage(invocationId, target, ex);
}
Expand All @@ -224,21 +250,21 @@ private HubMessage createInvocationMessage(MessageUnpacker unpacker, InvocationB
return new InvocationMessage(headers, invocationId, target, arguments, streams);
}

private HubMessage createStreamItemMessage(MessageUnpacker unpacker, InvocationBinder binder, ByteBuffer payload) throws IOException {
private HubMessage createStreamItemMessage(MessageUnpacker unpacker, InvocationBinder binder, ByteBuffer payload, int messageLength) throws IOException {
Map<String, String> headers = readHeaders(unpacker);
String invocationId = unpacker.unpackString();
Object value;
try {
Type itemType = binder.getReturnType(invocationId);
value = readValue(unpacker, itemType, payload, true);
value = readValue(unpacker, itemType, payload, true, messageLength);
} catch (Exception ex) {
return new StreamBindingFailureMessage(invocationId, ex);
}

return new StreamItem(headers, invocationId, value);
}

private HubMessage createCompletionMessage(MessageUnpacker unpacker, InvocationBinder binder, ByteBuffer payload) throws IOException {
private HubMessage createCompletionMessage(MessageUnpacker unpacker, InvocationBinder binder, ByteBuffer payload, int messageLength) throws IOException {
Map<String, String> headers = readHeaders(unpacker);
String invocationId = unpacker.unpackString();
int resultKind = unpacker.unpackInt();
Expand All @@ -254,7 +280,7 @@ private HubMessage createCompletionMessage(MessageUnpacker unpacker, InvocationB
break;
case NON_VOID_RESULT:
Type itemType = binder.getReturnType(invocationId);
result = readValue(unpacker, itemType, payload, true);
result = readValue(unpacker, itemType, payload, true, messageLength);
break;
default:
throw new RuntimeException("Invalid invocation result kind.");
Expand All @@ -263,15 +289,15 @@ private HubMessage createCompletionMessage(MessageUnpacker unpacker, InvocationB
return new CompletionMessage(headers, invocationId, result, error);
}

private HubMessage createStreamInvocationMessage(MessageUnpacker unpacker, InvocationBinder binder, int itemCount, ByteBuffer payload) throws IOException {
private HubMessage createStreamInvocationMessage(MessageUnpacker unpacker, InvocationBinder binder, int itemCount, ByteBuffer payload, int messageLength) throws IOException {
Map<String, String> headers = readHeaders(unpacker);
String invocationId = unpacker.unpackString();
String target = unpacker.unpackString();

Object[] arguments = null;
try {
List<Type> types = binder.getParameterTypes(target);
arguments = bindArguments(unpacker, types, payload);
arguments = bindArguments(unpacker, types, payload, messageLength);
} catch (Exception ex) {
return new InvocationBindingFailureMessage(invocationId, target, ex);
}
Expand Down Expand Up @@ -508,7 +534,7 @@ private void writeStreamIds(Collection<String> streamIds, MessagePacker packer)
}
}

private Object[] bindArguments(MessageUnpacker unpacker, List<Type> paramTypes, ByteBuffer payload) throws IOException {
private Object[] bindArguments(MessageUnpacker unpacker, List<Type> paramTypes, ByteBuffer payload, int messageLength) throws IOException {
int argumentCount = unpacker.unpackArrayHeader();

if (paramTypes.size() != argumentCount) {
Expand All @@ -518,13 +544,13 @@ private Object[] bindArguments(MessageUnpacker unpacker, List<Type> paramTypes,
Object[] arguments = new Object[argumentCount];

for (int i = 0; i < argumentCount; i++) {
arguments[i] = readValue(unpacker, paramTypes.get(i), payload, true);
arguments[i] = readValue(unpacker, paramTypes.get(i), payload, true, messageLength);
}

return arguments;
}

private Object readValue(MessageUnpacker unpacker, Type itemType, ByteBuffer payload, boolean outermostCall) throws IOException {
private Object readValue(MessageUnpacker unpacker, Type itemType, ByteBuffer payload, boolean outermostCall, int messageLength) throws IOException {
Class<?> itemClass = Utils.typeToClass(itemType);
MessageFormat messageFormat = unpacker.getNextFormat();
ValueType valueType = messageFormat.getValueType();
Expand Down Expand Up @@ -575,6 +601,9 @@ private Object readValue(MessageUnpacker unpacker, Type itemType, ByteBuffer pay
break;
case BINARY:
length = unpacker.unpackBinaryHeader();
if (length > messageLength - unpacker.getTotalReadBytes()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] [UNRESOLVED] Stream-item binary failures can abort before the stream-binding-failure handler

createStreamItemMessage catches this new IOException and returns STREAM_BINDING_FAILURE, but parseMessages only corrects a short read for INVOCATION_BINDING_FAILURE; it otherwise throws at the frame-length check. A malformed stream item followed by another frame therefore cannot reach HubConnection's existing log-and-drop path or return the following message.

Why unresolved: The frozen repository source establishes the guard/catch/recovery mismatch, but the bundle does not contain the target-version MessagePack implementation or an immutable validation artifact proving the exact unpackBinaryHeader/getTotalReadBytes behavior for the encoded trigger.

Minimal repro: Call parseMessages with {0x09,0x94,0x02,0x80,0xA2,0x69,0x64,0xC4,0x02,0x2A,0x02,0x91,0x06} and a binder returning byte[]: the first frame is a STREAM_ITEM whose bin8 declares two bytes with one byte left, followed by PING.

If the unpacker follows the expected edge, parsing throws the outer length-mismatch exception instead of returning STREAM_BINDING_FAILURE and PING. Consider allowing STREAM_BINDING_FAILURE through the same position correction as INVOCATION_BINDING_FAILURE and covering this sequence in a regression test.

throw new IOException("Binary value length exceeds the remaining message length.");
}
Comment on lines +604 to +606

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.

@copilot Look into this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Bound the unpacker to the current frame and added truncated C4/C5 header coverage that verifies the following ping is preserved. The existing length-mismatch diagnostic remains covered. Commit: 10fd5146.

byte[] binaryValue = new byte[length];
unpacker.readPayload(binaryValue);
item = binaryValue;
Expand All @@ -583,7 +612,7 @@ private Object readValue(MessageUnpacker unpacker, Type itemType, ByteBuffer pay
readBytesStart = unpacker.getTotalReadBytes();
length = unpacker.unpackArrayHeader();
for (int i = 0; i < length; i++) {
readValue(unpacker, Object.class, payload, false);
readValue(unpacker, Object.class, payload, false, messageLength);
}
if (outermostCall) {
// Check how many bytes we've read, grab that from the payload, and deserialize with objectMapper
Expand All @@ -603,8 +632,8 @@ private Object readValue(MessageUnpacker unpacker, Type itemType, ByteBuffer pay
readBytesStart = unpacker.getTotalReadBytes();
length = unpacker.unpackMapHeader();
for (int i = 0; i < length; i++) {
readValue(unpacker, Object.class, payload, false);
readValue(unpacker, Object.class, payload, false);
readValue(unpacker, Object.class, payload, false, messageLength);
readValue(unpacker, Object.class, payload, false, messageLength);
}
if (outermostCall) {
// Check how many bytes we've read, grab that from the payload, and deserialize with objectMapper
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

package com.microsoft.signalr;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
Expand All @@ -18,6 +19,8 @@
import java.util.TreeMap;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import com.microsoft.signalr.messagepack.MessagePackHubProtocol;

Expand Down Expand Up @@ -528,6 +531,117 @@ public void errorWhenLengthHeaderTooLong() {
assertEquals("MessagePack message was length 12 but claimed to be length 13.", exception.getMessage());
}

@ParameterizedTest
@ValueSource(ints = {2, 256, 65536, Integer.MAX_VALUE})
public void invocationBindingFailureWhenBinaryLengthExceedsRemainingBytes(int length) {
byte[] messageBytes = {0x10, (byte) 0x95, 0x01, (byte) 0x80, (byte) 0xC0, (byte) 0xA4, 0x74, 0x65, 0x73, 0x74,
(byte) 0x91, (byte) 0xC6, 0x00, 0x00, 0x00, 0x00, 0x2A};
ByteBuffer message = ByteBuffer.wrap(messageBytes);
message.putInt(12, length);
TestBinder binder = new TestBinder(new Type[] { byte[].class }, null);

List<HubMessage> messages;
try {
messages = messagePackHubProtocol.parseMessages(message, binder);
} catch (OutOfMemoryError ex) {
throw new AssertionError("Binary length must be validated before allocation.", ex);
}

assertEquals(1, messages.size());
assertEquals(HubMessageType.INVOCATION_BINDING_FAILURE, messages.get(0).getMessageType());
InvocationBindingFailureMessage failure = (InvocationBindingFailureMessage) messages.get(0);
assertEquals("Binary value length exceeds the remaining message length.", failure.getException().getMessage());
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
public void binaryLengthCannotIncludeNextMessage(boolean readOnly) {
byte[] messageBytes = {0x0D, (byte) 0x95, 0x01, (byte) 0x80, (byte) 0xC0, (byte) 0xA4, 0x74, 0x65, 0x73, 0x74,
(byte) 0x91, (byte) 0xC4, 0x04, 0x2A, 0x02, (byte) 0x91, 0x06};
ByteBuffer message = ByteBuffer.wrap(messageBytes);
TestBinder binder = new TestBinder(new Type[] { byte[].class }, null);

List<HubMessage> messages = messagePackHubProtocol.parseMessages(readOnly ? message.asReadOnlyBuffer() : message, binder);

assertEquals(2, messages.size());
assertEquals(HubMessageType.INVOCATION_BINDING_FAILURE, messages.get(0).getMessageType());
InvocationBindingFailureMessage failure = (InvocationBindingFailureMessage) messages.get(0);
assertEquals("Binary value length exceeds the remaining message length.", failure.getException().getMessage());
assertEquals(HubMessageType.PING, messages.get(1).getMessageType());
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
public void streamBindingFailureWhenBinaryLengthExceedsRemainingBytesPreservesNextMessage(boolean readOnly) {
byte[] messageBytes = {0x09, (byte) 0x94, 0x02, (byte) 0x80, (byte) 0xA2, 0x69, 0x64,
(byte) 0xC4, 0x02, 0x2A, 0x02, (byte) 0x91, 0x06};
ByteBuffer message = ByteBuffer.wrap(messageBytes);
TestBinder binder = new TestBinder(null, byte[].class);

List<HubMessage> messages = messagePackHubProtocol.parseMessages(readOnly ? message.asReadOnlyBuffer() : message, binder);

assertEquals(2, messages.size());
assertEquals(HubMessageType.STREAM_BINDING_FAILURE, messages.get(0).getMessageType());
StreamBindingFailureMessage failure = (StreamBindingFailureMessage) messages.get(0);
assertEquals("id", failure.getInvocationId());
assertEquals("Binary value length exceeds the remaining message length.", failure.getException().getMessage());
assertEquals(HubMessageType.PING, messages.get(1).getMessageType());
}

@ParameterizedTest
@ValueSource(bytes = {(byte) 0xC4, (byte) 0xC5})
public void truncatedBinaryHeaderCannotReadNextMessage(byte binaryHeader) {
byte[] messageBytes = {0x0B, (byte) 0x95, 0x01, (byte) 0x80, (byte) 0xC0, (byte) 0xA4, 0x74, 0x65, 0x73, 0x74,
(byte) 0x91, binaryHeader, 0x02, (byte) 0x91, 0x06};
TestBinder binder = new TestBinder(new Type[] { byte[].class }, null);

List<HubMessage> messages = messagePackHubProtocol.parseMessages(ByteBuffer.wrap(messageBytes), binder);

assertEquals(2, messages.size());
assertEquals(HubMessageType.INVOCATION_BINDING_FAILURE, messages.get(0).getMessageType());
InvocationBindingFailureMessage failure = (InvocationBindingFailureMessage) messages.get(0);
assertEquals("MessageInsufficientBufferException", failure.getException().getClass().getSimpleName());
assertEquals(HubMessageType.PING, messages.get(1).getMessageType());
}

@Test
public void invocationBindingFailureWhenNestedBinaryLengthExceedsRemainingBytes() {
byte[] messageBytes = {0x0E, (byte) 0x95, 0x01, (byte) 0x80, (byte) 0xC0, (byte) 0xA4, 0x74, 0x65, 0x73, 0x74,
(byte) 0x91, (byte) 0x91, (byte) 0xC5, 0x01, 0x00};
TestBinder binder = new TestBinder(new Type[] { byte[][].class }, null);

List<HubMessage> messages = messagePackHubProtocol.parseMessages(ByteBuffer.wrap(messageBytes), binder);

assertEquals(1, messages.size());
assertEquals(HubMessageType.INVOCATION_BINDING_FAILURE, messages.get(0).getMessageType());
InvocationBindingFailureMessage failure = (InvocationBindingFailureMessage) messages.get(0);
assertEquals("Binary value length exceeds the remaining message length.", failure.getException().getMessage());
}

@ParameterizedTest
@ValueSource(ints = {0, 1, 3})
public void parseBinaryValueAtMessageBoundary(int length) {
ByteBuffer message = ByteBuffer.allocate(16 + length);
message.put(new byte[] {(byte) (12 + length), (byte) 0x95, 0x01, (byte) 0x80, (byte) 0xC0, (byte) 0xA4,
0x74, 0x65, 0x73, 0x74, (byte) 0x91, (byte) 0xC4, (byte) length});
byte[] expected = new byte[length];
for (int i = 0; i < length; i++) {
expected[i] = (byte) (i + 1);
}
message.put(expected);
message.put(new byte[] {0x02, (byte) 0x91, 0x06});
message.flip();
TestBinder binder = new TestBinder(new Type[] { byte[].class }, null);

List<HubMessage> messages = messagePackHubProtocol.parseMessages(message, binder);

assertEquals(2, messages.size());
assertEquals(HubMessageType.INVOCATION, messages.get(0).getMessageType());
InvocationMessage invocation = (InvocationMessage) messages.get(0);
assertArrayEquals(expected, (byte[]) invocation.getArguments()[0]);
assertEquals(HubMessageType.PING, messages.get(1).getMessageType());
}

@Test
public void errorWhenLengthHeaderTooShort() {
byte[] messageBytes = {0x0B, (byte) 0x96, 0x01, (byte) 0x80, (byte) 0xC0, (byte) 0xA4, 0x74, 0x65, 0x73, 0x74, (byte) 0x91,
Expand Down