validator.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validate
  15. import (
  16. "fmt"
  17. "reflect"
  18. "github.com/go-openapi/errors"
  19. "github.com/go-openapi/spec"
  20. "github.com/go-openapi/strfmt"
  21. )
  22. // An EntityValidator is an interface for things that can validate entities
  23. type EntityValidator interface {
  24. Validate(interface{}) *Result
  25. }
  26. type valueValidator interface {
  27. SetPath(path string)
  28. Applies(interface{}, reflect.Kind) bool
  29. Validate(interface{}) *Result
  30. }
  31. type itemsValidator struct {
  32. items *spec.Items
  33. root interface{}
  34. path string
  35. in string
  36. validators []valueValidator
  37. KnownFormats strfmt.Registry
  38. }
  39. func newItemsValidator(path, in string, items *spec.Items, root interface{}, formats strfmt.Registry) *itemsValidator {
  40. iv := &itemsValidator{path: path, in: in, items: items, root: root, KnownFormats: formats}
  41. iv.validators = []valueValidator{
  42. &typeValidator{
  43. Type: spec.StringOrArray([]string{items.Type}),
  44. Format: items.Format,
  45. In: in,
  46. Path: path,
  47. },
  48. iv.stringValidator(),
  49. iv.formatValidator(),
  50. iv.numberValidator(),
  51. iv.sliceValidator(),
  52. iv.commonValidator(),
  53. }
  54. return iv
  55. }
  56. func (i *itemsValidator) Validate(index int, data interface{}) *Result {
  57. tpe := reflect.TypeOf(data)
  58. kind := tpe.Kind()
  59. mainResult := new(Result)
  60. path := fmt.Sprintf("%s.%d", i.path, index)
  61. for _, validator := range i.validators {
  62. validator.SetPath(path)
  63. if validator.Applies(i.root, kind) {
  64. result := validator.Validate(data)
  65. mainResult.Merge(result)
  66. mainResult.Inc()
  67. if result != nil && result.HasErrors() {
  68. return mainResult
  69. }
  70. }
  71. }
  72. return mainResult
  73. }
  74. func (i *itemsValidator) commonValidator() valueValidator {
  75. return &basicCommonValidator{
  76. In: i.in,
  77. Default: i.items.Default,
  78. Enum: i.items.Enum,
  79. }
  80. }
  81. func (i *itemsValidator) sliceValidator() valueValidator {
  82. return &basicSliceValidator{
  83. In: i.in,
  84. Default: i.items.Default,
  85. MaxItems: i.items.MaxItems,
  86. MinItems: i.items.MinItems,
  87. UniqueItems: i.items.UniqueItems,
  88. Source: i.root,
  89. Items: i.items.Items,
  90. KnownFormats: i.KnownFormats,
  91. }
  92. }
  93. func (i *itemsValidator) numberValidator() valueValidator {
  94. return &numberValidator{
  95. In: i.in,
  96. Default: i.items.Default,
  97. MultipleOf: i.items.MultipleOf,
  98. Maximum: i.items.Maximum,
  99. ExclusiveMaximum: i.items.ExclusiveMaximum,
  100. Minimum: i.items.Minimum,
  101. ExclusiveMinimum: i.items.ExclusiveMinimum,
  102. Type: i.items.Type,
  103. Format: i.items.Format,
  104. }
  105. }
  106. func (i *itemsValidator) stringValidator() valueValidator {
  107. return &stringValidator{
  108. In: i.in,
  109. Default: i.items.Default,
  110. MaxLength: i.items.MaxLength,
  111. MinLength: i.items.MinLength,
  112. Pattern: i.items.Pattern,
  113. AllowEmptyValue: false,
  114. }
  115. }
  116. func (i *itemsValidator) formatValidator() valueValidator {
  117. return &formatValidator{
  118. In: i.in,
  119. //Default: i.items.Default,
  120. Format: i.items.Format,
  121. KnownFormats: i.KnownFormats,
  122. }
  123. }
  124. type basicCommonValidator struct {
  125. Path string
  126. In string
  127. Default interface{}
  128. Enum []interface{}
  129. }
  130. func (b *basicCommonValidator) SetPath(path string) {
  131. b.Path = path
  132. }
  133. func (b *basicCommonValidator) Applies(source interface{}, kind reflect.Kind) bool {
  134. switch source.(type) {
  135. case *spec.Parameter, *spec.Schema, *spec.Header:
  136. return true
  137. }
  138. return false
  139. }
  140. func (b *basicCommonValidator) Validate(data interface{}) (res *Result) {
  141. if len(b.Enum) > 0 {
  142. for _, enumValue := range b.Enum {
  143. actualType := reflect.TypeOf(enumValue)
  144. if actualType != nil { // Safeguard
  145. expectedValue := reflect.ValueOf(data)
  146. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  147. if reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), enumValue) {
  148. return nil
  149. }
  150. }
  151. }
  152. }
  153. return errorHelp.sErr(errors.EnumFail(b.Path, b.In, data, b.Enum))
  154. }
  155. return nil
  156. }
  157. // A HeaderValidator has very limited subset of validations to apply
  158. type HeaderValidator struct {
  159. name string
  160. header *spec.Header
  161. validators []valueValidator
  162. KnownFormats strfmt.Registry
  163. }
  164. // NewHeaderValidator creates a new header validator object
  165. func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry) *HeaderValidator {
  166. p := &HeaderValidator{name: name, header: header, KnownFormats: formats}
  167. p.validators = []valueValidator{
  168. &typeValidator{
  169. Type: spec.StringOrArray([]string{header.Type}),
  170. Format: header.Format,
  171. In: "header",
  172. Path: name,
  173. },
  174. p.stringValidator(),
  175. p.formatValidator(),
  176. p.numberValidator(),
  177. p.sliceValidator(),
  178. p.commonValidator(),
  179. }
  180. return p
  181. }
  182. // Validate the value of the header against its schema
  183. func (p *HeaderValidator) Validate(data interface{}) *Result {
  184. result := new(Result)
  185. tpe := reflect.TypeOf(data)
  186. kind := tpe.Kind()
  187. for _, validator := range p.validators {
  188. if validator.Applies(p.header, kind) {
  189. if err := validator.Validate(data); err != nil {
  190. result.Merge(err)
  191. if err.HasErrors() {
  192. return result
  193. }
  194. }
  195. }
  196. }
  197. return nil
  198. }
  199. func (p *HeaderValidator) commonValidator() valueValidator {
  200. return &basicCommonValidator{
  201. Path: p.name,
  202. In: "response",
  203. Default: p.header.Default,
  204. Enum: p.header.Enum,
  205. }
  206. }
  207. func (p *HeaderValidator) sliceValidator() valueValidator {
  208. return &basicSliceValidator{
  209. Path: p.name,
  210. In: "response",
  211. Default: p.header.Default,
  212. MaxItems: p.header.MaxItems,
  213. MinItems: p.header.MinItems,
  214. UniqueItems: p.header.UniqueItems,
  215. Items: p.header.Items,
  216. Source: p.header,
  217. KnownFormats: p.KnownFormats,
  218. }
  219. }
  220. func (p *HeaderValidator) numberValidator() valueValidator {
  221. return &numberValidator{
  222. Path: p.name,
  223. In: "response",
  224. Default: p.header.Default,
  225. MultipleOf: p.header.MultipleOf,
  226. Maximum: p.header.Maximum,
  227. ExclusiveMaximum: p.header.ExclusiveMaximum,
  228. Minimum: p.header.Minimum,
  229. ExclusiveMinimum: p.header.ExclusiveMinimum,
  230. Type: p.header.Type,
  231. Format: p.header.Format,
  232. }
  233. }
  234. func (p *HeaderValidator) stringValidator() valueValidator {
  235. return &stringValidator{
  236. Path: p.name,
  237. In: "response",
  238. Default: p.header.Default,
  239. Required: true,
  240. MaxLength: p.header.MaxLength,
  241. MinLength: p.header.MinLength,
  242. Pattern: p.header.Pattern,
  243. AllowEmptyValue: false,
  244. }
  245. }
  246. func (p *HeaderValidator) formatValidator() valueValidator {
  247. return &formatValidator{
  248. Path: p.name,
  249. In: "response",
  250. //Default: p.header.Default,
  251. Format: p.header.Format,
  252. KnownFormats: p.KnownFormats,
  253. }
  254. }
  255. // A ParamValidator has very limited subset of validations to apply
  256. type ParamValidator struct {
  257. param *spec.Parameter
  258. validators []valueValidator
  259. KnownFormats strfmt.Registry
  260. }
  261. // NewParamValidator creates a new param validator object
  262. func NewParamValidator(param *spec.Parameter, formats strfmt.Registry) *ParamValidator {
  263. p := &ParamValidator{param: param, KnownFormats: formats}
  264. p.validators = []valueValidator{
  265. &typeValidator{
  266. Type: spec.StringOrArray([]string{param.Type}),
  267. Format: param.Format,
  268. In: param.In,
  269. Path: param.Name,
  270. },
  271. p.stringValidator(),
  272. p.formatValidator(),
  273. p.numberValidator(),
  274. p.sliceValidator(),
  275. p.commonValidator(),
  276. }
  277. return p
  278. }
  279. // Validate the data against the description of the parameter
  280. func (p *ParamValidator) Validate(data interface{}) *Result {
  281. result := new(Result)
  282. tpe := reflect.TypeOf(data)
  283. kind := tpe.Kind()
  284. // TODO: validate type
  285. for _, validator := range p.validators {
  286. if validator.Applies(p.param, kind) {
  287. if err := validator.Validate(data); err != nil {
  288. result.Merge(err)
  289. if err.HasErrors() {
  290. return result
  291. }
  292. }
  293. }
  294. }
  295. return nil
  296. }
  297. func (p *ParamValidator) commonValidator() valueValidator {
  298. return &basicCommonValidator{
  299. Path: p.param.Name,
  300. In: p.param.In,
  301. Default: p.param.Default,
  302. Enum: p.param.Enum,
  303. }
  304. }
  305. func (p *ParamValidator) sliceValidator() valueValidator {
  306. return &basicSliceValidator{
  307. Path: p.param.Name,
  308. In: p.param.In,
  309. Default: p.param.Default,
  310. MaxItems: p.param.MaxItems,
  311. MinItems: p.param.MinItems,
  312. UniqueItems: p.param.UniqueItems,
  313. Items: p.param.Items,
  314. Source: p.param,
  315. KnownFormats: p.KnownFormats,
  316. }
  317. }
  318. func (p *ParamValidator) numberValidator() valueValidator {
  319. return &numberValidator{
  320. Path: p.param.Name,
  321. In: p.param.In,
  322. Default: p.param.Default,
  323. MultipleOf: p.param.MultipleOf,
  324. Maximum: p.param.Maximum,
  325. ExclusiveMaximum: p.param.ExclusiveMaximum,
  326. Minimum: p.param.Minimum,
  327. ExclusiveMinimum: p.param.ExclusiveMinimum,
  328. Type: p.param.Type,
  329. Format: p.param.Format,
  330. }
  331. }
  332. func (p *ParamValidator) stringValidator() valueValidator {
  333. return &stringValidator{
  334. Path: p.param.Name,
  335. In: p.param.In,
  336. Default: p.param.Default,
  337. AllowEmptyValue: p.param.AllowEmptyValue,
  338. Required: p.param.Required,
  339. MaxLength: p.param.MaxLength,
  340. MinLength: p.param.MinLength,
  341. Pattern: p.param.Pattern,
  342. }
  343. }
  344. func (p *ParamValidator) formatValidator() valueValidator {
  345. return &formatValidator{
  346. Path: p.param.Name,
  347. In: p.param.In,
  348. //Default: p.param.Default,
  349. Format: p.param.Format,
  350. KnownFormats: p.KnownFormats,
  351. }
  352. }
  353. type basicSliceValidator struct {
  354. Path string
  355. In string
  356. Default interface{}
  357. MaxItems *int64
  358. MinItems *int64
  359. UniqueItems bool
  360. Items *spec.Items
  361. Source interface{}
  362. itemsValidator *itemsValidator
  363. KnownFormats strfmt.Registry
  364. }
  365. func (s *basicSliceValidator) SetPath(path string) {
  366. s.Path = path
  367. }
  368. func (s *basicSliceValidator) Applies(source interface{}, kind reflect.Kind) bool {
  369. switch source.(type) {
  370. case *spec.Parameter, *spec.Items, *spec.Header:
  371. return kind == reflect.Slice
  372. }
  373. return false
  374. }
  375. func (s *basicSliceValidator) Validate(data interface{}) *Result {
  376. val := reflect.ValueOf(data)
  377. size := int64(val.Len())
  378. if s.MinItems != nil {
  379. if err := MinItems(s.Path, s.In, size, *s.MinItems); err != nil {
  380. return errorHelp.sErr(err)
  381. }
  382. }
  383. if s.MaxItems != nil {
  384. if err := MaxItems(s.Path, s.In, size, *s.MaxItems); err != nil {
  385. return errorHelp.sErr(err)
  386. }
  387. }
  388. if s.UniqueItems {
  389. if err := UniqueItems(s.Path, s.In, data); err != nil {
  390. return errorHelp.sErr(err)
  391. }
  392. }
  393. if s.itemsValidator == nil && s.Items != nil {
  394. s.itemsValidator = newItemsValidator(s.Path, s.In, s.Items, s.Source, s.KnownFormats)
  395. }
  396. if s.itemsValidator != nil {
  397. for i := 0; i < int(size); i++ {
  398. ele := val.Index(i)
  399. if err := s.itemsValidator.Validate(i, ele.Interface()); err != nil && err.HasErrors() {
  400. return err
  401. }
  402. }
  403. }
  404. return nil
  405. }
  406. func (s *basicSliceValidator) hasDuplicates(value reflect.Value, size int) bool {
  407. dict := make(map[interface{}]struct{})
  408. for i := 0; i < size; i++ {
  409. ele := value.Index(i)
  410. if _, ok := dict[ele.Interface()]; ok {
  411. return true
  412. }
  413. dict[ele.Interface()] = struct{}{}
  414. }
  415. return false
  416. }
  417. type numberValidator struct {
  418. Path string
  419. In string
  420. Default interface{}
  421. MultipleOf *float64
  422. Maximum *float64
  423. ExclusiveMaximum bool
  424. Minimum *float64
  425. ExclusiveMinimum bool
  426. // Allows for more accurate behavior regarding integers
  427. Type string
  428. Format string
  429. }
  430. func (n *numberValidator) SetPath(path string) {
  431. n.Path = path
  432. }
  433. func (n *numberValidator) Applies(source interface{}, kind reflect.Kind) bool {
  434. switch source.(type) {
  435. case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header:
  436. isInt := kind >= reflect.Int && kind <= reflect.Uint64
  437. isFloat := kind == reflect.Float32 || kind == reflect.Float64
  438. r := isInt || isFloat
  439. debugLog("schema props validator for %q applies %t for %T (kind: %v) isInt=%t, isFloat=%t\n", n.Path, r, source, kind, isInt, isFloat)
  440. return r
  441. }
  442. debugLog("schema props validator for %q applies %t for %T (kind: %v)\n", n.Path, false, source, kind)
  443. return false
  444. }
  445. // Validate provides a validator for generic JSON numbers,
  446. //
  447. // By default, numbers are internally represented as float64.
  448. // Formats float, or float32 may alter this behavior by mapping to float32.
  449. // A special validation process is followed for integers, with optional "format":
  450. // this is an attempt to provide a validation with native types.
  451. //
  452. // NOTE: since the constraint specified (boundary, multipleOf) is unmarshalled
  453. // as float64, loss of information remains possible (e.g. on very large integers).
  454. //
  455. // Since this value directly comes from the unmarshalling, it is not possible
  456. // at this stage of processing to check further and guarantee the correctness of such values.
  457. //
  458. // Normally, the JSON Number.MAX_SAFE_INTEGER (resp. Number.MIN_SAFE_INTEGER)
  459. // would check we do not get such a loss.
  460. //
  461. // If this is the case, replace AddErrors() by AddWarnings() and IsValid() by !HasWarnings().
  462. //
  463. // TODO: consider replacing boundary check errors by simple warnings.
  464. //
  465. // TODO: default boundaries with MAX_SAFE_INTEGER are not checked (specific to json.Number?)
  466. func (n *numberValidator) Validate(val interface{}) *Result {
  467. res := new(Result)
  468. resMultiple := new(Result)
  469. resMinimum := new(Result)
  470. resMaximum := new(Result)
  471. // Used only to attempt to validate constraint on value,
  472. // even though value or constraint specified do not match type and format
  473. data := valueHelp.asFloat64(val)
  474. // Is the provided value within the range of the specified numeric type and format?
  475. res.AddErrors(IsValueValidAgainstRange(val, n.Type, n.Format, "Checked", n.Path))
  476. if n.MultipleOf != nil {
  477. // Is the constraint specifier within the range of the specific numeric type and format?
  478. resMultiple.AddErrors(IsValueValidAgainstRange(*n.MultipleOf, n.Type, n.Format, "MultipleOf", n.Path))
  479. if resMultiple.IsValid() {
  480. // Constraint validated with compatible types
  481. if err := MultipleOfNativeType(n.Path, n.In, val, *n.MultipleOf); err != nil {
  482. resMultiple.Merge(errorHelp.sErr(err))
  483. }
  484. } else {
  485. // Constraint nevertheless validated, converted as general number
  486. if err := MultipleOf(n.Path, n.In, data, *n.MultipleOf); err != nil {
  487. resMultiple.Merge(errorHelp.sErr(err))
  488. }
  489. }
  490. }
  491. if n.Maximum != nil {
  492. // Is the constraint specifier within the range of the specific numeric type and format?
  493. resMaximum.AddErrors(IsValueValidAgainstRange(*n.Maximum, n.Type, n.Format, "Maximum boundary", n.Path))
  494. if resMaximum.IsValid() {
  495. // Constraint validated with compatible types
  496. if err := MaximumNativeType(n.Path, n.In, val, *n.Maximum, n.ExclusiveMaximum); err != nil {
  497. resMaximum.Merge(errorHelp.sErr(err))
  498. }
  499. } else {
  500. // Constraint nevertheless validated, converted as general number
  501. if err := Maximum(n.Path, n.In, data, *n.Maximum, n.ExclusiveMaximum); err != nil {
  502. resMaximum.Merge(errorHelp.sErr(err))
  503. }
  504. }
  505. }
  506. if n.Minimum != nil {
  507. // Is the constraint specifier within the range of the specific numeric type and format?
  508. resMinimum.AddErrors(IsValueValidAgainstRange(*n.Minimum, n.Type, n.Format, "Minimum boundary", n.Path))
  509. if resMinimum.IsValid() {
  510. // Constraint validated with compatible types
  511. if err := MinimumNativeType(n.Path, n.In, val, *n.Minimum, n.ExclusiveMinimum); err != nil {
  512. resMinimum.Merge(errorHelp.sErr(err))
  513. }
  514. } else {
  515. // Constraint nevertheless validated, converted as general number
  516. if err := Minimum(n.Path, n.In, data, *n.Minimum, n.ExclusiveMinimum); err != nil {
  517. resMinimum.Merge(errorHelp.sErr(err))
  518. }
  519. }
  520. }
  521. res.Merge(resMultiple, resMinimum, resMaximum)
  522. res.Inc()
  523. return res
  524. }
  525. type stringValidator struct {
  526. Default interface{}
  527. Required bool
  528. AllowEmptyValue bool
  529. MaxLength *int64
  530. MinLength *int64
  531. Pattern string
  532. Path string
  533. In string
  534. }
  535. func (s *stringValidator) SetPath(path string) {
  536. s.Path = path
  537. }
  538. func (s *stringValidator) Applies(source interface{}, kind reflect.Kind) bool {
  539. switch source.(type) {
  540. case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header:
  541. r := kind == reflect.String
  542. debugLog("string validator for %q applies %t for %T (kind: %v)\n", s.Path, r, source, kind)
  543. return r
  544. }
  545. debugLog("string validator for %q applies %t for %T (kind: %v)\n", s.Path, false, source, kind)
  546. return false
  547. }
  548. func (s *stringValidator) Validate(val interface{}) *Result {
  549. data, ok := val.(string)
  550. if !ok {
  551. return errorHelp.sErr(errors.InvalidType(s.Path, s.In, "string", val))
  552. }
  553. if s.Required && !s.AllowEmptyValue && (s.Default == nil || s.Default == "") {
  554. if err := RequiredString(s.Path, s.In, data); err != nil {
  555. return errorHelp.sErr(err)
  556. }
  557. }
  558. if s.MaxLength != nil {
  559. if err := MaxLength(s.Path, s.In, data, *s.MaxLength); err != nil {
  560. return errorHelp.sErr(err)
  561. }
  562. }
  563. if s.MinLength != nil {
  564. if err := MinLength(s.Path, s.In, data, *s.MinLength); err != nil {
  565. return errorHelp.sErr(err)
  566. }
  567. }
  568. if s.Pattern != "" {
  569. if err := Pattern(s.Path, s.In, data, s.Pattern); err != nil {
  570. return errorHelp.sErr(err)
  571. }
  572. }
  573. return nil
  574. }