From bbd5282abfcbb09665e24710bd84a13b981b9961 Mon Sep 17 00:00:00 2001 From: Paul Yang Date: Thu, 12 Jul 2018 11:04:29 -0700 Subject: [PATCH] Check the message to be encoded is the wrong type. (#4885) --- ruby/ext/google/protobuf_c/encode_decode.c | 7 +++++++ ruby/tests/encode_decode_test.rb | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/ruby/ext/google/protobuf_c/encode_decode.c b/ruby/ext/google/protobuf_c/encode_decode.c index 12080d034a75..5f11fcd1c53b 100644 --- a/ruby/ext/google/protobuf_c/encode_decode.c +++ b/ruby/ext/google/protobuf_c/encode_decode.c @@ -1106,6 +1106,13 @@ static void putmsg(VALUE msg_rb, const Descriptor* desc, TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg); + if (desc != msg->descriptor) { + rb_raise(cTypeError, + "The type of given msg is '%s', expect '%s'.", + upb_msgdef_fullname(msg->descriptor->msgdef), + upb_msgdef_fullname(desc->msgdef)); + } + for (upb_msg_field_begin(&i, desc->msgdef); !upb_msg_field_done(&i); upb_msg_field_next(&i)) { diff --git a/ruby/tests/encode_decode_test.rb b/ruby/tests/encode_decode_test.rb index 2bd9b98b5a9a..95c2cfa4700c 100644 --- a/ruby/tests/encode_decode_test.rb +++ b/ruby/tests/encode_decode_test.rb @@ -84,4 +84,14 @@ def test_encode_json assert_match 'optional_int32', json end + + def test_encode_wrong_msg + e = assert_raise Google::Protobuf::TypeError do + m = A::B::C::TestMessage.new( + :optional_int32 => 1, + ) + Google::Protobuf::Any.encode(m) + end + end + end