Debian Codegraph @

requests/validate_body_test.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package requests
5
6 import (
7 "bytes"
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http"
12 "sync"
13 "testing"
14
15 "github.com/pb33f/libopenapi"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
18
19 "github.com/pb33f/libopenapi-validator/config"
20 "github.com/pb33f/libopenapi-validator/helpers"
21 "github.com/pb33f/libopenapi-validator/paths"
22 )
23
24 func TestValidateBody_NotRequiredBody(t *testing.T) {
25 spec := `openapi: 3.1.0
26 paths:
27 /burgers/createBurger:
28 post:
29 requestBody:
30 required: false
31 content:
32 application/json:
33 schema:
34 type: object
35 properties:
36 name:
37 type: string
38 patties:
39 type: integer
40 vegetarian:
41 type: boolean`
42
43 doc, _ := libopenapi.NewDocument([]byte(spec))
44
45 m, _ := doc.BuildV3Model()
46 v := NewRequestBodyValidator(&m.Model)
47
48 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", http.NoBody)
49
50 valid, errors := v.ValidateRequestBody(request)
51
52 assert.True(t, valid)
53 assert.Len(t, errors, 0)
54 }
55
56 func TestValidateBody_MediaRangeContentType_Wildcard_end(t *testing.T) {
57 spec := `openapi: 3.1.0
58 paths:
59 /burgers/createBurger:
60 post:
61 requestBody:
62 required: true
63 content:
64 thomas/*:
65 schema:
66 type: object
67 properties:
68 name:
69 type: string
70 patties:
71 type: integer
72 vegetarian:
73 type: boolean`
74
75 doc, _ := libopenapi.NewDocument([]byte(spec))
76
77 m, _ := doc.BuildV3Model()
78 v := NewRequestBodyValidator(&m.Model)
79
80 // mix up the primitives to fire two schema violations.
81 body := map[string]interface{}{
82 "name": "Big Mac",
83 "patties": false,
84 "vegetarian": 2,
85 }
86
87 bodyBytes, _ := json.Marshal(body)
88
89 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
90 bytes.NewBuffer(bodyBytes))
91 request.Header.Set("Content-Type", "thomas/tank-engine") // wtf kinda content type is this?
92
93 valid, errors := v.ValidateRequestBody(request)
94
95 assert.True(t, valid)
96 assert.Len(t, errors, 0)
97 }
98
99 func TestValidateBody_MediaRangeContentType_Wildcards(t *testing.T) {
100 spec := `openapi: 3.1.0
101 paths:
102 /burgers/createBurger:
103 post:
104 requestBody:
105 required: true
106 content:
107 "*/*":
108 schema:
109 type: object
110 properties:
111 name:
112 type: string
113 patties:
114 type: integer
115 vegetarian:
116 type: boolean`
117
118 doc, err := libopenapi.NewDocument([]byte(spec))
119 require.NoError(t, err)
120 m, _ := doc.BuildV3Model()
121 v := NewRequestBodyValidator(&m.Model)
122
123 // mix up the primitives to fire two schema violations.
124 body := map[string]interface{}{
125 "name": "Big Mac",
126 "patties": false,
127 "vegetarian": 2,
128 }
129
130 bodyBytes, _ := json.Marshal(body)
131
132 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
133 bytes.NewBuffer(bodyBytes))
134 request.Header.Set("Content-Type", "thomas/tank-engine") // wtf kinda content type is this?
135
136 valid, errors := v.ValidateRequestBody(request)
137
138 assert.True(t, valid)
139 assert.Len(t, errors, 0)
140 }
141
142 func TestValidateBody_InvalidBasicSchema_MediaRangeContentType_Wildcard_Required(t *testing.T) {
143 spec := `openapi: 3.1.0
144 paths:
145 /burgers/createBurger:
146 post:
147 requestBody:
148 required: false
149 content:
150 "*/json":
151 schema:
152 type: object
153 properties:
154 name:
155 type: string
156 patties:
157 type: integer
158 vegetarian:
159 type: boolean`
160
161 doc, _ := libopenapi.NewDocument([]byte(spec))
162
163 m, _ := doc.BuildV3Model()
164 v := NewRequestBodyValidator(&m.Model)
165
166 // mix up the primitives to fire two schema violations.
167 body := map[string]interface{}{
168 "name": "Big Mac",
169 "patties": false,
170 "vegetarian": 2,
171 }
172
173 bodyBytes, _ := json.Marshal(body)
174
175 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
176 bytes.NewBuffer(bodyBytes))
177 request.Header.Set("Content-Type", "foo/json")
178
179 valid, errors := v.ValidateRequestBody(request)
180
181 // double-tap to hit the cache
182 _, _ = v.ValidateRequestBody(request)
183
184 assert.False(t, valid)
185 assert.Len(t, errors, 1)
186 assert.Len(t, errors[0].SchemaValidationErrors, 2)
187 assert.Equal(t, "POST request body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
188 }
189
190 func TestValidateBody_UnknownContentType(t *testing.T) {
191 spec := `openapi: 3.1.0
192 paths:
193 /burgers/createBurger:
194 post:
195 requestBody:
196 required: true
197 content:
198 application/json:
199 schema:
200 type: object
201 properties:
202 name:
203 type: string
204 patties:
205 type: integer
206 vegetarian:
207 type: boolean`
208
209 doc, _ := libopenapi.NewDocument([]byte(spec))
210
211 m, _ := doc.BuildV3Model()
212 v := NewRequestBodyValidator(&m.Model)
213
214 // mix up the primitives to fire two schema violations.
215 body := map[string]interface{}{
216 "name": "Big Mac",
217 "patties": false,
218 "vegetarian": 2,
219 }
220
221 bodyBytes, _ := json.Marshal(body)
222
223 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
224 bytes.NewBuffer(bodyBytes))
225 request.Header.Set("Content-Type", "thomas/tank-engine") // wtf kinda content type is this?
226
227 valid, errors := v.ValidateRequestBody(request)
228
229 assert.False(t, valid)
230 assert.Len(t, errors, 1)
231 assert.Equal(t, "POST operation request content type 'thomas/tank-engine' does not exist", errors[0].Message)
232 assert.Equal(t, "The content type is invalid, Use one of the 1 "+
233 "supported types for this operation: application/json", errors[0].HowToFix)
234 assert.Equal(t, request.Method, errors[0].RequestMethod)
235 assert.Equal(t, request.URL.Path, errors[0].RequestPath)
236 assert.Equal(t, "/burgers/createBurger", errors[0].SpecPath)
237 }
238
239 func TestValidateBody_SkipValidationForNonJSON(t *testing.T) {
240 spec := `openapi: 3.1.0
241 paths:
242 /burgers/createBurger:
243 post:
244 requestBody:
245 content:
246 application/yaml:
247 schema:
248 type: object
249 properties:
250 name:
251 type: string
252 patties:
253 type: integer
254 vegetarian:
255 type: boolean`
256
257 doc, _ := libopenapi.NewDocument([]byte(spec))
258
259 m, _ := doc.BuildV3Model()
260 v := NewRequestBodyValidator(&m.Model)
261
262 body := map[string]interface{}{
263 "name": "Big Mac",
264 "patties": false,
265 "vegetarian": 2,
266 }
267
268 bodyBytes, _ := json.Marshal(body)
269
270 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
271 bytes.NewBuffer(bodyBytes))
272 request.Header.Set("Content-Type", "application/yaml")
273
274 valid, errors := v.ValidateRequestBody(request)
275
276 assert.True(t, valid)
277 assert.Len(t, errors, 0)
278 }
279
280 func TestValidateBody_PathNotFound(t *testing.T) {
281 spec := `openapi: 3.1.0
282 paths:
283 /burgers/createBurger:
284 post:
285 requestBody:
286 content:
287 application/json:
288 schema:
289 type: object
290 properties:
291 name:
292 type: string
293 patties:
294 type: integer
295 vegetarian:
296 type: boolean`
297
298 doc, _ := libopenapi.NewDocument([]byte(spec))
299
300 m, _ := doc.BuildV3Model()
301 v := NewRequestBodyValidator(&m.Model)
302
303 // mix up the primitives to fire two schema violations.
304 body := map[string]interface{}{
305 "name": "Big Mac",
306 "patties": false,
307 "vegetarian": 2,
308 }
309
310 bodyBytes, _ := json.Marshal(body)
311
312 request, _ := http.NewRequest(http.MethodPost, "https://things.com/I do not exist",
313 bytes.NewBuffer(bodyBytes))
314 request.Header.Set("Content-Type", "application/json")
315
316 valid, errors := v.ValidateRequestBody(request)
317
318 assert.False(t, valid)
319 assert.Len(t, errors, 1)
320 assert.Equal(t, "POST Path '/I do not exist' not found", errors[0].Message)
321 assert.Equal(t, request.Method, errors[0].RequestMethod)
322 assert.Equal(t, request.URL.Path, errors[0].RequestPath)
323 assert.Equal(t, "", errors[0].SpecPath)
324 }
325
326 func TestValidateBody_OperationNotFound(t *testing.T) {
327 spec := `openapi: 3.1.0
328 paths:
329 /burgers/createBurger:
330 post:
331 requestBody:
332 content:
333 application/json:
334 schema:
335 type: object
336 properties:
337 name:
338 type: string
339 patties:
340 type: integer
341 vegetarian:
342 type: boolean`
343
344 doc, _ := libopenapi.NewDocument([]byte(spec))
345
346 m, _ := doc.BuildV3Model()
347 v := NewRequestBodyValidator(&m.Model)
348
349 // mix up the primitives to fire two schema violations.
350 body := map[string]interface{}{
351 "name": "Big Mac",
352 "patties": 2,
353 "vegetarian": true,
354 }
355
356 bodyBytes, _ := json.Marshal(body)
357
358 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
359 bytes.NewBuffer(bodyBytes))
360 request.Header.Set("Content-Type", "application/json")
361
362 pathItem, validationErrors, pathValue := paths.FindPath(request, &m.Model, nil)
363 assert.Len(t, validationErrors, 0)
364
365 request2, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers/createBurger",
366 bytes.NewBuffer(bodyBytes))
367 request2.Header.Set("Content-Type", "application/json")
368 valid, errors := v.ValidateRequestBodyWithPathItem(request2, pathItem, pathValue)
369
370 assert.False(t, valid)
371 assert.Len(t, errors, 1)
372 assert.Equal(t, "GET operation request content type 'GET' does not exist", errors[0].Message)
373 assert.Equal(t, request2.Method, errors[0].RequestMethod)
374 assert.Equal(t, request.URL.Path, errors[0].RequestPath)
375 assert.Equal(t, "/burgers/createBurger", errors[0].SpecPath)
376 }
377
378 func TestValidateBody_SetPath(t *testing.T) {
379 spec := `openapi: 3.1.0
380 paths:
381 /burgers/createBurger:
382 post:
383 requestBody:
384 content:
385 application/json:
386 schema:
387 type: object
388 properties:
389 name:
390 type: string
391 patties:
392 type: integer
393 vegetarian:
394 type: boolean`
395
396 doc, _ := libopenapi.NewDocument([]byte(spec))
397
398 m, _ := doc.BuildV3Model()
399 v := NewRequestBodyValidator(&m.Model)
400
401 // mix up the primitives to fire two schema violations.
402 body := map[string]interface{}{
403 "name": "Big Mac",
404 "patties": 2,
405 "vegetarian": true,
406 }
407
408 bodyBytes, _ := json.Marshal(body)
409
410 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
411 bytes.NewBuffer(bodyBytes))
412 request.Header.Set("Content-Type", "application/json")
413
414 valid, errors := v.ValidateRequestBodyWithPathItem(request, nil, "")
415
416 assert.False(t, valid)
417 assert.Len(t, errors, 1)
418 assert.Equal(t, "POST Path '/burgers/createBurger' not found", errors[0].Message)
419 }
420
421 func TestValidateBody_ContentTypeNotFound(t *testing.T) {
422 spec := `openapi: 3.1.0
423 paths:
424 /burgers/createBurger:
425 post:
426 requestBody:
427 required: true
428 content:
429 application/json:
430 schema:
431 type: object
432 properties:
433 name:
434 type: string
435 patties:
436 type: integer
437 vegetarian:
438 type: boolean`
439
440 doc, _ := libopenapi.NewDocument([]byte(spec))
441
442 m, _ := doc.BuildV3Model()
443 v := NewRequestBodyValidator(&m.Model)
444
445 // mix up the primitives to fire two schema violations.
446 body := map[string]interface{}{
447 "name": "Big Mac",
448 "patties": 2,
449 "vegetarian": true,
450 }
451
452 bodyBytes, _ := json.Marshal(body)
453
454 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
455 bytes.NewBuffer(bodyBytes))
456 request.Header.Set("content-type", "application/not-json")
457
458 pathItem, validationErrors, pathValue := paths.FindPath(request, &m.Model, nil)
459 assert.Len(t, validationErrors, 0)
460 valid, errors := v.ValidateRequestBodyWithPathItem(request, pathItem, pathValue)
461
462 assert.False(t, valid)
463 assert.Len(t, errors, 1)
464 }
465
466 func TestValidateBody_ContentTypeNotSet(t *testing.T) {
467 spec := `openapi: 3.1.0
468 paths:
469 /burgers/createBurger:
470 post:
471 requestBody:
472 required: true
473 content:
474 application/json:
475 schema:
476 type: object
477 properties:
478 name:
479 type: string
480 patties:
481 type: integer
482 vegetarian:
483 type: boolean`
484
485 doc, _ := libopenapi.NewDocument([]byte(spec))
486
487 m, _ := doc.BuildV3Model()
488 v := NewRequestBodyValidator(&m.Model)
489
490 body := map[string]interface{}{
491 "name": "Big Mac",
492 "patties": 2,
493 "vegetarian": true,
494 }
495
496 bodyBytes, _ := json.Marshal(body)
497
498 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
499 bytes.NewBuffer(bodyBytes))
500
501 pathItem, validationErrors, pathValue := paths.FindPath(request, &m.Model, &config.ValidationOptions{RegexCache: &sync.Map{}})
502 assert.Len(t, validationErrors, 0)
503 valid, errors := v.ValidateRequestBodyWithPathItem(request, pathItem, pathValue)
504
505 assert.False(t, valid)
506 assert.Len(t, errors, 1)
507 }
508
509 func TestValidateBody_InvalidBasicSchema_NotRequired(t *testing.T) {
510 spec := `openapi: 3.1.0
511 paths:
512 /burgers/createBurger:
513 post:
514 requestBody:
515 required: false
516 content:
517 application/json:
518 schema:
519 type: object
520 properties:
521 name:
522 type: string
523 patties:
524 type: integer
525 vegetarian:
526 type: boolean`
527
528 doc, _ := libopenapi.NewDocument([]byte(spec))
529
530 m, _ := doc.BuildV3Model()
531 v := NewRequestBodyValidator(&m.Model)
532
533 // mix up the primitives to fire two schema violations.
534 body := map[string]interface{}{
535 "name": "Big Mac",
536 "patties": false,
537 "vegetarian": 2,
538 }
539
540 bodyBytes, _ := json.Marshal(body)
541
542 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
543 bytes.NewBuffer(bodyBytes))
544 request.Header.Set("Content-Type", "application/json")
545
546 valid, errors := v.ValidateRequestBody(request)
547
548 // double-tap to hit the cache
549 _, _ = v.ValidateRequestBody(request)
550
551 assert.False(t, valid)
552 assert.Len(t, errors, 1)
553 assert.Len(t, errors[0].SchemaValidationErrors, 2)
554 assert.Equal(t, "POST request body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
555 }
556
557 func TestValidateBody_InvalidBasicSchema_Required(t *testing.T) {
558 spec := `openapi: 3.1.0
559 paths:
560 /burgers/createBurger:
561 post:
562 requestBody:
563 required: false
564 content:
565 application/json:
566 schema:
567 type: object
568 properties:
569 name:
570 type: string
571 patties:
572 type: integer
573 vegetarian:
574 type: boolean`
575
576 doc, _ := libopenapi.NewDocument([]byte(spec))
577
578 m, _ := doc.BuildV3Model()
579 v := NewRequestBodyValidator(&m.Model)
580
581 // mix up the primitives to fire two schema violations.
582 body := map[string]interface{}{
583 "name": "Big Mac",
584 "patties": false,
585 "vegetarian": 2,
586 }
587
588 bodyBytes, _ := json.Marshal(body)
589
590 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
591 bytes.NewBuffer(bodyBytes))
592 request.Header.Set("Content-Type", "application/json")
593
594 valid, errors := v.ValidateRequestBody(request)
595
596 // double-tap to hit the cache
597 _, _ = v.ValidateRequestBody(request)
598
599 assert.False(t, valid)
600 assert.Len(t, errors, 1)
601 assert.Len(t, errors[0].SchemaValidationErrors, 2)
602 assert.Equal(t, "POST request body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
603 }
604
605 func TestValidateBody_ValidBasicSchema(t *testing.T) {
606 spec := `openapi: 3.1.0
607 paths:
608 /burgers/createBurger:
609 post:
610 requestBody:
611 content:
612 application/json:
613 schema:
614 type: object
615 properties:
616 name:
617 type: string
618 patties:
619 type: integer
620 vegetarian:
621 type: boolean`
622
623 doc, _ := libopenapi.NewDocument([]byte(spec))
624
625 m, _ := doc.BuildV3Model()
626 v := NewRequestBodyValidator(&m.Model)
627
628 body := map[string]interface{}{
629 "name": "Big Mac",
630 "patties": 2,
631 "vegetarian": true,
632 }
633
634 bodyBytes, _ := json.Marshal(body)
635
636 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
637 bytes.NewBuffer(bodyBytes))
638 request.Header.Set("Content-Type", "application/json")
639
640 valid, errors := v.ValidateRequestBody(request)
641
642 assert.True(t, valid)
643 assert.Len(t, errors, 0)
644 }
645
646 func TestValidateBody_UsesGetBodyWhenBodyAlreadyConsumed(t *testing.T) {
647 spec := `openapi: 3.1.0
648 paths:
649 /burgers/createBurger:
650 post:
651 requestBody:
652 required: true
653 content:
654 application/json:
655 schema:
656 type: object
657 required: [name, patties, vegetarian]
658 properties:
659 name:
660 type: string
661 patties:
662 type: integer
663 vegetarian:
664 type: boolean`
665
666 doc, _ := libopenapi.NewDocument([]byte(spec))
667
668 m, _ := doc.BuildV3Model()
669 v := NewRequestBodyValidator(&m.Model)
670
671 body := map[string]interface{}{
672 "name": "Big Mac",
673 "patties": 2,
674 "vegetarian": true,
675 }
676 bodyBytes, _ := json.Marshal(body)
677
678 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
679 bytes.NewReader(bodyBytes))
680 request.Header.Set("Content-Type", "application/json")
681 _, _ = io.ReadAll(request.Body)
682
683 valid, validationErrors := v.ValidateRequestBody(request)
684 require.True(t, valid)
685 require.Empty(t, validationErrors)
686
687 restoredBody, err := io.ReadAll(request.Body)
688 require.NoError(t, err)
689 require.JSONEq(t, string(bodyBytes), string(restoredBody))
690
691 replayedBody, err := request.GetBody()
692 require.NoError(t, err)
693 replayedBytes, err := io.ReadAll(replayedBody)
694 require.NoError(t, err)
695 require.NoError(t, replayedBody.Close())
696 require.JSONEq(t, string(bodyBytes), string(replayedBytes))
697 }
698
699 func TestValidateBody_PrefersAssignedBodyOverStaleGetBody(t *testing.T) {
700 spec := `openapi: 3.1.0
701 paths:
702 /burgers/createBurger:
703 post:
704 requestBody:
705 required: true
706 content:
707 application/json:
708 schema:
709 type: object
710 required: [name, patties, vegetarian]
711 properties:
712 name:
713 type: string
714 patties:
715 type: integer
716 vegetarian:
717 type: boolean`
718
719 doc, _ := libopenapi.NewDocument([]byte(spec))
720
721 m, _ := doc.BuildV3Model()
722 v := NewRequestBodyValidator(&m.Model)
723
724 staleBodyBytes, _ := json.Marshal(map[string]interface{}{
725 "name": "Big Mac",
726 "patties": false,
727 "vegetarian": true,
728 })
729 currentBodyBytes, _ := json.Marshal(map[string]interface{}{
730 "name": "Big Mac",
731 "patties": 2,
732 "vegetarian": true,
733 })
734
735 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
736 bytes.NewReader(staleBodyBytes))
737 request.Header.Set("Content-Type", "application/json")
738 request.Body = io.NopCloser(bytes.NewReader(currentBodyBytes))
739
740 valid, validationErrors := v.ValidateRequestBody(request)
741 require.True(t, valid)
742 require.Empty(t, validationErrors)
743 }
744
745 func TestValidateBody_DoesNotUseStaleGetBodyForConsumedDifferentBodySameLength(t *testing.T) {
746 spec := `openapi: 3.1.0
747 paths:
748 /burgers/createBurger:
749 post:
750 requestBody:
751 required: true
752 content:
753 application/json:
754 schema:
755 type: object
756 required: [patties]
757 properties:
758 patties:
759 type: integer`
760
761 doc, _ := libopenapi.NewDocument([]byte(spec))
762
763 m, _ := doc.BuildV3Model()
764 v := NewRequestBodyValidator(&m.Model)
765
766 staleBodyBytes := []byte(`{"patties":12345}`)
767 currentBodyBytes := []byte(`{"patties":false}`)
768 require.Len(t, currentBodyBytes, len(staleBodyBytes))
769
770 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
771 bytes.NewReader(staleBodyBytes))
772 request.Header.Set("Content-Type", "application/json")
773 request.Body = io.NopCloser(bytes.NewReader(currentBodyBytes))
774 _, _ = io.ReadAll(request.Body)
775
776 valid, validationErrors := v.ValidateRequestBody(request)
777 require.False(t, valid)
778 require.Len(t, validationErrors, 1)
779 require.Equal(t, "POST request body is empty for '/burgers/createBurger'", validationErrors[0].Message)
780
781 replayedBody, err := request.GetBody()
782 require.NoError(t, err)
783 replayedBytes, err := io.ReadAll(replayedBody)
784 require.NoError(t, err)
785 require.NoError(t, replayedBody.Close())
786 require.Empty(t, replayedBytes)
787 }
788
789 func TestValidateBody_DoesNotUseStaleGetBodyForExplicitEmptyBody(t *testing.T) {
790 spec := `openapi: 3.1.0
791 paths:
792 /burgers/createBurger:
793 post:
794 requestBody:
795 required: true
796 content:
797 application/json:
798 schema:
799 type: object
800 required: [name, patties, vegetarian]
801 properties:
802 name:
803 type: string
804 patties:
805 type: integer
806 vegetarian:
807 type: boolean`
808
809 doc, _ := libopenapi.NewDocument([]byte(spec))
810
811 m, _ := doc.BuildV3Model()
812 v := NewRequestBodyValidator(&m.Model)
813
814 staleBodyBytes, _ := json.Marshal(map[string]interface{}{
815 "name": "Big Mac",
816 "patties": 2,
817 "vegetarian": true,
818 })
819
820 tests := []struct {
821 name string
822 body io.ReadCloser
823 }{
824 {
825 name: "http no body",
826 body: http.NoBody,
827 },
828 {
829 name: "empty reader",
830 body: io.NopCloser(bytes.NewReader(nil)),
831 },
832 }
833
834 for _, tc := range tests {
835 t.Run(tc.name, func(t *testing.T) {
836 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
837 bytes.NewReader(staleBodyBytes))
838 request.Header.Set("Content-Type", "application/json")
839 request.Body = tc.body
840
841 valid, validationErrors := v.ValidateRequestBody(request)
842 require.False(t, valid)
843 require.Len(t, validationErrors, 1)
844 require.Equal(t, "POST request body is empty for '/burgers/createBurger'", validationErrors[0].Message)
845
846 replayedBody, err := request.GetBody()
847 require.NoError(t, err)
848 replayedBytes, err := io.ReadAll(replayedBody)
849 require.NoError(t, err)
850 require.NoError(t, replayedBody.Close())
851 require.Empty(t, replayedBytes)
852 })
853 }
854 }
855
856 func TestRequestBodyHelpers_NilRequest(t *testing.T) {
857 setRequestBody(nil, []byte(`{"ok":true}`))
858 require.Nil(t, readAndResetRequestBody(nil))
859 }
860
861 type requestBodyReaderTestBody struct{}
862
863 func (r *requestBodyReaderTestBody) Read(_ []byte) (int, error) {
864 return 0, io.EOF
865 }
866
867 func (r *requestBodyReaderTestBody) Close() error {
868 return nil
869 }
870
871 type failingReplayableBody struct{}
872
873 func (r *failingReplayableBody) Read(_ []byte) (int, error) {
874 return 0, io.EOF
875 }
876
877 func (r *failingReplayableBody) Close() error {
878 return nil
879 }
880
881 func (r *failingReplayableBody) ReadAt(_ []byte, _ int64) (int, error) {
882 return 0, io.ErrUnexpectedEOF
883 }
884
885 func (r *failingReplayableBody) Size() int64 {
886 return 1
887 }
888
889 func TestRequestBodyReader_DefensiveBranches(t *testing.T) {
890 require.Nil(t, requestBodyReader(nil))
891 require.Nil(t, requestBodyReader(http.NoBody))
892
893 var nilBody *requestBodyReaderTestBody
894 require.Nil(t, requestBodyReader(nilBody))
895
896 body := &requestBodyReaderTestBody{}
897 require.Same(t, body, requestBodyReader(body))
898 }
899
900 func TestRequestBodySnapshot_DefensiveBranches(t *testing.T) {
901 snapshot, ok := requestBodySnapshot(nil)
902 require.False(t, ok)
903 require.Nil(t, snapshot)
904
905 snapshot, ok = requestBodySnapshot(&http.Request{Body: &requestBodyReaderTestBody{}})
906 require.False(t, ok)
907 require.Nil(t, snapshot)
908
909 snapshot, ok = requestBodySnapshot(&http.Request{Body: io.NopCloser(bytes.NewReader(nil))})
910 require.False(t, ok)
911 require.Nil(t, snapshot)
912
913 snapshot, ok = requestBodySnapshot(&http.Request{Body: &failingReplayableBody{}})
914 require.False(t, ok)
915 require.Nil(t, snapshot)
916 }
917
918 func TestValidateBody_ValidBasicSchema_WithFullContentTypeHeader(t *testing.T) {
919 spec := `openapi: 3.1.0
920 paths:
921 /burgers/createBurger:
922 post:
923 requestBody:
924 content:
925 application/json:
926 schema:
927 type: object
928 properties:
929 name:
930 type: string
931 patties:
932 type: integer
933 vegetarian:
934 type: boolean`
935
936 doc, _ := libopenapi.NewDocument([]byte(spec))
937
938 m, _ := doc.BuildV3Model()
939 v := NewRequestBodyValidator(&m.Model)
940
941 body := map[string]interface{}{
942 "name": "Big Mac",
943 "patties": 2,
944 "vegetarian": true,
945 }
946
947 bodyBytes, _ := json.Marshal(body)
948
949 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
950 bytes.NewBuffer(bodyBytes))
951 request.Header.Set("Content-Type", "application/json; charset=utf-8; boundary=12345")
952
953 valid, errors := v.ValidateRequestBody(request)
954
955 assert.True(t, valid)
956 assert.Len(t, errors, 0)
957 }
958
959 func TestValidateBody_ValidSchemaUsingAllOf(t *testing.T) {
960 spec := `openapi: 3.1.0
961 paths:
962 /burgers/createBurger:
963 post:
964 requestBody:
965 content:
966 application/json:
967 schema:
968 $ref: '#/components/schema_validation/TestBody'
969 components:
970 schema_validation:
971 Nutrients:
972 type: object
973 required: [fat, salt, meat]
974 properties:
975 fat:
976 type: number
977 salt:
978 type: number
979 meat:
980 type: string
981 enum:
982 - beef
983 - pork
984 - lamb
985 - vegetables
986 TestBody:
987 type: object
988 allOf:
989 - $ref: '#/components/schema_validation/Nutrients'
990 properties:
991 name:
992 type: string
993 patties:
994 type: integer
995 vegetarian:
996 type: boolean
997 required: [name, patties, vegetarian] `
998
999 doc, _ := libopenapi.NewDocument([]byte(spec))
1000
1001 m, _ := doc.BuildV3Model()
1002 v := NewRequestBodyValidator(&m.Model)
1003
1004 body := map[string]interface{}{
1005 "name": "Big Mac",
1006 "patties": 2,
1007 "vegetarian": true,
1008 "fat": 10.0,
1009 "salt": 0.5,
1010 "meat": "beef",
1011 }
1012
1013 bodyBytes, _ := json.Marshal(body)
1014
1015 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1016 bytes.NewBuffer(bodyBytes))
1017 request.Header.Set("Content-Type", "application/json")
1018
1019 valid, errors := v.ValidateRequestBody(request)
1020
1021 assert.True(t, valid)
1022 assert.Len(t, errors, 0)
1023 }
1024
1025 func TestValidateBody_InvalidSchemaUsingAllOf(t *testing.T) {
1026 spec := `openapi: 3.1.0
1027 paths:
1028 /burgers/createBurger:
1029 post:
1030 requestBody:
1031 content:
1032 application/json:
1033 schema:
1034 $ref: '#/components/schema_validation/TestBody'
1035 components:
1036 schema_validation:
1037 Nutrients:
1038 type: object
1039 required: [fat, salt, meat]
1040 properties:
1041 fat:
1042 type: number
1043 salt:
1044 type: number
1045 meat:
1046 type: string
1047 enum:
1048 - beef
1049 - pork
1050 - lamb
1051 - vegetables
1052 TestBody:
1053 type: object
1054 allOf:
1055 - $ref: '#/components/schema_validation/Nutrients'
1056 properties:
1057 name:
1058 type: string
1059 patties:
1060 type: integer
1061 vegetarian:
1062 type: boolean
1063 required: [name, patties, vegetarian] `
1064
1065 doc, _ := libopenapi.NewDocument([]byte(spec))
1066
1067 m, _ := doc.BuildV3Model()
1068 v := NewRequestBodyValidator(&m.Model)
1069
1070 body := map[string]interface{}{
1071 "name": "Big Mac",
1072 "patties": 2,
1073 "vegetarian": true,
1074 "fat": 10.0,
1075 "salt": false, // invalid
1076 "meat": "turkey", // invalid
1077 }
1078
1079 bodyBytes, _ := json.Marshal(body)
1080
1081 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1082 bytes.NewBuffer(bodyBytes))
1083 request.Header.Set("Content-Type", "application/json")
1084
1085 valid, errors := v.ValidateRequestBody(request)
1086
1087 assert.False(t, valid)
1088 assert.Len(t, errors, 1)
1089 assert.Len(t, errors[0].SchemaValidationErrors, 2)
1090 }
1091
1092 func TestValidateBody_ValidSchemaUsingAllOfAnyOf(t *testing.T) {
1093 spec := `openapi: 3.1.0
1094 paths:
1095 /burgers/createBurger:
1096 post:
1097 requestBody:
1098 content:
1099 application/json:
1100 schema:
1101 $ref: '#/components/schema_validation/TestBody'
1102 components:
1103 schema_validation:
1104 Uncooked:
1105 type: object
1106 required: [uncookedWeight, uncookedHeight]
1107 properties:
1108 uncookedWeight:
1109 type: number
1110 uncookedHeight:
1111 type: number
1112 Cooked:
1113 type: object
1114 required: [usedOil, usedAnimalFat]
1115 properties:
1116 usedOil:
1117 type: boolean
1118 usedAnimalFat:
1119 type: boolean
1120 Nutrients:
1121 type: object
1122 required: [fat, salt, meat]
1123 properties:
1124 fat:
1125 type: number
1126 salt:
1127 type: number
1128 meat:
1129 type: string
1130 enum:
1131 - beef
1132 - pork
1133 - lamb
1134 - vegetables
1135 TestBody:
1136 type: object
1137 oneOf:
1138 - $ref: '#/components/schema_validation/Uncooked'
1139 - $ref: '#/components/schema_validation/Cooked'
1140 allOf:
1141 - $ref: '#/components/schema_validation/Nutrients'
1142 properties:
1143 name:
1144 type: string
1145 patties:
1146 type: integer
1147 vegetarian:
1148 type: boolean
1149 required: [name, patties, vegetarian] `
1150
1151 doc, _ := libopenapi.NewDocument([]byte(spec))
1152
1153 m, _ := doc.BuildV3Model()
1154 v := NewRequestBodyValidator(&m.Model)
1155
1156 body := map[string]interface{}{
1157 "name": "Big Mac",
1158 "patties": 2,
1159 "vegetarian": true,
1160 "fat": 10.0,
1161 "salt": 0.5,
1162 "meat": "beef",
1163 "usedOil": true,
1164 "usedAnimalFat": false,
1165 }
1166
1167 bodyBytes, _ := json.Marshal(body)
1168
1169 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1170 bytes.NewBuffer(bodyBytes))
1171 request.Header.Set("Content-Type", "application/json")
1172
1173 valid, errors := v.ValidateRequestBody(request)
1174
1175 assert.True(t, valid)
1176 assert.Len(t, errors, 0)
1177 }
1178
1179 func TestValidateBody_InvalidSchemaUsingOneOf(t *testing.T) {
1180 spec := `openapi: 3.1.0
1181 paths:
1182 /burgers/createBurger:
1183 post:
1184 requestBody:
1185 content:
1186 application/json:
1187 schema:
1188 $ref: '#/components/schema_validation/TestBody'
1189 components:
1190 schema_validation:
1191 Uncooked:
1192 type: object
1193 required: [uncookedWeight, uncookedHeight]
1194 properties:
1195 uncookedWeight:
1196 type: number
1197 uncookedHeight:
1198 type: number
1199 Cooked:
1200 type: object
1201 required: [usedOil, usedAnimalFat]
1202 properties:
1203 usedOil:
1204 type: boolean
1205 usedAnimalFat:
1206 type: boolean
1207 Nutrients:
1208 type: object
1209 required: [fat, salt, meat]
1210 properties:
1211 fat:
1212 type: number
1213 salt:
1214 type: number
1215 meat:
1216 type: string
1217 enum:
1218 - beef
1219 - pork
1220 - lamb
1221 - vegetables
1222 TestBody:
1223 type: object
1224 oneOf:
1225 - $ref: '#/components/schema_validation/Uncooked'
1226 - $ref: '#/components/schema_validation/Cooked'
1227 allOf:
1228 - $ref: '#/components/schema_validation/Nutrients'
1229 properties:
1230 name:
1231 type: string
1232 patties:
1233 type: integer
1234 vegetarian:
1235 type: boolean
1236 required: [name, patties, vegetarian] `
1237
1238 doc, _ := libopenapi.NewDocument([]byte(spec))
1239
1240 m, _ := doc.BuildV3Model()
1241 v := NewRequestBodyValidator(&m.Model)
1242
1243 body := map[string]interface{}{
1244 "name": "Big Mac",
1245 "patties": 2,
1246 "vegetarian": true,
1247 "fat": 10.0,
1248 "salt": 0.5,
1249 "meat": "beef",
1250 }
1251
1252 bodyBytes, _ := json.Marshal(body)
1253
1254 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1255 bytes.NewBuffer(bodyBytes))
1256 request.Header.Set("Content-Type", "application/json")
1257
1258 valid, errors := v.ValidateRequestBody(request)
1259
1260 assert.False(t, valid)
1261 assert.Len(t, errors, 1)
1262 assert.Len(t, errors[0].SchemaValidationErrors, 2)
1263 assert.Equal(t, "missing properties 'uncookedWeight', 'uncookedHeight'", errors[0].SchemaValidationErrors[0].Reason)
1264 assert.Equal(t, "missing properties 'usedOil', 'usedAnimalFat'", errors[0].SchemaValidationErrors[1].Reason)
1265 }
1266
1267 func TestValidateBody_InvalidSchemaMinMax(t *testing.T) {
1268 spec := `openapi: 3.1.0
1269 paths:
1270 /burgers/createBurger:
1271 post:
1272 requestBody:
1273 content:
1274 application/json:
1275 schema:
1276 $ref: '#/components/schema_validation/TestBody'
1277 components:
1278 schema_validation:
1279 TestBody:
1280 type: object
1281 properties:
1282 name:
1283 type: string
1284 patties:
1285 type: integer
1286 maximum: 3
1287 minimum: 1
1288 vegetarian:
1289 type: boolean
1290 required: [name, patties, vegetarian] `
1291
1292 doc, _ := libopenapi.NewDocument([]byte(spec))
1293
1294 m, _ := doc.BuildV3Model()
1295 v := NewRequestBodyValidator(&m.Model)
1296
1297 body := map[string]interface{}{
1298 "name": "Big Mac",
1299 "patties": 5,
1300 "vegetarian": true,
1301 "fat": 10.0,
1302 "salt": 0.5,
1303 "meat": "beef",
1304 }
1305
1306 bodyBytes, _ := json.Marshal(body)
1307
1308 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1309 bytes.NewBuffer(bodyBytes))
1310 request.Header.Set("Content-Type", "application/json")
1311
1312 valid, errors := v.ValidateRequestBody(request)
1313
1314 assert.False(t, valid)
1315 assert.Len(t, errors, 1)
1316 assert.Len(t, errors[0].SchemaValidationErrors, 1)
1317 assert.Equal(t, "maximum: got 5, want 3", errors[0].SchemaValidationErrors[0].Reason)
1318 }
1319
1320 func TestValidateBody_InvalidSchemaMaxItems(t *testing.T) {
1321 spec := `openapi: 3.1.0
1322 paths:
1323 /burgers/createBurger:
1324 post:
1325 requestBody:
1326 content:
1327 application/json:
1328 schema:
1329 $ref: '#/components/schema_validation/TestBody'
1330 components:
1331 schema_validation:
1332 TestBody:
1333 type: array
1334 maxItems: 2
1335 items:
1336 type: object
1337 properties:
1338 name:
1339 type: string
1340 patties:
1341 type: integer
1342 maximum: 3
1343 minimum: 1
1344 vegetarian:
1345 type: boolean
1346 required: [name, patties, vegetarian] `
1347
1348 doc, _ := libopenapi.NewDocument([]byte(spec))
1349
1350 m, _ := doc.BuildV3Model()
1351 v := NewRequestBodyValidator(&m.Model)
1352
1353 body := map[string]interface{}{
1354 "name": "Big Mac",
1355 "patties": 2,
1356 "vegetarian": true,
1357 "fat": 10.0,
1358 "salt": 0.5,
1359 "meat": "beef",
1360 }
1361 bodyArray := []interface{}{body, body, body, body} // two too many!
1362 bodyBytes, _ := json.Marshal(bodyArray)
1363
1364 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1365 bytes.NewBuffer(bodyBytes))
1366 request.Header.Set("Content-Type", "application/json")
1367
1368 valid, errors := v.ValidateRequestBody(request)
1369
1370 assert.False(t, valid)
1371 assert.Len(t, errors, 1)
1372 assert.Len(t, errors[0].SchemaValidationErrors, 1)
1373 assert.Equal(t, "maxItems: got 4, want 2", errors[0].SchemaValidationErrors[0].Reason)
1374 assert.Equal(t, 2, errors[0].SchemaValidationErrors[0].Line)
1375 assert.Equal(t, "maxItems: got 4, want 2", errors[0].SchemaValidationErrors[0].Reason)
1376 assert.Equal(t, 11, errors[0].SchemaValidationErrors[0].Column)
1377 }
1378
1379 func TestValidateBody_SchemaHasNoRequestBody(t *testing.T) {
1380 spec := `openapi: 3.1.0
1381 paths:
1382 /burgers/createBurger:
1383 post:`
1384
1385 doc, _ := libopenapi.NewDocument([]byte(spec))
1386
1387 m, _ := doc.BuildV3Model()
1388 v := NewRequestBodyValidator(&m.Model)
1389
1390 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1391 http.NoBody)
1392 request.Header.Set("Content-Type", "application/json")
1393
1394 valid, errors := v.ValidateRequestBody(request)
1395
1396 assert.True(t, valid)
1397 assert.Len(t, errors, 0)
1398 }
1399
1400 func TestValidateBody_MediaTypeHasNullSchema(t *testing.T) {
1401 spec := `openapi: 3.1.0
1402 paths:
1403 /burgers/createBurger:
1404 post:
1405 requestBody:
1406 content:
1407 application/json:`
1408
1409 doc, _ := libopenapi.NewDocument([]byte(spec))
1410
1411 m, _ := doc.BuildV3Model()
1412 v := NewRequestBodyValidator(&m.Model)
1413
1414 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1415 http.NoBody)
1416 request.Header.Set("Content-Type", "application/json")
1417
1418 valid, errors := v.ValidateRequestBody(request)
1419
1420 assert.True(t, valid)
1421 assert.Len(t, errors, 0)
1422 }
1423
1424 func TestValidateBody_MissingBody(t *testing.T) {
1425 spec := `openapi: 3.1.0
1426 paths:
1427 /burgers/createBurger:
1428 post:
1429 requestBody:
1430 required: true
1431 content:
1432 application/json:
1433 schema:
1434 $ref: '#/components/schema_validation/TestBody'
1435 components:
1436 schema_validation:
1437 TestBody:
1438 type: array
1439 maxItems: 2
1440 items:
1441 type: object
1442 properties:
1443 name:
1444 type: string
1445 patties:
1446 type: integer
1447 maximum: 3
1448 minimum: 1
1449 vegetarian:
1450 type: boolean
1451 required: [name, patties, vegetarian] `
1452
1453 doc, _ := libopenapi.NewDocument([]byte(spec))
1454
1455 m, _ := doc.BuildV3Model()
1456 v := NewRequestBodyValidator(&m.Model)
1457
1458 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1459 http.NoBody)
1460 request.Header.Set("Content-Type", "application/json")
1461
1462 valid, errors := v.ValidateRequestBody(request)
1463
1464 assert.False(t, valid)
1465 assert.Len(t, errors, 1)
1466 }
1467
1468 func TestValidateBody_NoBodyNoNothing(t *testing.T) {
1469 spec := `openapi: 3.1.0
1470 paths:
1471 /burgers/createBurger:
1472 post:`
1473
1474 doc, _ := libopenapi.NewDocument([]byte(spec))
1475
1476 m, _ := doc.BuildV3Model()
1477 v := NewRequestBodyValidator(&m.Model)
1478
1479 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1480 http.NoBody)
1481 request.Header.Set("Content-Type", "application/json")
1482
1483 valid, errors := v.ValidateRequestBody(request)
1484
1485 assert.True(t, valid)
1486 assert.Len(t, errors, 0)
1487 }
1488
1489 func TestValidateBody_InvalidSchemaMultipleItems(t *testing.T) {
1490 spec := `openapi: 3.1.0
1491 paths:
1492 /burgers/createBurger:
1493 post:
1494 requestBody:
1495 content:
1496 application/json:
1497 schema:
1498 type: array
1499 items:
1500 type: object
1501 required:
1502 - name
1503 properties:
1504 name:
1505 type: string
1506 patties:
1507 type: integer
1508 vegetarian:
1509 type: boolean`
1510
1511 doc, _ := libopenapi.NewDocument([]byte(spec))
1512
1513 m, _ := doc.BuildV3Model()
1514 v := NewRequestBodyValidator(&m.Model)
1515
1516 var items []map[string]interface{}
1517 items = append(items, map[string]interface{}{
1518 "patties": 1,
1519 "vegetarian": true,
1520 })
1521 items = append(items, map[string]interface{}{
1522 "name": "Quarter Pounder",
1523 "patties": true,
1524 "vegetarian": false,
1525 })
1526 items = append(items, map[string]interface{}{
1527 "name": "Big Mac",
1528 "patties": 2,
1529 "vegetarian": false,
1530 })
1531
1532 bodyBytes, _ := json.Marshal(items)
1533
1534 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1535 bytes.NewBuffer(bodyBytes))
1536 request.Header.Set("Content-Type", "application/json")
1537
1538 valid, errors := v.ValidateRequestBody(request)
1539
1540 // double-tap to hit the cache
1541 _, _ = v.ValidateRequestBody(request)
1542
1543 assert.False(t, valid)
1544 assert.Len(t, errors, 1)
1545 assert.Len(t, errors[0].SchemaValidationErrors, 2)
1546 assert.Equal(t, "POST request body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
1547 }
1548
1549 func TestValidateBody_InvalidSchema_BadDecode(t *testing.T) {
1550 spec := `openapi: 3.1.0
1551 paths:
1552 /burgers/createBurger:
1553 post:
1554 requestBody:
1555 content:
1556 application/json:
1557 schema:
1558 $ref: '#/components/schema_validation/TestBody'
1559 components:
1560 schema_validation:
1561 TestBody:
1562 type: object
1563 properties:
1564 name:
1565 type: string
1566 patties:
1567 type: integer
1568 maximum: 3
1569 minimum: 1
1570 vegetarian:
1571 type: boolean
1572 required: [name, patties, vegetarian] `
1573
1574 doc, _ := libopenapi.NewDocument([]byte(spec))
1575
1576 m, _ := doc.BuildV3Model()
1577 v := NewRequestBodyValidator(&m.Model)
1578
1579 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1580 bytes.NewBuffer([]byte("{\"bad\": \"json\",}")))
1581 request.Header.Set("Content-Type", "application/json")
1582
1583 valid, errors := v.ValidateRequestBody(request)
1584
1585 assert.False(t, valid)
1586 assert.Len(t, errors, 1)
1587 assert.Nil(t, errors[0].SchemaValidationErrors)
1588 assert.Contains(t, errors[0].Reason, "cannot be decoded")
1589 }
1590
1591 func TestValidateBody_SchemaNoType_Issue75(t *testing.T) {
1592 spec := `{
1593 "openapi": "3.0.1",
1594 "info": {
1595 "title": "testing",
1596 "description": "<p>This is for testing purpose</p>",
1597 "version": "1.0",
1598 "x-targetEndpoint": "https://mocktarget.apigee.net/json"
1599 },
1600 "servers": [
1601 {
1602 "url": "https://some-url.com"
1603 }
1604 ],
1605 "paths": {
1606 "/path1": {
1607 "put": {
1608 "requestBody": {
1609 "required": true,
1610 "content": {
1611 "application/json": {
1612 "schema": {
1613 "anyOf": [
1614 {
1615 "type": "object",
1616 "properties": {
1617 "name": {
1618 "type": "string",
1619 "minLength": 1
1620 },
1621 "age": {
1622 "type": "integer"
1623 }
1624 },
1625 "required": [
1626 "name"
1627 ]
1628 },
1629 {
1630 "type": "object",
1631 "properties": {
1632 "email": {
1633 "type": "string"
1634 },
1635 "address": {
1636 "type": "string"
1637 }
1638 },
1639 "required": [
1640 "email"
1641 ]
1642 }
1643 ]
1644 }
1645 }
1646 }
1647 },
1648 "responses": {
1649 "200": {
1650 "description": "OK"
1651 }
1652 }
1653 }
1654 },
1655 "/path2": {
1656 "get": {
1657 "parameters": [
1658 {
1659 "name": "X-My-Header",
1660 "in": "header",
1661 "required": true,
1662 "schema": {
1663 "type": "string"
1664 }
1665 }
1666 ],
1667 "responses": {
1668 "200": {
1669 "description": "OK"
1670 }
1671 }
1672 }
1673 },
1674 "/path3": {
1675 "get": {
1676 "parameters": [
1677 {
1678 "name": "id",
1679 "in": "query",
1680 "required": true,
1681 "schema": {
1682 "type": "integer"
1683 }
1684 }
1685 ],
1686 "responses": {
1687 "200": {
1688 "description": "OK"
1689 }
1690 }
1691 }
1692 }
1693 }
1694 }
1695 `
1696
1697 doc, err := libopenapi.NewDocument([]byte(spec))
1698 if err != nil {
1699 fmt.Println("error while creating open api spec document", err)
1700 return
1701 }
1702
1703 req, err := http.NewRequest("PUT", "/path1", nil)
1704 if err != nil {
1705 fmt.Println("error while creating new HTTP request", err)
1706 return
1707 }
1708
1709 req.Header.Set("Content-Type", "application/json")
1710
1711 v3Model, errs := doc.BuildV3Model()
1712 if errs != nil {
1713 fmt.Println("error while building a Open API spec V3 model", errs)
1714 return
1715 }
1716
1717 reqBodyValidator := NewRequestBodyValidator(&v3Model.Model)
1718 isSuccess, valErrs := reqBodyValidator.ValidateRequestBody(req)
1719
1720 assert.False(t, isSuccess)
1721 assert.Len(t, valErrs, 1)
1722 assert.Equal(t, "PUT request body is empty for '/path1'", valErrs[0].Message)
1723 }
1724
1725 // https://github.com/pb33f/wiretap/issues/146
1726 func TestValidateBody_OptionalRequestBody_EmptyBody(t *testing.T) {
1727 spec := `openapi: 3.0.1
1728 info:
1729 title: test
1730 version: "1.0"
1731 paths:
1732 /test:
1733 post:
1734 requestBody:
1735 required: false
1736 content:
1737 application/json:
1738 schema:
1739 type: object
1740 properties:
1741 name:
1742 type: string
1743 responses:
1744 "200":
1745 description: OK`
1746
1747 doc, _ := libopenapi.NewDocument([]byte(spec))
1748 v3Model, _ := doc.BuildV3Model()
1749
1750 req, _ := http.NewRequest("POST", "/test", nil)
1751 req.Header.Set("Content-Type", "application/json")
1752
1753 reqBodyValidator := NewRequestBodyValidator(&v3Model.Model)
1754 isSuccess, valErrs := reqBodyValidator.ValidateRequestBody(req)
1755
1756 assert.True(t, isSuccess)
1757 assert.Empty(t, valErrs)
1758 }
1759
1760 // https://github.com/pb33f/libopenapi-validator/issues/144
1761 func TestValidateBody_InvalidSchema_EnsureOptionsPassthrough(t *testing.T) {
1762 spec := `openapi: 3.1.0
1763 paths:
1764 /burgers/createBurger:
1765 post:
1766 requestBody:
1767 content:
1768 application/json:
1769 schema:
1770 $ref: '#/components/schema_validation/V1_UserRequest'
1771 components:
1772 schema_validation:
1773 V1_UserRequest:
1774 type: object
1775 properties:
1776 email:
1777 type: string
1778 format: email
1779 minLength: 1
1780 maxLength: 320`
1781
1782 doc, _ := libopenapi.NewDocument([]byte(spec))
1783
1784 m, _ := doc.BuildV3Model()
1785 v := NewRequestBodyValidator(&m.Model, config.WithFormatAssertions())
1786
1787 items := make(map[string]interface{})
1788 items["email"] = "test"
1789
1790 bodyBytes, _ := json.Marshal(items)
1791
1792 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1793 bytes.NewBuffer(bodyBytes))
1794 request.Header.Set("Content-Type", "application/json")
1795
1796 valid, errors := v.ValidateRequestBody(request)
1797
1798 assert.False(t, valid)
1799 assert.Len(t, errors, 1)
1800 assert.Len(t, errors[0].SchemaValidationErrors, 1)
1801 assert.Equal(t, "POST request body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
1802
1803 assert.False(t, valid)
1804 assert.Len(t, errors, 1)
1805 assert.Len(t, errors[0].SchemaValidationErrors, 1)
1806 assert.Equal(t, "'test' is not valid email: missing @", errors[0].SchemaValidationErrors[0].Reason)
1807 }
1808
1809 func TestValidateBody_StrictMode_UndeclaredProperty(t *testing.T) {
1810 spec := `openapi: 3.1.0
1811 paths:
1812 /burgers/createBurger:
1813 post:
1814 requestBody:
1815 content:
1816 application/json:
1817 schema:
1818 type: object
1819 properties:
1820 name:
1821 type: string
1822 patties:
1823 type: integer`
1824
1825 doc, _ := libopenapi.NewDocument([]byte(spec))
1826
1827 m, _ := doc.BuildV3Model()
1828 v := NewRequestBodyValidator(&m.Model, config.WithStrictMode())
1829
1830 // Include an undeclared property 'extra'
1831 body := map[string]interface{}{
1832 "name": "Big Mac",
1833 "patties": 2,
1834 "extra": "undeclared property",
1835 }
1836
1837 bodyBytes, _ := json.Marshal(body)
1838
1839 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1840 bytes.NewBuffer(bodyBytes))
1841 request.Header.Set("Content-Type", "application/json")
1842
1843 valid, errors := v.ValidateRequestBody(request)
1844
1845 assert.False(t, valid)
1846 assert.Len(t, errors, 1)
1847 assert.Contains(t, errors[0].Message, "extra")
1848 assert.Contains(t, errors[0].Message, "not declared")
1849 }
1850
1851 func TestValidateBody_StrictMode_ValidRequest(t *testing.T) {
1852 spec := `openapi: 3.1.0
1853 paths:
1854 /burgers/createBurger:
1855 post:
1856 requestBody:
1857 content:
1858 application/json:
1859 schema:
1860 type: object
1861 properties:
1862 name:
1863 type: string
1864 patties:
1865 type: integer`
1866
1867 doc, _ := libopenapi.NewDocument([]byte(spec))
1868
1869 m, _ := doc.BuildV3Model()
1870 v := NewRequestBodyValidator(&m.Model, config.WithStrictMode())
1871
1872 // Only declared properties
1873 body := map[string]interface{}{
1874 "name": "Big Mac",
1875 "patties": 2,
1876 }
1877
1878 bodyBytes, _ := json.Marshal(body)
1879
1880 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
1881 bytes.NewBuffer(bodyBytes))
1882 request.Header.Set("Content-Type", "application/json")
1883
1884 valid, errors := v.ValidateRequestBody(request)
1885
1886 assert.True(t, valid)
1887 assert.Len(t, errors, 0)
1888 }
1889
1890 func TestValidateBody_StrictMode_ReadOnlyProperty(t *testing.T) {
1891 spec := `openapi: 3.1.0
1892 paths:
1893 /users:
1894 post:
1895 requestBody:
1896 content:
1897 application/json:
1898 schema:
1899 type: object
1900 properties:
1901 id:
1902 type: string
1903 readOnly: true
1904 name:
1905 type: string`
1906
1907 doc, _ := libopenapi.NewDocument([]byte(spec))
1908
1909 m, _ := doc.BuildV3Model()
1910 v := NewRequestBodyValidator(&m.Model,
1911 config.WithStrictMode(),
1912 config.WithStrictRejectReadOnly(),
1913 )
1914
1915 body := map[string]interface{}{
1916 "id": "user-123",
1917 "name": "John",
1918 }
1919
1920 bodyBytes, _ := json.Marshal(body)
1921
1922 request, _ := http.NewRequest(http.MethodPost, "https://things.com/users",
1923 bytes.NewBuffer(bodyBytes))
1924 request.Header.Set("Content-Type", "application/json")
1925
1926 valid, errors := v.ValidateRequestBody(request)
1927
1928 assert.False(t, valid)
1929 assert.Len(t, errors, 1)
1930 assert.Contains(t, errors[0].Message, "readOnly")
1931 assert.Contains(t, errors[0].Message, "id")
1932 }
1933
1934 func TestValidateRequestBody_XMLMarshalError(t *testing.T) {
1935 spec := []byte(`
1936 openapi: 3.1.0
1937 info:
1938 title: Test Spec
1939 version: 1.0.0
1940 paths:
1941 /test:
1942 post:
1943 requestBody:
1944 required: true
1945 content:
1946 application/xml:
1947 schema:
1948 type: object
1949 properties:
1950 bad_number:
1951 type: number
1952 responses:
1953 '200':
1954 description: Success
1955 `)
1956
1957 doc, _ := libopenapi.NewDocument([]byte(spec))
1958
1959 m, _ := doc.BuildV3Model()
1960 v := NewRequestBodyValidator(&m.Model, config.WithXmlBodyValidation())
1961
1962 request, _ := http.NewRequest(http.MethodPost, "https://things.com/test",
1963 bytes.NewBuffer([]byte("<bad_number>NaN</bad_number>")))
1964 request.Header.Set("Content-Type", "application/xml")
1965
1966 valid, errors := v.ValidateRequestBody(request)
1967
1968 assert.False(t, valid)
1969 assert.Len(t, errors, 1)
1970 assert.Equal(t, errors[0].Message, "xml example is malformed")
1971 }
1972
1973 func TestValidateRequestBody_URLEncodedMarshalError(t *testing.T) {
1974 spec := []byte(`
1975 openapi: 3.1.0
1976 info:
1977 title: Test Spec
1978 version: 1.0.0
1979 paths:
1980 /test:
1981 post:
1982 requestBody:
1983 required: true
1984 content:
1985 application/x-www-form-urlencoded:
1986 schema:
1987 type: object
1988 properties:
1989 bad_number:
1990 type: number
1991 responses:
1992 '200':
1993 description: Success
1994 `)
1995
1996 doc, _ := libopenapi.NewDocument([]byte(spec))
1997
1998 m, _ := doc.BuildV3Model()
1999 v := NewRequestBodyValidator(&m.Model, config.WithURLEncodedBodyValidation())
2000
2001 request, _ := http.NewRequest(http.MethodPost, "https://things.com/test",
2002 bytes.NewBuffer([]byte("bad_number=NaN")))
2003 request.Header.Set("Content-Type", helpers.URLEncodedContentType)
2004
2005 valid, errors := v.ValidateRequestBody(request)
2006
2007 assert.False(t, valid)
2008 assert.Len(t, errors, 1)
2009 assert.Equal(t, errors[0].Message, "Unable to parse form-urlencoded body")
2010 }
2011
2012 func TestValidateBody_URLEncodedRequest(t *testing.T) {
2013 spec := `openapi: 3.1.0
2014 paths:
2015 /burgers/createBurger:
2016 post:
2017 requestBody:
2018 content:
2019 application/x-www-form-urlencoded:
2020 schema:
2021 type: object
2022 required:
2023 - name
2024 properties:
2025 name:
2026 type: string
2027 patties:
2028 type: integer`
2029
2030 doc, _ := libopenapi.NewDocument([]byte(spec))
2031
2032 m, _ := doc.BuildV3Model()
2033 v := NewRequestBodyValidator(&m.Model, config.WithURLEncodedBodyValidation())
2034
2035 body := "name=cheeseburger&patties=23"
2036
2037 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
2038 bytes.NewBuffer([]byte(body)))
2039 request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
2040
2041 valid, errors := v.ValidateRequestBody(request)
2042 assert.True(t, valid)
2043 assert.Len(t, errors, 0)
2044
2045 body = "name=cheeseburger&patties=23.4"
2046
2047 request, _ = http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
2048 bytes.NewBuffer([]byte(body)))
2049 request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
2050
2051 valid, errors = v.ValidateRequestBody(request)
2052
2053 assert.False(t, valid)
2054 assert.Len(t, errors, 1)
2055 }
2056
2057 func TestValidateBody_XmlRequest(t *testing.T) {
2058 spec := `openapi: 3.1.0
2059 paths:
2060 /burgers/createBurger:
2061 post:
2062 requestBody:
2063 content:
2064 application/xml:
2065 schema:
2066 type: object
2067 required:
2068 - name
2069 properties:
2070 name:
2071 type: string
2072 patties:
2073 type: integer
2074 xml:
2075 name: cost`
2076
2077 doc, _ := libopenapi.NewDocument([]byte(spec))
2078
2079 m, _ := doc.BuildV3Model()
2080 v := NewRequestBodyValidator(&m.Model, config.WithXmlBodyValidation())
2081
2082 body := "<name>cheeseburger</name><cost>23</cost>"
2083
2084 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
2085 bytes.NewBuffer([]byte(body)))
2086 request.Header.Set("Content-Type", "application/xml")
2087
2088 valid, errors := v.ValidateRequestBody(request)
2089
2090 assert.True(t, valid)
2091 assert.Len(t, errors, 0)
2092 }
2093
2094 func TestValidateBody_XmlMalformedRequest(t *testing.T) {
2095 spec := `openapi: 3.1.0
2096 paths:
2097 /burgers/createBurger:
2098 post:
2099 requestBody:
2100 content:
2101 application/xml:
2102 schema:
2103 type: object
2104 required:
2105 - name
2106 properties:
2107 name:
2108 type: string
2109 patties:
2110 type: integer
2111 xml:
2112 name: cost`
2113
2114 doc, _ := libopenapi.NewDocument([]byte(spec))
2115
2116 m, _ := doc.BuildV3Model()
2117 v := NewRequestBodyValidator(&m.Model, config.WithXmlBodyValidation())
2118
2119 body := ""
2120
2121 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
2122 bytes.NewBuffer([]byte(body)))
2123 request.Header.Set("Content-Type", "application/xml")
2124
2125 valid, errors := v.ValidateRequestBody(request)
2126
2127 assert.False(t, valid)
2128 assert.Len(t, errors, 1)
2129
2130 err := errors[0]
2131 assert.Equal(t, helpers.XmlValidation, err.ValidationType)
2132 assert.Contains(t, err.Reason, "failed to parse xml")
2133 }
2134
2135 func TestValidateBody_XmlRequestTransformations(t *testing.T) {
2136 spec := `openapi: 3.1.0
2137 paths:
2138 /burgers/createBurger:
2139 post:
2140 requestBody:
2141 content:
2142 application/xml:
2143 schema:
2144 type: object
2145 xml:
2146 name: Burger
2147 required:
2148 - name
2149 - patties
2150 properties:
2151 name:
2152 type: string
2153 patties:
2154 type: integer
2155 xml:
2156 name: cost`
2157
2158 doc, _ := libopenapi.NewDocument([]byte(spec))
2159
2160 m, _ := doc.BuildV3Model()
2161 v := NewRequestBodyValidator(&m.Model, config.WithXmlBodyValidation())
2162
2163 body := "<Burger><name>cheeseburger</name><cost>23</cost></Burger>"
2164
2165 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger",
2166 bytes.NewBuffer([]byte(body)))
2167 request.Header.Set("Content-Type", "application/xml")
2168
2169 valid, errors := v.ValidateRequestBody(request)
2170
2171 assert.True(t, valid)
2172 assert.Len(t, errors, 0)
2173 }