encoding/prototext: fix parsing of field names

Previous code tries to do all-lowercase match all non-extension field
names to match group field names, which is incorrect. Fix to check for
only group field type and make sure that the format is correct as well.

Fixes golang/protobuf#878.

Fix typo in text proto string in internal/impl/message_test.go that
wasn't caught before due to above issue.

Change-Id: Ief952907306435ed76a095e96e29fcc9c0027b73
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/183737
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
diff --git a/encoding/prototext/decode.go b/encoding/prototext/decode.go
index a7fc2bf..df05f95 100644
--- a/encoding/prototext/decode.go
+++ b/encoding/prototext/decode.go
@@ -95,9 +95,19 @@
 		case text.Name:
 			name, _ = tkey.Name()
 			fd = fieldDescs.ByName(name)
+			// The proto name of a group field is in all lowercase. However, the
+			// textproto field name is the type name. Check to make sure that
+			// group name is correct.
 			if fd == nil {
-				// Check if this is a group field.
-				fd = fieldDescs.ByName(pref.Name(strings.ToLower(string(name))))
+				gd := fieldDescs.ByName(pref.Name(strings.ToLower(string(name))))
+				if gd != nil && gd.Kind() == pref.GroupKind && gd.Message().Name() == name {
+					fd = gd
+				}
+			} else {
+				if fd.Kind() == pref.GroupKind && fd.Message().Name() != name {
+					// Reset fd to nil because name does not match.
+					fd = nil
+				}
 			}
 		case text.String:
 			// Handle extensions only. This code path is not for Any.
diff --git a/encoding/prototext/decode_test.go b/encoding/prototext/decode_test.go
index 32d9be8..7f0a4e8 100644
--- a/encoding/prototext/decode_test.go
+++ b/encoding/prototext/decode_test.go
@@ -121,6 +121,11 @@
 			OptString:   scalar.String("谷歌"),
 		},
 	}, {
+		desc:         "case sensitive",
+		inputMessage: &pb3.Scalars{},
+		inputText:    `S_BOOL: true`,
+		wantErr:      true,
+	}, {
 		desc:         "proto3 scalars",
 		inputMessage: &pb3.Scalars{},
 		inputText: `s_bool: true
@@ -404,6 +409,11 @@
 			Optgroup:  &pb2.Nests_OptGroup{},
 		},
 	}, {
+		desc:         "group field name",
+		inputMessage: &pb2.Nests{},
+		inputText:    `optgroup: {}`,
+		wantErr:      true,
+	}, {
 		desc:         "proto2 nested messages",
 		inputMessage: &pb2.Nests{},
 		inputText: `