diff --git a/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java b/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java index ff638b74..8da8d794 100644 --- a/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java +++ b/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java @@ -624,6 +624,9 @@ public ImmutableValue unpackValue() return ValueFactory.newFloat(unpackDouble()); case STRING: { int length = unpackRawStringHeader(); + if (length > stringSizeLimit) { + throw new MessageSizeException(String.format("cannot unpack a String of size larger than %,d: %,d", stringSizeLimit, length), length); + } return ValueFactory.newString(readPayload(length), true); } case BINARY: { @@ -689,6 +692,9 @@ public Variable unpackValue(Variable var) return var; case STRING: { int length = unpackRawStringHeader(); + if (length > stringSizeLimit) { + throw new MessageSizeException(String.format("cannot unpack a String of size larger than %,d: %,d", stringSizeLimit, length), length); + } var.setStringValue(readPayload(length)); return var; } diff --git a/msgpack-core/src/test/scala/org/msgpack/core/StringLimitTest.scala b/msgpack-core/src/test/scala/org/msgpack/core/StringLimitTest.scala new file mode 100644 index 00000000..96319a7f --- /dev/null +++ b/msgpack-core/src/test/scala/org/msgpack/core/StringLimitTest.scala @@ -0,0 +1,37 @@ +package org.msgpack.core + +import org.msgpack.core.MessagePack.UnpackerConfig +import org.msgpack.value.Variable +import wvlet.airspec.AirSpec + +class StringLimitTest extends AirSpec { + + test("throws an exception when the string size exceeds a limit") { + val customLimit = 100 + val packer = MessagePack.newDefaultBufferPacker() + packer.packString("a" * (customLimit + 1)) + val msgpack = packer.toByteArray + + test("unpackString") { + val unpacker = new UnpackerConfig().withStringSizeLimit(customLimit).newUnpacker(msgpack) + intercept[MessageSizeException] { + unpacker.unpackString() + } + } + + test("unpackValue") { + val unpacker = new UnpackerConfig().withStringSizeLimit(customLimit).newUnpacker(msgpack) + intercept[MessageSizeException] { + unpacker.unpackValue() + } + } + + test("unpackValue(var)") { + val unpacker = new UnpackerConfig().withStringSizeLimit(customLimit).newUnpacker(msgpack) + intercept[MessageSizeException] { + val v = new Variable() + unpacker.unpackValue(v) + } + } + } +}