From 9244d121b49f88645234098ae59d28a0ca1f90e4 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Wed, 11 Jan 2023 09:13:42 -0800 Subject: [PATCH] Fix crash when attempting to parse a JSON document that contains an extension field for the wrong type of message. I.e., if foo.extn is an extension for message foo.Foo, attempting to parse the document {"[foo.extn]": 4} as a foo.Bar would crash. This CL causes the parser to return an error instead. PiperOrigin-RevId: 501299336 --- src/google/protobuf/json/internal/parser.cc | 8 ++++++++ src/google/protobuf/json/json_test.cc | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/src/google/protobuf/json/internal/parser.cc b/src/google/protobuf/json/internal/parser.cc index 7b2289a433..80e94634ba 100644 --- a/src/google/protobuf/json/internal/parser.cc +++ b/src/google/protobuf/json/internal/parser.cc @@ -1181,6 +1181,14 @@ absl::Status ParseField(JsonLexer& lex, const Desc& desc, if (absl::StartsWith(name, "[") && absl::EndsWith(name, "]")) { absl::string_view extn_name = name.substr(1, name.size() - 2); field = Traits::ExtensionByName(desc, extn_name); + + auto correct_type_name = Traits::TypeName(desc); + if (Traits::TypeName(Traits::ContainingType(*field)) != correct_type_name) { + return lex.Invalid(absl::StrFormat( + "'%s' is a known extension name, but is not an extenion " + "of '%s' as expected", + extn_name, correct_type_name)); + } } else { field = Traits::FieldByName(desc, name); } diff --git a/src/google/protobuf/json/json_test.cc b/src/google/protobuf/json/json_test.cc index 3e0ad836d7..a6514667ea 100644 --- a/src/google/protobuf/json/json_test.cc +++ b/src/google/protobuf/json/json_test.cc @@ -1042,6 +1042,11 @@ TEST_P(JsonTest, Extensions) { R"("[protobuf_unittest.TestMixedFieldsAndExtensions.c]":42,)" R"("b":[1,2,3],)" R"("[protobuf_unittest.TestMixedFieldsAndExtensions.d]":[1,1,2,3,5,8,13]})")); + + auto m2 = ToProto(R"json({ + "[protobuf_unittest.TestMixedFieldsAndExtensions.c]": 42 + })json"); + EXPECT_THAT(m2, StatusIs(absl::StatusCode::kInvalidArgument)); } // Parsing does NOT work like MergeFrom: existing repeated field values are