desc_validate.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package protodesc
  5. import (
  6. "strings"
  7. "unicode"
  8. "google.golang.org/protobuf/internal/encoding/wire"
  9. "google.golang.org/protobuf/internal/errors"
  10. "google.golang.org/protobuf/internal/filedesc"
  11. "google.golang.org/protobuf/internal/flags"
  12. "google.golang.org/protobuf/internal/strs"
  13. "google.golang.org/protobuf/reflect/protoreflect"
  14. "google.golang.org/protobuf/types/descriptorpb"
  15. )
  16. func validateEnumDeclarations(es []filedesc.Enum, eds []*descriptorpb.EnumDescriptorProto) error {
  17. for i, ed := range eds {
  18. e := &es[i]
  19. if err := e.L2.ReservedNames.CheckValid(); err != nil {
  20. return errors.New("enum %q reserved names has %v", e.FullName(), err)
  21. }
  22. if err := e.L2.ReservedRanges.CheckValid(); err != nil {
  23. return errors.New("enum %q reserved ranges has %v", e.FullName(), err)
  24. }
  25. if len(ed.GetValue()) == 0 {
  26. return errors.New("enum %q must contain at least one value declaration", e.FullName())
  27. }
  28. allowAlias := ed.GetOptions().GetAllowAlias()
  29. foundAlias := false
  30. for i := 0; i < e.Values().Len(); i++ {
  31. v1 := e.Values().Get(i)
  32. if v2 := e.Values().ByNumber(v1.Number()); v1 != v2 {
  33. foundAlias = true
  34. if !allowAlias {
  35. return errors.New("enum %q has conflicting non-aliased values on number %d: %q with %q", e.FullName(), v1.Number(), v1.Name(), v2.Name())
  36. }
  37. }
  38. }
  39. if allowAlias && !foundAlias {
  40. return errors.New("enum %q allows aliases, but none were found", e.FullName())
  41. }
  42. if e.Syntax() == protoreflect.Proto3 {
  43. if v := e.Values().Get(0); v.Number() != 0 {
  44. return errors.New("enum %q using proto3 semantics must have zero number for the first value", v.FullName())
  45. }
  46. // Verify that value names in proto3 do not conflict if the
  47. // case-insensitive prefix is removed.
  48. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:4991-5055
  49. names := map[string]protoreflect.EnumValueDescriptor{}
  50. prefix := strings.Replace(strings.ToLower(string(e.Name())), "_", "", -1)
  51. for i := 0; i < e.Values().Len(); i++ {
  52. v1 := e.Values().Get(i)
  53. s := strs.EnumValueName(strs.TrimEnumPrefix(string(v1.Name()), prefix))
  54. if v2, ok := names[s]; ok && v1.Number() != v2.Number() {
  55. return errors.New("enum %q using proto3 semantics has conflict: %q with %q", e.FullName(), v1.Name(), v2.Name())
  56. }
  57. names[s] = v1
  58. }
  59. }
  60. for j, vd := range ed.GetValue() {
  61. v := &e.L2.Values.List[j]
  62. if vd.Number == nil {
  63. return errors.New("enum value %q must have a specified number", v.FullName())
  64. }
  65. if e.L2.ReservedNames.Has(v.Name()) {
  66. return errors.New("enum value %q must not use reserved name", v.FullName())
  67. }
  68. if e.L2.ReservedRanges.Has(v.Number()) {
  69. return errors.New("enum value %q must not use reserved number %d", v.FullName(), v.Number())
  70. }
  71. }
  72. }
  73. return nil
  74. }
  75. func validateMessageDeclarations(ms []filedesc.Message, mds []*descriptorpb.DescriptorProto) error {
  76. for i, md := range mds {
  77. m := &ms[i]
  78. // Handle the message descriptor itself.
  79. isMessageSet := md.GetOptions().GetMessageSetWireFormat()
  80. if err := m.L2.ReservedNames.CheckValid(); err != nil {
  81. return errors.New("message %q reserved names has %v", m.FullName(), err)
  82. }
  83. if err := m.L2.ReservedRanges.CheckValid(isMessageSet); err != nil {
  84. return errors.New("message %q reserved ranges has %v", m.FullName(), err)
  85. }
  86. if err := m.L2.ExtensionRanges.CheckValid(isMessageSet); err != nil {
  87. return errors.New("message %q extension ranges has %v", m.FullName(), err)
  88. }
  89. if err := (*filedesc.FieldRanges).CheckOverlap(&m.L2.ReservedRanges, &m.L2.ExtensionRanges); err != nil {
  90. return errors.New("message %q reserved and extension ranges has %v", m.FullName(), err)
  91. }
  92. for i := 0; i < m.Fields().Len(); i++ {
  93. f1 := m.Fields().Get(i)
  94. if f2 := m.Fields().ByNumber(f1.Number()); f1 != f2 {
  95. return errors.New("message %q has conflicting fields: %q with %q", m.FullName(), f1.Name(), f2.Name())
  96. }
  97. }
  98. if isMessageSet && !flags.ProtoLegacy {
  99. return errors.New("message %q is a MessageSet, which is a legacy proto1 feature that is no longer supported", m.FullName())
  100. }
  101. if isMessageSet && (m.Syntax() != protoreflect.Proto2 || m.Fields().Len() > 0 || m.ExtensionRanges().Len() == 0) {
  102. return errors.New("message %q is an invalid proto1 MessageSet", m.FullName())
  103. }
  104. if m.Syntax() == protoreflect.Proto3 {
  105. if m.ExtensionRanges().Len() > 0 {
  106. return errors.New("message %q using proto3 semantics cannot have extension ranges", m.FullName())
  107. }
  108. // Verify that field names in proto3 do not conflict if lowercased
  109. // with all underscores removed.
  110. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:5830-5847
  111. names := map[string]protoreflect.FieldDescriptor{}
  112. for i := 0; i < m.Fields().Len(); i++ {
  113. f1 := m.Fields().Get(i)
  114. s := strings.Replace(strings.ToLower(string(f1.Name())), "_", "", -1)
  115. if f2, ok := names[s]; ok {
  116. return errors.New("message %q using proto3 semantics has conflict: %q with %q", m.FullName(), f1.Name(), f2.Name())
  117. }
  118. names[s] = f1
  119. }
  120. }
  121. for j, fd := range md.GetField() {
  122. f := &m.L2.Fields.List[j]
  123. if m.L2.ReservedNames.Has(f.Name()) {
  124. return errors.New("message field %q must not use reserved name", f.FullName())
  125. }
  126. if !f.Number().IsValid() {
  127. return errors.New("message field %q has an invalid number: %d", f.FullName(), f.Number())
  128. }
  129. if !f.Cardinality().IsValid() {
  130. return errors.New("message field %q has an invalid cardinality: %d", f.FullName(), f.Cardinality())
  131. }
  132. if m.L2.ReservedRanges.Has(f.Number()) {
  133. return errors.New("message field %q must not use reserved number %d", f.FullName(), f.Number())
  134. }
  135. if m.L2.ExtensionRanges.Has(f.Number()) {
  136. return errors.New("message field %q with number %d in extension range", f.FullName(), f.Number())
  137. }
  138. if fd.Extendee != nil {
  139. return errors.New("message field %q may not have extendee: %q", f.FullName(), fd.GetExtendee())
  140. }
  141. if f.IsWeak() && !flags.ProtoLegacy {
  142. return errors.New("message field %q is a weak field, which is a legacy proto1 feature that is no longer supported", f.FullName())
  143. }
  144. if f.IsWeak() && (f.Syntax() != protoreflect.Proto2 || !isOptionalMessage(f) || f.ContainingOneof() != nil) {
  145. return errors.New("message field %q may only be weak for an optional message", f.FullName())
  146. }
  147. if f.IsPacked() && !isPackable(f) {
  148. return errors.New("message field %q is not packable", f.FullName())
  149. }
  150. if err := checkValidGroup(f); err != nil {
  151. return errors.New("message field %q is an invalid group: %v", f.FullName(), err)
  152. }
  153. if err := checkValidMap(f); err != nil {
  154. return errors.New("message field %q is an invalid map: %v", f.FullName(), err)
  155. }
  156. if f.Syntax() == protoreflect.Proto3 {
  157. if f.Cardinality() == protoreflect.Required {
  158. return errors.New("message field %q using proto3 semantics cannot be required", f.FullName())
  159. }
  160. if f.Enum() != nil && !f.Enum().IsPlaceholder() && f.Enum().Syntax() != protoreflect.Proto3 {
  161. return errors.New("message field %q using proto3 semantics may only depend on a proto3 enum", f.FullName())
  162. }
  163. }
  164. }
  165. for j := range md.GetOneofDecl() {
  166. o := &m.L2.Oneofs.List[j]
  167. if o.Fields().Len() == 0 {
  168. return errors.New("message oneof %q must contain at least one field declaration", o.FullName())
  169. }
  170. if n := o.Fields().Len(); n-1 != (o.Fields().Get(n-1).Index() - o.Fields().Get(0).Index()) {
  171. return errors.New("message oneof %q must have consecutively declared fields", o.FullName())
  172. }
  173. for i := 0; i < o.Fields().Len(); i++ {
  174. f := o.Fields().Get(i)
  175. if f.Cardinality() != protoreflect.Optional {
  176. return errors.New("message field %q belongs in a oneof and must be optional", f.FullName())
  177. }
  178. if f.IsWeak() {
  179. return errors.New("message field %q belongs in a oneof and must not be a weak reference", f.FullName())
  180. }
  181. }
  182. }
  183. if err := validateEnumDeclarations(m.L1.Enums.List, md.GetEnumType()); err != nil {
  184. return err
  185. }
  186. if err := validateMessageDeclarations(m.L1.Messages.List, md.GetNestedType()); err != nil {
  187. return err
  188. }
  189. if err := validateExtensionDeclarations(m.L1.Extensions.List, md.GetExtension()); err != nil {
  190. return err
  191. }
  192. }
  193. return nil
  194. }
  195. func validateExtensionDeclarations(xs []filedesc.Extension, xds []*descriptorpb.FieldDescriptorProto) error {
  196. for i, xd := range xds {
  197. x := &xs[i]
  198. // NOTE: Avoid using the IsValid method since extensions to MessageSet
  199. // may have a field number higher than normal. This check only verifies
  200. // that the number is not negative or reserved. We check again later
  201. // if we know that the extendee is definitely not a MessageSet.
  202. if n := x.Number(); n < 0 || (wire.FirstReservedNumber <= n && n <= wire.LastReservedNumber) {
  203. return errors.New("extension field %q has an invalid number: %d", x.FullName(), x.Number())
  204. }
  205. if !x.Cardinality().IsValid() || x.Cardinality() == protoreflect.Required {
  206. return errors.New("extension field %q has an invalid cardinality: %d", x.FullName(), x.Cardinality())
  207. }
  208. if xd.JsonName != nil {
  209. if xd.GetJsonName() != strs.JSONCamelCase(string(x.Name())) {
  210. return errors.New("extension field %q may not have an explicitly set JSON name: %q", x.FullName(), xd.GetJsonName())
  211. }
  212. }
  213. if xd.OneofIndex != nil {
  214. return errors.New("extension field %q may not be part of a oneof", x.FullName())
  215. }
  216. if md := x.ContainingMessage(); !md.IsPlaceholder() {
  217. if !md.ExtensionRanges().Has(x.Number()) {
  218. return errors.New("extension field %q extends %q with non-extension field number: %d", x.FullName(), md.FullName(), x.Number())
  219. }
  220. isMessageSet := md.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat()
  221. if isMessageSet && !isOptionalMessage(x) {
  222. return errors.New("extension field %q extends MessageSet and must be an optional message", x.FullName())
  223. }
  224. if !isMessageSet && !x.Number().IsValid() {
  225. return errors.New("extension field %q has an invalid number: %d", x.FullName(), x.Number())
  226. }
  227. }
  228. if xd.GetOptions().GetWeak() {
  229. return errors.New("extension field %q cannot be a weak reference", x.FullName())
  230. }
  231. if x.IsPacked() && !isPackable(x) {
  232. return errors.New("extension field %q is not packable", x.FullName())
  233. }
  234. if err := checkValidGroup(x); err != nil {
  235. return errors.New("extension field %q is an invalid group: %v", x.FullName(), err)
  236. }
  237. if md := x.Message(); md != nil && md.IsMapEntry() {
  238. return errors.New("extension field %q cannot be a map entry", x.FullName())
  239. }
  240. if x.Syntax() == protoreflect.Proto3 {
  241. switch x.ContainingMessage().FullName() {
  242. case (*descriptorpb.FileOptions)(nil).ProtoReflect().Descriptor().FullName():
  243. case (*descriptorpb.EnumOptions)(nil).ProtoReflect().Descriptor().FullName():
  244. case (*descriptorpb.EnumValueOptions)(nil).ProtoReflect().Descriptor().FullName():
  245. case (*descriptorpb.MessageOptions)(nil).ProtoReflect().Descriptor().FullName():
  246. case (*descriptorpb.FieldOptions)(nil).ProtoReflect().Descriptor().FullName():
  247. case (*descriptorpb.OneofOptions)(nil).ProtoReflect().Descriptor().FullName():
  248. case (*descriptorpb.ExtensionRangeOptions)(nil).ProtoReflect().Descriptor().FullName():
  249. case (*descriptorpb.ServiceOptions)(nil).ProtoReflect().Descriptor().FullName():
  250. case (*descriptorpb.MethodOptions)(nil).ProtoReflect().Descriptor().FullName():
  251. default:
  252. return errors.New("extension field %q cannot be declared in proto3 unless extended descriptor options", x.FullName())
  253. }
  254. }
  255. }
  256. return nil
  257. }
  258. // isOptionalMessage reports whether this is an optional message.
  259. // If the kind is unknown, it is assumed to be a message.
  260. func isOptionalMessage(fd protoreflect.FieldDescriptor) bool {
  261. return (fd.Kind() == 0 || fd.Kind() == protoreflect.MessageKind) && fd.Cardinality() == protoreflect.Optional
  262. }
  263. // isPackable checks whether the pack option can be specified.
  264. func isPackable(fd protoreflect.FieldDescriptor) bool {
  265. switch fd.Kind() {
  266. case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind:
  267. return false
  268. }
  269. return fd.IsList()
  270. }
  271. // checkValidGroup reports whether fd is a valid group according to the same
  272. // rules that protoc imposes.
  273. func checkValidGroup(fd protoreflect.FieldDescriptor) error {
  274. md := fd.Message()
  275. switch {
  276. case fd.Kind() != protoreflect.GroupKind:
  277. return nil
  278. case fd.Syntax() != protoreflect.Proto2:
  279. return errors.New("invalid under proto2 semantics")
  280. case md == nil || md.IsPlaceholder():
  281. return errors.New("message must be resolvable")
  282. case fd.FullName().Parent() != md.FullName().Parent():
  283. return errors.New("message and field must be declared in the same scope")
  284. case !unicode.IsUpper(rune(md.Name()[0])):
  285. return errors.New("message name must start with an uppercase")
  286. case fd.Name() != protoreflect.Name(strings.ToLower(string(md.Name()))):
  287. return errors.New("field name must be lowercased form of the message name")
  288. }
  289. return nil
  290. }
  291. // checkValidMap checks whether the field is a valid map according to the same
  292. // rules that protoc imposes.
  293. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:6045-6115
  294. func checkValidMap(fd protoreflect.FieldDescriptor) error {
  295. md := fd.Message()
  296. switch {
  297. case md == nil || !md.IsMapEntry():
  298. return nil
  299. case fd.FullName().Parent() != md.FullName().Parent():
  300. return errors.New("message and field must be declared in the same scope")
  301. case md.Name() != protoreflect.Name(strs.MapEntryName(string(fd.Name()))):
  302. return errors.New("incorrect implicit map entry name")
  303. case fd.Cardinality() != protoreflect.Repeated:
  304. return errors.New("field must be repeated")
  305. case md.Fields().Len() != 2:
  306. return errors.New("message must have exactly two fields")
  307. case md.ExtensionRanges().Len() > 0:
  308. return errors.New("message must not have any extension ranges")
  309. case md.Enums().Len()+md.Messages().Len()+md.Extensions().Len() > 0:
  310. return errors.New("message must not have any nested declarations")
  311. }
  312. kf := md.Fields().Get(0)
  313. vf := md.Fields().Get(1)
  314. switch {
  315. case kf.Name() != "key" || kf.Number() != 1 || kf.Cardinality() != protoreflect.Optional || kf.ContainingOneof() != nil || kf.HasDefault():
  316. return errors.New("invalid key field")
  317. case vf.Name() != "value" || vf.Number() != 2 || vf.Cardinality() != protoreflect.Optional || vf.ContainingOneof() != nil || vf.HasDefault():
  318. return errors.New("invalid value field")
  319. }
  320. switch kf.Kind() {
  321. case protoreflect.BoolKind: // bool
  322. case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: // int32
  323. case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: // int64
  324. case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: // uint32
  325. case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: // uint64
  326. case protoreflect.StringKind: // string
  327. default:
  328. return errors.New("invalid key kind: %v", kf.Kind())
  329. }
  330. if e := vf.Enum(); e != nil && e.Values().Len() > 0 && e.Values().Get(0).Number() != 0 {
  331. return errors.New("map enum value must have zero number for the first value")
  332. }
  333. return nil
  334. }