Debian Codegraph @

responses/validate_body_test.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package responses
5
6 import (
7 "bytes"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net/http"
14 "net/http/httptest"
15 "strings"
16 "testing"
17
18 "github.com/pb33f/libopenapi"
19 "github.com/stretchr/testify/assert"
20 "github.com/stretchr/testify/require"
21
22 "github.com/pb33f/libopenapi-validator/config"
23 "github.com/pb33f/libopenapi-validator/helpers"
24 "github.com/pb33f/libopenapi-validator/paths"
25 )
26
27 type validateResponseTestBed struct {
28 responseBodyValidator ResponseBodyValidator
29 httpTestServer *httptest.Server
30 responseHandlerFunc http.HandlerFunc
31 }
32
33 func newvalidateResponseTestBed(
34 t *testing.T,
35 openApiSpec []byte,
36 ) *validateResponseTestBed {
37 doc, err := libopenapi.NewDocument(openApiSpec)
38 if err != nil {
39 t.Fatalf("failed to create openapi document: %v", err)
40 }
41
42 m, buildV3ModelErr := doc.BuildV3Model()
43 if buildV3ModelErr != nil {
44 t.Fatalf("failed to build v3 model: %v", err)
45 }
46
47 tb := validateResponseTestBed{responseBodyValidator: NewResponseBodyValidator(&m.Model, config.WithXmlBodyValidation(), config.WithURLEncodedBodyValidation())}
48 tb.httpTestServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
49 if tb.responseHandlerFunc != nil {
50 tb.responseHandlerFunc(w, r)
51 return
52 }
53
54 w.WriteHeader(http.StatusOK)
55 }))
56
57 t.Cleanup(func() {
58 tb.httpTestServer.Close()
59 })
60
61 return &tb
62 }
63
64 func (tb *validateResponseTestBed) makeRequestWithReponse(
65 t *testing.T,
66 method string,
67 path string,
68 responseHandler http.HandlerFunc,
69 ) (
70 *http.Request,
71 *http.Response,
72 ) {
73 tb.responseHandlerFunc = responseHandler
74
75 req, err := http.NewRequestWithContext(context.TODO(), method, tb.httpTestServer.URL+path, nil)
76 if err != nil {
77 t.Fatalf("failed to create http request: %v", err)
78 }
79
80 res, err := http.DefaultClient.Do(req)
81 if err != nil {
82 t.Fatalf("failed to perform http request: %v", err)
83 }
84
85 return req, res
86 }
87
88 func TestValidateBody_MissingContentType(t *testing.T) {
89 tb := newvalidateResponseTestBed(
90 t,
91 []byte(`openapi: 3.1.0
92 paths:
93 /burgers/createBurger:
94 post:
95 responses:
96 '200':
97 content:
98 application/json:
99 schema:
100 type: object
101 properties:
102 name:
103 type: string
104 patties:
105 type: integer
106 vegetarian:
107 type: boolean`,
108 ),
109 )
110
111 req, res := tb.makeRequestWithReponse(
112 t,
113 http.MethodPost,
114 "/burgers/createBurger",
115 func(w http.ResponseWriter, r *http.Request) {
116 w.Header().Set(helpers.ContentTypeHeader, "cheeky/monkey")
117 w.WriteHeader(http.StatusOK)
118 _, _ = w.Write([]byte(`{"name":"Big Mac","patties":false,"vegetarian":2}`))
119 },
120 )
121
122 // validate!
123 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
124
125 assert.False(t, valid)
126 assert.Len(t, errors, 1)
127 assert.Equal(t, "POST / 200 operation response content type 'cheeky/monkey' does not exist", errors[0].Message)
128 assert.Equal(t, "The content type is invalid, Use one of the 1 supported types for this operation: application/json", errors[0].HowToFix)
129 assert.Equal(t, req.Method, errors[0].RequestMethod)
130 assert.Equal(t, req.URL.Path, errors[0].RequestPath)
131 assert.Equal(t, "/burgers/createBurger", errors[0].SpecPath)
132 }
133
134 func TestValidateBody_MissingContentType4XX(t *testing.T) {
135 tb := newvalidateResponseTestBed(
136 t,
137 []byte(`openapi: 3.1.0
138 paths:
139 /burgers/createBurger:
140 post:
141 responses:
142 4XX:
143 content:
144 application/json:
145 schema:
146 type: object
147 properties:
148 error:
149 type: string`,
150 ),
151 )
152
153 req, res := tb.makeRequestWithReponse(
154 t,
155 http.MethodPost,
156 "/burgers/createBurger",
157 func(w http.ResponseWriter, r *http.Request) {
158 bodyBytes, err := json.Marshal(map[string]interface{}{
159 "name": "Big Mac",
160 "patties": false,
161 "vegetarian": 2,
162 })
163
164 require.NoError(t, err, "failed to marshal body")
165
166 w.Header().Set(helpers.ContentTypeHeader, "cheeky/monkey")
167 w.WriteHeader(http.StatusBadRequest)
168 _, _ = w.Write(bodyBytes)
169 },
170 )
171
172 // validate!
173 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
174
175 assert.False(t, valid)
176 assert.Len(t, errors, 1)
177 assert.Equal(t, "POST / 4XX operation response content type 'cheeky/monkey' does not exist", errors[0].Message)
178 assert.Equal(t, "The content type is invalid, Use one of the 1 supported types for this operation: application/json", errors[0].HowToFix)
179 assert.Equal(t, req.Method, errors[0].RequestMethod)
180 assert.Equal(t, req.URL.Path, errors[0].RequestPath)
181 assert.Equal(t, "/burgers/createBurger", errors[0].SpecPath)
182 }
183
184 func TestValidateBody_MissingPath(t *testing.T) {
185 tb := newvalidateResponseTestBed(
186 t,
187 []byte(`openapi: 3.1.0
188 paths:
189 /burgers/createBurger:
190 post:
191 responses:
192 '200':
193 content:
194 application/json:
195 schema:
196 type: object
197 properties:
198 name:
199 type: string
200 patties:
201 type: integer
202 vegetarian:
203 type: boolean`,
204 ),
205 )
206
207 req, res := tb.makeRequestWithReponse(
208 t,
209 http.MethodPost,
210 "/I do not exist",
211 func(w http.ResponseWriter, r *http.Request) {
212 bodyBytes, err := json.Marshal(map[string]interface{}{
213 "name": "Big Mac",
214 "patties": false,
215 "vegetarian": 2,
216 })
217
218 require.NoError(t, err, "failed to marshal body")
219
220 w.Header().Set(helpers.ContentTypeHeader, "cheeky/monkey") // won't even matter!
221 w.WriteHeader(http.StatusUnprocessableEntity) // does not matter.
222 _, _ = w.Write(bodyBytes)
223 },
224 )
225
226 // validate!
227 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
228
229 assert.False(t, valid)
230 assert.Len(t, errors, 1)
231 assert.Equal(t, "POST Path '/I do not exist' not found", errors[0].Message)
232 assert.Equal(t, req.Method, errors[0].RequestMethod)
233 assert.Equal(t, req.URL.Path, errors[0].RequestPath)
234 assert.Equal(t, "", errors[0].SpecPath)
235 }
236
237 func TestValidateBody_SetPath(t *testing.T) {
238 tb := newvalidateResponseTestBed(
239 t,
240 []byte(`openapi: 3.1.0
241 paths:
242 /burgers/createBurger:
243 post:
244 responses:
245 '200':
246 content:
247 application/json:
248 schema:
249 type: object
250 properties:
251 name:
252 type: string
253 patties:
254 type: integer
255 vegetarian:
256 type: boolean`,
257 ),
258 )
259
260 req, res := tb.makeRequestWithReponse(
261 t,
262 http.MethodPost,
263 "/I do not exist",
264 func(w http.ResponseWriter, r *http.Request) {
265 bodyBytes, err := json.Marshal(map[string]interface{}{
266 "name": "Big Mac",
267 "patties": false,
268 "vegetarian": 2,
269 })
270
271 require.NoError(t, err, "failed to marshal body")
272
273 w.Header().Set(helpers.ContentTypeHeader, "cheeky/monkey") // won't even matter!
274 w.WriteHeader(http.StatusUnprocessableEntity) // does not matter.
275 _, _ = w.Write(bodyBytes)
276 },
277 )
278
279 // preset the path
280 m := tb.responseBodyValidator.(*responseBodyValidator).document
281 path, _, pv := paths.FindPath(req, m, nil)
282
283 // validate!
284 valid, errors := tb.responseBodyValidator.ValidateResponseBodyWithPathItem(req, res, path, pv)
285
286 assert.False(t, valid)
287 assert.Len(t, errors, 1)
288 assert.Equal(t, "POST Path '/I do not exist' not found", errors[0].Message)
289 }
290
291 func TestValidateBody_SetPath_missing_operation(t *testing.T) {
292 tb := newvalidateResponseTestBed(
293 t,
294 []byte(`openapi: 3.1.0
295 paths:
296 /burgers/createBurger:
297 post:
298 responses:
299 '200':
300 content:
301 application/json:
302 schema:
303 type: object
304 properties:
305 name:
306 type: string
307 patties:
308 type: integer
309 vegetarian:
310 type: boolean`,
311 ),
312 )
313
314 req, res := tb.makeRequestWithReponse(
315 t,
316 http.MethodPost,
317 "/burgers/createBurger",
318 func(w http.ResponseWriter, r *http.Request) {
319 bodyBytes, err := json.Marshal(map[string]interface{}{
320 "name": "Big Mac",
321 "patties": 2,
322 "vegetarian": false,
323 })
324
325 require.NoError(t, err, "failed to marshal body")
326
327 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) // won't even matter!
328 w.WriteHeader(http.StatusOK)
329 _, _ = w.Write(bodyBytes)
330 },
331 )
332
333 // preset the path
334 m := tb.responseBodyValidator.(*responseBodyValidator).document
335 path, _, pv := paths.FindPath(req, m, nil)
336
337 // Create a different request with GET method to test missing operation
338 request2, _ := http.NewRequest(http.MethodGet, req.URL.String(), nil)
339 request2.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
340
341 // validate!
342 valid, errors := tb.responseBodyValidator.ValidateResponseBodyWithPathItem(request2, res, path, pv)
343
344 assert.False(t, valid)
345 assert.Len(t, errors, 1)
346 assert.Equal(t, "GET operation request content type 'GET' does not exist", errors[0].Message)
347 }
348
349 func TestValidateBody_MissingStatusCode(t *testing.T) {
350 tb := newvalidateResponseTestBed(
351 t,
352 []byte(`openapi: 3.1.0
353 paths:
354 /burgers/createBurger:
355 post:
356 responses:
357 '200':
358 content:
359 application/json:
360 schema:
361 type: object
362 properties:
363 name:
364 type: string
365 patties:
366 type: integer
367 vegetarian:
368 type: boolean`,
369 ),
370 )
371
372 req, res := tb.makeRequestWithReponse(
373 t,
374 http.MethodPost,
375 "/burgers/createBurger",
376 func(w http.ResponseWriter, r *http.Request) {
377 bodyBytes, err := json.Marshal(map[string]interface{}{
378 "name": "Big Mac",
379 "patties": false,
380 "vegetarian": 2,
381 })
382
383 require.NoError(t, err, "failed to marshal body")
384
385 w.Header().Set(helpers.ContentTypeHeader, "cheeky/monkey") // won't even matter!
386 w.WriteHeader(http.StatusUnprocessableEntity) // undefined in the spec.
387 _, _ = w.Write(bodyBytes)
388 },
389 )
390
391 // validate!
392 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
393
394 assert.False(t, valid)
395 assert.Len(t, errors, 1)
396 assert.Equal(t, "POST operation request response code '422' does not exist", errors[0].Message)
397 assert.Equal(t, "The service is responding with a code that is not defined in the spec, fix the service or add the code to the specification", errors[0].HowToFix)
398 }
399
400 func TestValidateBody_InvalidBasicSchema(t *testing.T) {
401 tb := newvalidateResponseTestBed(
402 t,
403 []byte(`openapi: 3.1.0
404 paths:
405 /burgers/createBurger:
406 post:
407 responses:
408 '200':
409 content:
410 application/json:
411 schema:
412 type: object
413 properties:
414 name:
415 type: string
416 patties:
417 type: integer
418 vegetarian:
419 type: boolean`,
420 ),
421 )
422
423 req, res := tb.makeRequestWithReponse(
424 t,
425 http.MethodPost,
426 "/burgers/createBurger",
427 func(w http.ResponseWriter, r *http.Request) {
428 // mix up the primitives to fire two schema violations.
429 bodyBytes, err := json.Marshal(map[string]interface{}{
430 "name": "Big Mac",
431 "patties": false,
432 "vegetarian": 2,
433 })
434
435 require.NoError(t, err, "failed to marshal body")
436
437 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
438 w.WriteHeader(http.StatusOK)
439 _, _ = w.Write(bodyBytes)
440 },
441 )
442
443 // validate!
444 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
445
446 // doubletap to hit cache
447 _, _ = tb.responseBodyValidator.ValidateResponseBody(req, res)
448
449 assert.False(t, valid)
450 assert.Len(t, errors, 1)
451 assert.Len(t, errors[0].SchemaValidationErrors, 2)
452 }
453
454 func TestValidateBody_NoBody(t *testing.T) {
455 tb := newvalidateResponseTestBed(
456 t,
457 []byte(`openapi: 3.1.0
458 paths:
459 /burgers/createBurger:
460 post:
461 responses:
462 '200':
463 content:
464 application/json:
465 schema:
466 type: object
467 properties:
468 name:
469 type: string
470 patties:
471 type: integer
472 vegetarian:
473 type: boolean`,
474 ),
475 )
476
477 req, res := tb.makeRequestWithReponse(
478 t,
479 http.MethodPost,
480 "/burgers/createBurger",
481 func(w http.ResponseWriter, r *http.Request) {
482 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
483 w.WriteHeader(http.StatusOK)
484 // Don't write anything - this creates a response with no body
485 },
486 )
487
488 // validate!
489 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
490
491 // doubletap to hit cache
492 _, _ = tb.responseBodyValidator.ValidateResponseBody(req, res)
493
494 // With the real HTTP server, an empty body is now properly detected
495 assert.False(t, valid)
496 assert.Len(t, errors, 1)
497 assert.Equal(t, "POST response object is missing for '/burgers/createBurger'", errors[0].Message)
498 }
499
500 func TestValidateBody_InvalidResponseBodyNil(t *testing.T) {
501 tb := newvalidateResponseTestBed(
502 t,
503 []byte(`openapi: 3.1.0
504 paths:
505 /burgers/createBurger:
506 post:
507 responses:
508 '200':
509 content:
510 application/json:
511 schema:
512 type: object
513 properties:
514 name:
515 type: string
516 patties:
517 type: integer
518 vegetarian:
519 type: boolean`,
520 ),
521 )
522
523 req, res := tb.makeRequestWithReponse(
524 t,
525 http.MethodPost,
526 "/burgers/createBurger",
527 func(w http.ResponseWriter, r *http.Request) {
528 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
529 w.WriteHeader(http.StatusOK)
530 // Don't write anything - this creates a response with no body
531 },
532 )
533
534 // validate!
535 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
536
537 // doubletap to hit cache
538 _, _ = tb.responseBodyValidator.ValidateResponseBody(req, res)
539
540 assert.False(t, valid)
541 require.Len(t, errors, 1)
542 assert.ErrorContains(t, errors[0], "response object is missing")
543 }
544
545 func TestValidateBody_InvalidResponseBodyError(t *testing.T) {
546 tb := newvalidateResponseTestBed(
547 t,
548 []byte(`openapi: 3.1.0
549 paths:
550 /burgers/createBurger:
551 post:
552 responses:
553 '200':
554 content:
555 application/json:
556 schema:
557 type: object
558 properties:
559 name:
560 type: string
561 patties:
562 type: integer
563 vegetarian:
564 type: boolean`,
565 ),
566 )
567
568 req, res := tb.makeRequestWithReponse(
569 t,
570 http.MethodPost,
571 "/burgers/createBurger",
572 func(w http.ResponseWriter, r *http.Request) {
573 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
574 w.WriteHeader(http.StatusOK)
575 // Don't write anything - this creates a response with no body
576 },
577 )
578
579 // simulate an error reading the body
580 res.Body = &errorReader{}
581
582 // validate!
583 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
584
585 // doubletap to hit cache
586 _, _ = tb.responseBodyValidator.ValidateResponseBody(req, res)
587
588 assert.False(t, valid)
589 require.Len(t, errors, 1)
590 assert.ErrorContains(t, errors[0], "The response body cannot be decoded: some io error")
591 }
592
593 func TestValidateBody_InvalidBasicSchema_SetPath(t *testing.T) {
594 spec := `openapi: 3.1.0
595 paths:
596 /burgers/createBurger:
597 post:
598 responses:
599 '200':
600 content:
601 application/json:
602 schema:
603 type: object
604 properties:
605 name:
606 type: string
607 patties:
608 type: integer
609 vegetarian:
610 type: boolean`
611
612 doc, _ := libopenapi.NewDocument([]byte(spec))
613
614 m, _ := doc.BuildV3Model()
615 v := NewResponseBodyValidator(&m.Model)
616
617 // mix up the primitives to fire two schema violations.
618 body := map[string]interface{}{
619 "name": "Big Mac",
620 "patties": false,
621 "vegetarian": 2,
622 }
623
624 bodyBytes, _ := json.Marshal(body)
625
626 // build a request
627 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader(bodyBytes))
628 request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
629
630 // simulate a request/response
631 res := httptest.NewRecorder()
632 handler := func(w http.ResponseWriter, r *http.Request) {
633 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
634 w.WriteHeader(http.StatusOK)
635 _, _ = w.Write(bodyBytes)
636 }
637
638 // fire the request
639 handler(res, request)
640
641 // record response
642 response := res.Result()
643
644 // preset the path
645 path, _, pv := paths.FindPath(request, &m.Model, nil)
646
647 // validate!
648 valid, errors := v.ValidateResponseBodyWithPathItem(request, response, path, pv)
649
650 assert.False(t, valid)
651 assert.Len(t, errors, 1)
652 assert.Len(t, errors[0].SchemaValidationErrors, 2)
653 assert.Equal(t, "200 response body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
654 }
655
656 func TestValidateBody_ValidComplexSchema(t *testing.T) {
657 tb := newvalidateResponseTestBed(
658 t,
659 []byte(`openapi: 3.1.0
660 paths:
661 /burgers/createBurger:
662 post:
663 responses:
664 '200':
665 content:
666 application/json:
667 schema:
668 $ref: '#/components/schema_validation/TestBody'
669 components:
670 schema_validation:
671 Uncooked:
672 type: object
673 required: [uncookedWeight, uncookedHeight]
674 properties:
675 uncookedWeight:
676 type: number
677 uncookedHeight:
678 type: number
679 Cooked:
680 type: object
681 required: [usedOil, usedAnimalFat]
682 properties:
683 usedOil:
684 type: boolean
685 usedAnimalFat:
686 type: boolean
687 Nutrients:
688 type: object
689 required: [fat, salt, meat]
690 properties:
691 fat:
692 type: number
693 salt:
694 type: number
695 meat:
696 type: string
697 enum:
698 - beef
699 - pork
700 - lamb
701 - vegetables
702 TestBody:
703 type: object
704 oneOf:
705 - $ref: '#/components/schema_validation/Uncooked'
706 - $ref: '#/components/schema_validation/Cooked'
707 allOf:
708 - $ref: '#/components/schema_validation/Nutrients'
709 properties:
710 name:
711 type: string
712 patties:
713 type: integer
714 vegetarian:
715 type: boolean
716 required: [name, patties, vegetarian]`,
717 ),
718 )
719
720 body := map[string]interface{}{
721 "name": "Big Mac",
722 "patties": 2,
723 "vegetarian": true,
724 "fat": 10.0,
725 "salt": 0.5,
726 "meat": "beef",
727 "usedOil": true,
728 "usedAnimalFat": false,
729 }
730
731 bodyBytes, _ := json.Marshal(body)
732
733 req, res := tb.makeRequestWithReponse(
734 t,
735 http.MethodPost,
736 "/burgers/createBurger",
737 func(w http.ResponseWriter, r *http.Request) {
738 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
739 w.WriteHeader(http.StatusOK)
740 _, _ = w.Write(bodyBytes)
741 },
742 )
743
744 // validate!
745 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
746
747 assert.True(t, valid)
748 assert.Len(t, errors, 0)
749 }
750
751 func TestValidateBody_InvalidComplexSchema(t *testing.T) {
752 tb := newvalidateResponseTestBed(
753 t,
754 []byte(`openapi: 3.1.0
755 paths:
756 /burgers/createBurger:
757 post:
758 responses:
759 '200':
760 content:
761 application/json:
762 schema:
763 $ref: '#/components/schema_validation/TestBody'
764 components:
765 schema_validation:
766 Uncooked:
767 type: object
768 required: [uncookedWeight, uncookedHeight]
769 properties:
770 uncookedWeight:
771 type: number
772 uncookedHeight:
773 type: number
774 Cooked:
775 type: object
776 required: [usedOil, usedAnimalFat]
777 properties:
778 usedOil:
779 type: boolean
780 usedAnimalFat:
781 type: boolean
782 Nutrients:
783 type: object
784 required: [fat, salt, meat]
785 properties:
786 fat:
787 type: number
788 salt:
789 type: number
790 meat:
791 type: string
792 enum:
793 - beef
794 - pork
795 - lamb
796 - vegetables
797 TestBody:
798 type: object
799 oneOf:
800 - $ref: '#/components/schema_validation/Uncooked'
801 - $ref: '#/components/schema_validation/Cooked'
802 allOf:
803 - $ref: '#/components/schema_validation/Nutrients'
804 properties:
805 name:
806 type: string
807 patties:
808 type: integer
809 vegetarian:
810 type: boolean
811 required: [name, patties, vegetarian]`,
812 ),
813 )
814
815 req, res := tb.makeRequestWithReponse(
816 t,
817 http.MethodPost,
818 "/burgers/createBurger",
819 func(w http.ResponseWriter, r *http.Request) {
820 bodyBytes, err := json.Marshal(map[string]interface{}{
821 "name": "Big Mac",
822 "patties": 2,
823 "vegetarian": true,
824 "fat": 10.0,
825 "salt": 0.5,
826 "meat": "beef",
827 "usedOil": 12345, // invalid, should be bool
828 "usedAnimalFat": false,
829 })
830
831 require.NoError(t, err, "failed to marshal body")
832
833 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
834 w.WriteHeader(http.StatusOK)
835 _, _ = w.Write(bodyBytes)
836 },
837 )
838
839 // validate!
840 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
841
842 assert.False(t, valid)
843 assert.Len(t, errors, 1)
844 assert.Len(t, errors[0].SchemaValidationErrors, 2)
845 assert.Equal(t, "missing properties 'uncookedWeight', 'uncookedHeight'", errors[0].SchemaValidationErrors[0].Reason)
846 }
847
848 func TestValidateBody_ValidBasicSchema(t *testing.T) {
849 tb := newvalidateResponseTestBed(
850 t,
851 []byte(`openapi: 3.1.0
852 paths:
853 /burgers/createBurger:
854 post:
855 responses:
856 '200':
857 content:
858 application/json:
859 schema:
860 type: object
861 properties:
862 name:
863 type: string
864 patties:
865 type: integer
866 vegetarian:
867 type: boolean`,
868 ),
869 )
870
871 req, res := tb.makeRequestWithReponse(
872 t,
873 http.MethodPost,
874 "/burgers/createBurger",
875 func(w http.ResponseWriter, r *http.Request) {
876 bodyBytes, err := json.Marshal(map[string]interface{}{
877 "name": "Big Mac",
878 "patties": 2,
879 "vegetarian": false,
880 })
881
882 require.NoError(t, err, "failed to marshal body")
883
884 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
885 w.WriteHeader(http.StatusOK)
886 _, _ = w.Write(bodyBytes)
887 },
888 )
889
890 // validate!
891 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
892
893 assert.True(t, valid)
894 assert.Len(t, errors, 0)
895 }
896
897 func TestValidateBody_ValidBasicSchema_WithFullContentTypeHeader(t *testing.T) {
898 tb := newvalidateResponseTestBed(
899 t,
900 []byte(`openapi: 3.1.0
901 paths:
902 /burgers/createBurger:
903 post:
904 responses:
905 '200':
906 content:
907 application/json:
908 schema:
909 type: object
910 properties:
911 name:
912 type: string
913 patties:
914 type: integer
915 vegetarian:
916 type: boolean`,
917 ),
918 )
919
920 req, res := tb.makeRequestWithReponse(
921 t,
922 http.MethodPost,
923 "/burgers/createBurger",
924 func(w http.ResponseWriter, r *http.Request) {
925 bodyBytes, err := json.Marshal(map[string]interface{}{
926 "name": "Big Mac",
927 "patties": 2,
928 "vegetarian": false,
929 })
930
931 require.NoError(t, err, "failed to marshal body")
932
933 // inject a full content type header, including charset and boundary
934 w.Header().Set(helpers.ContentTypeHeader,
935 fmt.Sprintf("%s; charset=utf-8; boundary=---12223344", helpers.JSONContentType))
936 w.WriteHeader(http.StatusOK)
937 _, _ = w.Write(bodyBytes)
938 },
939 )
940
941 // validate!
942 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
943
944 assert.True(t, valid)
945 assert.Len(t, errors, 0)
946 }
947
948 func TestValidateBody_ValidBasicSchemaUsingDefault(t *testing.T) {
949 tb := newvalidateResponseTestBed(
950 t,
951 []byte(`openapi: 3.1.0
952 paths:
953 /burgers/createBurger:
954 post:
955 responses:
956 default:
957 content:
958 application/json:
959 schema:
960 type: object
961 properties:
962 name:
963 type: string
964 patties:
965 type: integer
966 vegetarian:
967 type: boolean`,
968 ),
969 )
970
971 req, res := tb.makeRequestWithReponse(
972 t,
973 http.MethodPost,
974 "/burgers/createBurger",
975 func(w http.ResponseWriter, r *http.Request) {
976 bodyBytes, err := json.Marshal(map[string]interface{}{
977 "name": "Big Mac",
978 "patties": 2,
979 "vegetarian": false,
980 })
981
982 require.NoError(t, err, "failed to marshal body")
983
984 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
985 w.WriteHeader(http.StatusOK)
986 _, _ = w.Write(bodyBytes)
987 },
988 )
989
990 // validate!
991 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
992
993 assert.True(t, valid)
994 assert.Len(t, errors, 0)
995 }
996
997 func TestValidateBody_InvalidBasicSchemaUsingDefault_MissingContentType(t *testing.T) {
998 tb := newvalidateResponseTestBed(
999 t,
1000 []byte(`openapi: 3.1.0
1001 paths:
1002 /burgers/createBurger:
1003 post:
1004 responses:
1005 default:
1006 content:
1007 application/json:
1008 schema:
1009 type: object
1010 properties:
1011 name:
1012 type: string
1013 patties:
1014 type: integer
1015 vegetarian:
1016 type: boolean`,
1017 ),
1018 )
1019
1020 req, res := tb.makeRequestWithReponse(
1021 t,
1022 http.MethodPost,
1023 "/burgers/createBurger",
1024 func(w http.ResponseWriter, r *http.Request) {
1025 // primitives are now correct.
1026 bodyBytes, err := json.Marshal(map[string]interface{}{
1027 "name": "Big Mac",
1028 "patties": 2,
1029 "vegetarian": false,
1030 })
1031
1032 require.NoError(t, err, "failed to marshal body")
1033
1034 w.Header().Set(helpers.ContentTypeHeader, "chicken/nuggets;chicken=soup")
1035 w.WriteHeader(http.StatusOK)
1036 _, _ = w.Write(bodyBytes)
1037 },
1038 )
1039
1040 // validate!
1041 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1042
1043 assert.False(t, valid)
1044 assert.Len(t, errors, 1)
1045 assert.Equal(t, "POST / 200 operation response content type 'chicken/nuggets' does not exist", errors[0].Message)
1046 }
1047
1048 func TestValidateBody_InvalidSchemaMultiple(t *testing.T) {
1049 tb := newvalidateResponseTestBed(
1050 t,
1051 []byte(`openapi: 3.1.0
1052 paths:
1053 /burgers/createBurger:
1054 post:
1055 responses:
1056 '200':
1057 content:
1058 application/json:
1059 schema:
1060 type: array
1061 items:
1062 type: object
1063 required:
1064 - name
1065 properties:
1066 name:
1067 type: string
1068 patties:
1069 type: integer
1070 vegetarian:
1071 type: boolean`,
1072 ),
1073 )
1074
1075 req, res := tb.makeRequestWithReponse(
1076 t,
1077 http.MethodPost,
1078 "/burgers/createBurger",
1079 func(w http.ResponseWriter, r *http.Request) {
1080 bodyBytes, err := json.Marshal([]map[string]interface{}{
1081 {
1082 "patties": 1,
1083 "vegetarian": true,
1084 },
1085 {
1086 "name": "Quarter Pounder",
1087 "patties": true,
1088 "vegetarian": false,
1089 },
1090 {
1091 "name": "Big Mac",
1092 "patties": 2,
1093 "vegetarian": false,
1094 },
1095 })
1096
1097 require.NoError(t, err, "failed to marshal body")
1098
1099 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1100 w.WriteHeader(http.StatusOK)
1101 _, _ = w.Write(bodyBytes)
1102 },
1103 )
1104
1105 // validate!
1106 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1107
1108 assert.False(t, valid)
1109 assert.Len(t, errors, 1)
1110 assert.Len(t, errors[0].SchemaValidationErrors, 2)
1111 assert.Equal(t, "200 response body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
1112 }
1113
1114 func TestValidateBody_EmptyContentType_Valid(t *testing.T) {
1115 tb := newvalidateResponseTestBed(
1116 t,
1117 []byte(`openapi: "3.0.0"
1118 info:
1119 title: Healthcheck
1120 version: '0.1.0'
1121 paths:
1122 /health:
1123 get:
1124 responses:
1125 '200':
1126 description: pet response
1127 content: {}`,
1128 ),
1129 )
1130
1131 req, res := tb.makeRequestWithReponse(
1132 t,
1133 http.MethodGet,
1134 "/health",
1135 func(w http.ResponseWriter, r *http.Request) {
1136 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1137 w.WriteHeader(http.StatusOK)
1138 _, _ = w.Write(nil)
1139 },
1140 )
1141
1142 // validate!
1143 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1144
1145 assert.True(t, valid)
1146 assert.Len(t, errors, 0)
1147 }
1148
1149 func TestValidateBody_InvalidBodyJSON(t *testing.T) {
1150 tb := newvalidateResponseTestBed(
1151 t,
1152 []byte(`openapi: 3.1.0
1153 paths:
1154 /burgers/createBurger:
1155 post:
1156 responses:
1157 default:
1158 content:
1159 application/json:
1160 schema:
1161 type: object
1162 properties:
1163 name:
1164 type: string
1165 patties:
1166 type: integer
1167 vegetarian:
1168 type: boolean`,
1169 ),
1170 )
1171
1172 req, res := tb.makeRequestWithReponse(
1173 t,
1174 http.MethodPost,
1175 "/burgers/createBurger",
1176 func(w http.ResponseWriter, r *http.Request) {
1177 w.Header().Set(helpers.ContentTypeHeader, "application/json")
1178 w.WriteHeader(http.StatusOK)
1179 _, _ = w.Write([]byte("{\"bad\": \"json\",}"))
1180 },
1181 )
1182
1183 // validate!
1184 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1185
1186 assert.False(t, valid)
1187 assert.Len(t, errors, 1)
1188 assert.Equal(t, "POST response body for '/burgers/createBurger' failed to validate schema", errors[0].Message)
1189 assert.Nil(t, errors[0].SchemaValidationErrors)
1190 assert.Contains(t, errors[0].Reason, "cannot be decoded")
1191 }
1192
1193 func TestValidateBody_NoContentType_Valid(t *testing.T) {
1194 tb := newvalidateResponseTestBed(
1195 t,
1196 []byte(`openapi: "3.0.0"
1197 info:
1198 title: Healthcheck
1199 version: '0.1.0'
1200 paths:
1201 /health:
1202 get:
1203 responses:
1204 '200':
1205 description: pet response`,
1206 ),
1207 )
1208
1209 req, res := tb.makeRequestWithReponse(
1210 t,
1211 http.MethodGet,
1212 "/health",
1213 func(w http.ResponseWriter, r *http.Request) {
1214 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1215 w.WriteHeader(http.StatusOK)
1216 _, _ = w.Write(nil)
1217 },
1218 )
1219
1220 // validate!
1221 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1222
1223 assert.True(t, valid)
1224 assert.Len(t, errors, 0)
1225 }
1226
1227 // https://github.com/pb33f/libopenapi-validator/issues/107
1228 // https://github.com/pb33f/libopenapi-validator/issues/103
1229 func TestNewValidator_TestCircularRefsInValidation_Response(t *testing.T) {
1230 tb := newvalidateResponseTestBed(
1231 t,
1232 []byte(`openapi: 3.1.0
1233 info:
1234 title: Panic at response validation
1235 version: 1.0.0
1236 paths:
1237 /operations:
1238 delete:
1239 description: Delete operations
1240 responses:
1241 default:
1242 description: Any response
1243 content:
1244 application/json:
1245 schema:
1246 $ref: '#/components/schemas/Error'
1247
1248 components:
1249 schemas:
1250 Error:
1251 type: object
1252 properties:
1253 code:
1254 type: string
1255 details:
1256 type: array
1257 items:
1258 $ref: '#/components/schemas/Error'`,
1259 ),
1260 )
1261
1262 req, res := tb.makeRequestWithReponse(
1263 t,
1264 http.MethodDelete,
1265 "/operations",
1266 func(w http.ResponseWriter, r *http.Request) {
1267 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1268 w.WriteHeader(http.StatusOK)
1269 _, _ = w.Write(nil)
1270 },
1271 )
1272
1273 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1274
1275 assert.False(t, valid)
1276 assert.Len(t, errors, 1)
1277 // The error message may vary depending on whether the circular reference is caught
1278 // during rendering or compilation, so we check for either pattern
1279 assert.True(t,
1280 strings.Contains(errors[0].Reason, "circular reference") ||
1281 strings.Contains(errors[0].Reason, "json-pointer") ||
1282 strings.Contains(errors[0].Reason, "not found"),
1283 "Expected error about circular reference or JSON pointer not found, got: %s", errors[0].Reason)
1284 }
1285
1286 func TestValidateResponseBody_XMLMarshalError(t *testing.T) {
1287 tb := newvalidateResponseTestBed(
1288 t,
1289 []byte(`
1290 openapi: 3.1.0
1291 info:
1292 title: Test Spec
1293 version: 1.0.0
1294 paths:
1295 /test:
1296 get:
1297 responses:
1298 '200':
1299 description: Success
1300 content:
1301 application/xml:
1302 schema:
1303 type: object
1304 properties:
1305 bad_number:
1306 type: number
1307 `,
1308 ),
1309 )
1310
1311 req, res := tb.makeRequestWithReponse(
1312 t,
1313 http.MethodGet,
1314 "/test",
1315 func(w http.ResponseWriter, r *http.Request) {
1316 w.Header().Set(helpers.ContentTypeHeader, "application/xml")
1317 w.WriteHeader(http.StatusOK)
1318 _, _ = w.Write([]byte("<bad_number>NaN</bad_number>"))
1319 },
1320 )
1321
1322 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1323
1324 assert.False(t, valid)
1325 assert.Len(t, errors, 1)
1326 assert.Equal(t, errors[0].Message, "xml example is malformed")
1327 }
1328
1329 func TestValidateResponseBody_URLEncodedMarshalError(t *testing.T) {
1330 tb := newvalidateResponseTestBed(
1331 t,
1332 []byte(`
1333 openapi: 3.1.0
1334 info:
1335 title: Test Spec
1336 version: 1.0.0
1337 paths:
1338 /test:
1339 get:
1340 responses:
1341 '200':
1342 description: Success
1343 content:
1344 application/x-www-form-urlencoded:
1345 schema:
1346 type: object
1347 properties:
1348 bad_number:
1349 type: number
1350 `,
1351 ),
1352 )
1353
1354 req, res := tb.makeRequestWithReponse(
1355 t,
1356 http.MethodGet,
1357 "/test",
1358 func(w http.ResponseWriter, r *http.Request) {
1359 w.Header().Set(helpers.ContentTypeHeader, helpers.URLEncodedContentType)
1360 w.WriteHeader(http.StatusOK)
1361 _, _ = w.Write([]byte("bad_number=NaN"))
1362 },
1363 )
1364
1365 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1366
1367 assert.False(t, valid)
1368 assert.Len(t, errors, 1)
1369 assert.Equal(t, errors[0].Message, "Unable to parse form-urlencoded body")
1370 }
1371
1372 func TestValidateResponseBody_NilSchema(t *testing.T) {
1373 tb := newvalidateResponseTestBed(
1374 t,
1375 []byte(`
1376 openapi: 3.1.0
1377 info:
1378 title: Test Spec
1379 version: 1.0.0
1380 paths:
1381 /test:
1382 get:
1383 responses:
1384 '200':
1385 description: Success
1386 content:
1387 application/json: {}
1388 `,
1389 ),
1390 )
1391
1392 req, res := tb.makeRequestWithReponse(
1393 t,
1394 http.MethodGet,
1395 "/test",
1396 func(w http.ResponseWriter, r *http.Request) {
1397 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1398 w.WriteHeader(http.StatusOK)
1399 _, _ = w.Write(nil)
1400 },
1401 )
1402
1403 valid, errors := tb.responseBodyValidator.ValidateResponseBody(req, res)
1404
1405 assert.True(t, valid)
1406 assert.Len(t, errors, 0)
1407 }
1408
1409 func TestValidateBody_CheckHeader(t *testing.T) {
1410 spec := `openapi: "3.0.0"
1411 info:
1412 title: Healthcheck
1413 version: '0.1.0'
1414 paths:
1415 /health:
1416 get:
1417 responses:
1418 '200':
1419 headers:
1420 chicken-nuggets:
1421 description: chicken nuggets response
1422 required: true
1423 schema:
1424 type: integer
1425 description: pet response`
1426
1427 doc, _ := libopenapi.NewDocument([]byte(spec))
1428
1429 m, _ := doc.BuildV3Model()
1430 v := NewResponseBodyValidator(&m.Model)
1431
1432 // build a request
1433 request, _ := http.NewRequest(http.MethodGet, "https://things.com/health", nil)
1434
1435 // simulate a request/response
1436 res := httptest.NewRecorder()
1437 handler := func(w http.ResponseWriter, r *http.Request) {
1438 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1439 w.WriteHeader(http.StatusOK)
1440 _, _ = w.Write(nil)
1441 }
1442
1443 // fire the request
1444 handler(res, request)
1445
1446 // record response
1447 response := res.Result()
1448
1449 // validate!
1450 valid, errors := v.ValidateResponseBody(request, response)
1451
1452 assert.False(t, valid)
1453 assert.Len(t, errors, 1)
1454 assert.Equal(t, "Missing required header", errors[0].Message)
1455 assert.Equal(t, "Required header 'chicken-nuggets' was not found in response", errors[0].Reason)
1456 }
1457
1458 // TestValidateBody_ComplexRegexSchemaCompilationError tests that complex regex patterns
1459 // that cause schema compilation to fail are handled gracefully instead of causing panics
1460 func TestValidateBody_ComplexRegexSchemaCompilationError(t *testing.T) {
1461 spec := `openapi: 3.1.0
1462 paths:
1463 /burgers/createBurger:
1464 post:
1465 responses:
1466 '200':
1467 content:
1468 application/json:
1469 schema:
1470 type: object
1471 properties:
1472 name:
1473 type: string
1474 pattern: "[\\w\\W]{1,1024}$"
1475 patties:
1476 type: integer
1477 vegetarian:
1478 type: boolean`
1479
1480 doc, _ := libopenapi.NewDocument([]byte(spec))
1481
1482 m, _ := doc.BuildV3Model()
1483 v := NewResponseBodyValidator(&m.Model)
1484
1485 body := map[string]interface{}{
1486 "name": "Big Mac test",
1487 "patties": 2,
1488 "vegetarian": false,
1489 }
1490
1491 bodyBytes, _ := json.Marshal(body)
1492
1493 // build a request
1494 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader(bodyBytes))
1495 request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1496
1497 // simulate a request/response
1498 res := httptest.NewRecorder()
1499 handler := func(w http.ResponseWriter, r *http.Request) {
1500 w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1501 w.WriteHeader(http.StatusOK)
1502 _, _ = w.Write(bodyBytes)
1503 }
1504
1505 // fire the request
1506 handler(res, request)
1507
1508 // record response
1509 response := res.Result()
1510
1511 // validate - this should not panic even if schema compilation fails
1512 valid, validationErrors := v.ValidateResponseBody(request, response)
1513
1514 // if schema compilation failed due to complex regex, we should get a validation error instead of a panic
1515 if !valid {
1516 // verify we got a schema compilation error instead of a panic
1517 assert.NotEmpty(t, validationErrors)
1518 found := false
1519 for _, err := range validationErrors {
1520 if err.ValidationSubType == helpers.Schema &&
1521 len(err.SchemaValidationErrors) == 0 {
1522 // Schema compilation errors don't have SchemaValidationFailure objects
1523 if strings.Contains(err.Reason, "failed to compile JSON schema") {
1524 found = true
1525 assert.Contains(t, err.Reason, "failed to compile JSON schema")
1526 assert.Contains(t, err.HowToFix, "complex regex patterns")
1527 break
1528 }
1529 }
1530 }
1531 if !found {
1532 // if it didn't fail compilation, it should have succeeded
1533 t.Logf("Schema compilation succeeded, validation result: %v", valid)
1534 }
1535 } else {
1536 // schema compiled and validated successfully
1537 assert.True(t, valid)
1538 assert.Empty(t, validationErrors)
1539 }
1540 }
1541
1542 func TestValidateBody_StrictMode_UndeclaredProperty(t *testing.T) {
1543 spec := `openapi: 3.1.0
1544 paths:
1545 /burgers/getBurger:
1546 get:
1547 responses:
1548 '200':
1549 content:
1550 application/json:
1551 schema:
1552 type: object
1553 properties:
1554 name:
1555 type: string
1556 patties:
1557 type: integer`
1558
1559 doc, _ := libopenapi.NewDocument([]byte(spec))
1560
1561 m, _ := doc.BuildV3Model()
1562 v := NewResponseBodyValidator(&m.Model, config.WithStrictMode())
1563
1564 request, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers/getBurger", nil)
1565
1566 // Response with undeclared property 'extra'
1567 responseBody := `{"name": "Big Mac", "patties": 2, "extra": "undeclared"}`
1568 response := &http.Response{
1569 Header: http.Header{},
1570 StatusCode: http.StatusOK,
1571 Body: io.NopCloser(strings.NewReader(responseBody)),
1572 }
1573 response.Header.Set("Content-Type", "application/json")
1574
1575 valid, errs := v.ValidateResponseBody(request, response)
1576
1577 assert.False(t, valid)
1578 assert.Len(t, errs, 1)
1579 assert.Contains(t, errs[0].Message, "extra")
1580 assert.Contains(t, errs[0].Message, "not declared")
1581 }
1582
1583 func TestValidateBody_StrictMode_ValidResponse(t *testing.T) {
1584 spec := `openapi: 3.1.0
1585 paths:
1586 /burgers/getBurger:
1587 get:
1588 responses:
1589 '200':
1590 content:
1591 application/json:
1592 schema:
1593 type: object
1594 properties:
1595 name:
1596 type: string
1597 patties:
1598 type: integer`
1599
1600 doc, _ := libopenapi.NewDocument([]byte(spec))
1601
1602 m, _ := doc.BuildV3Model()
1603 v := NewResponseBodyValidator(&m.Model, config.WithStrictMode())
1604
1605 request, _ := http.NewRequest(http.MethodGet, "https://things.com/burgers/getBurger", nil)
1606
1607 // Response with only declared properties
1608 responseBody := `{"name": "Big Mac", "patties": 2}`
1609 response := &http.Response{
1610 Header: http.Header{},
1611 StatusCode: http.StatusOK,
1612 Body: io.NopCloser(strings.NewReader(responseBody)),
1613 }
1614 response.Header.Set("Content-Type", "application/json")
1615
1616 valid, errs := v.ValidateResponseBody(request, response)
1617
1618 assert.True(t, valid)
1619 assert.Len(t, errs, 0)
1620 }
1621
1622 func TestValidateBody_StrictMode_WriteOnlyProperty(t *testing.T) {
1623 spec := `openapi: 3.1.0
1624 paths:
1625 /users/123:
1626 get:
1627 responses:
1628 '200':
1629 content:
1630 application/json:
1631 schema:
1632 type: object
1633 properties:
1634 name:
1635 type: string
1636 password:
1637 type: string
1638 writeOnly: true`
1639
1640 doc, _ := libopenapi.NewDocument([]byte(spec))
1641
1642 m, _ := doc.BuildV3Model()
1643 v := NewResponseBodyValidator(&m.Model,
1644 config.WithStrictMode(),
1645 config.WithStrictRejectWriteOnly(),
1646 )
1647
1648 request, _ := http.NewRequest(http.MethodGet, "https://things.com/users/123", nil)
1649
1650 responseBody := `{"name": "John", "password": "secret"}`
1651 response := &http.Response{
1652 Header: http.Header{},
1653 StatusCode: http.StatusOK,
1654 Body: io.NopCloser(strings.NewReader(responseBody)),
1655 }
1656 response.Header.Set("Content-Type", "application/json")
1657
1658 valid, errs := v.ValidateResponseBody(request, response)
1659
1660 assert.False(t, valid)
1661 assert.Len(t, errs, 1)
1662 assert.Contains(t, errs[0].Message, "writeOnly")
1663 assert.Contains(t, errs[0].Message, "password")
1664 }
1665
1666 func TestValidateBody_ValidURLEncodedBody(t *testing.T) {
1667 spec := `openapi: 3.1.0
1668 paths:
1669 /burgers/createBurger:
1670 post:
1671 responses:
1672 default:
1673 content:
1674 application/x-www-form-urlencoded:
1675 schema:
1676 type: object
1677 properties:
1678 name:
1679 type: string
1680 patties:
1681 type: integer`
1682
1683 doc, _ := libopenapi.NewDocument([]byte(spec))
1684
1685 m, _ := doc.BuildV3Model()
1686 v := NewResponseBodyValidator(&m.Model, config.WithURLEncodedBodyValidation())
1687
1688 body := "name=test&patties=2"
1689
1690 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader([]byte(body)))
1691 request.Header.Set(helpers.ContentTypeHeader, helpers.URLEncodedContentType)
1692
1693 res := httptest.NewRecorder()
1694 handler := func(w http.ResponseWriter, r *http.Request) {
1695 w.Header().Set(helpers.ContentTypeHeader, helpers.URLEncodedContentType)
1696 w.WriteHeader(http.StatusOK)
1697 _, _ = w.Write([]byte(body))
1698 }
1699
1700 handler(res, request)
1701 response := res.Result()
1702
1703 valid, errors := v.ValidateResponseBody(request, response)
1704 assert.True(t, valid)
1705 assert.Len(t, errors, 0)
1706 }
1707
1708 func TestValidateBody_InvalidURLEncoded(t *testing.T) {
1709 spec := `openapi: 3.1.0
1710 paths:
1711 /burgers/createBurger:
1712 post:
1713 responses:
1714 default:
1715 content:
1716 application/x-www-form-urlencoded:
1717 schema:
1718 type: object
1719 properties:
1720 name:
1721 type: string
1722 patties:
1723 type: integer`
1724
1725 doc, _ := libopenapi.NewDocument([]byte(spec))
1726
1727 m, _ := doc.BuildV3Model()
1728 v := NewResponseBodyValidator(&m.Model, config.WithURLEncodedBodyValidation())
1729
1730 body := "name=test&patties=true"
1731
1732 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader([]byte(body)))
1733 request.Header.Set(helpers.ContentTypeHeader, helpers.URLEncodedContentType)
1734
1735 res := httptest.NewRecorder()
1736 handler := func(w http.ResponseWriter, r *http.Request) {
1737 w.Header().Set(helpers.ContentTypeHeader, helpers.URLEncodedContentType)
1738 w.WriteHeader(http.StatusOK)
1739 _, _ = w.Write([]byte(body))
1740 }
1741
1742 handler(res, request)
1743 response := res.Result()
1744
1745 valid, errors := v.ValidateResponseBody(request, response)
1746 assert.False(t, valid)
1747 assert.Len(t, errors, 1)
1748 }
1749
1750 func TestValidateBody_ValidXmlDecode(t *testing.T) {
1751 spec := `openapi: 3.1.0
1752 paths:
1753 /burgers/createBurger:
1754 post:
1755 responses:
1756 default:
1757 content:
1758 application/xml:
1759 schema:
1760 type: object
1761 properties:
1762 name:
1763 type: string
1764 patties:
1765 type: integer`
1766
1767 doc, _ := libopenapi.NewDocument([]byte(spec))
1768
1769 m, _ := doc.BuildV3Model()
1770 v := NewResponseBodyValidator(&m.Model, config.WithXmlBodyValidation())
1771
1772 body := "<name>test</name><patties>2</patties>"
1773
1774 // build a request
1775 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader([]byte(body)))
1776 request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1777
1778 // simulate a request/response
1779 res := httptest.NewRecorder()
1780 handler := func(w http.ResponseWriter, r *http.Request) {
1781 w.Header().Set(helpers.ContentTypeHeader, "application/xml")
1782 w.WriteHeader(http.StatusOK)
1783 _, _ = w.Write([]byte(body))
1784 }
1785
1786 // fire the request
1787 handler(res, request)
1788
1789 // record response
1790 response := res.Result()
1791
1792 // validate!
1793 valid, errors := v.ValidateResponseBody(request, response)
1794
1795 assert.True(t, valid)
1796 assert.Len(t, errors, 0)
1797 }
1798
1799 func TestValidateBody_ValidXmlFailedValidation(t *testing.T) {
1800 spec := `openapi: 3.1.0
1801 paths:
1802 /burgers/createBurger:
1803 post:
1804 responses:
1805 default:
1806 content:
1807 application/xml:
1808 schema:
1809 type: object
1810 properties:
1811 name:
1812 type: string
1813 patties:
1814 type: integer`
1815
1816 doc, _ := libopenapi.NewDocument([]byte(spec))
1817
1818 m, _ := doc.BuildV3Model()
1819 v := NewResponseBodyValidator(&m.Model, config.WithXmlBodyValidation())
1820
1821 body := "<name>20</name><patties>text</patties>"
1822
1823 // build a request
1824 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader([]byte(body)))
1825 request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1826
1827 // simulate a request/response
1828 res := httptest.NewRecorder()
1829 handler := func(w http.ResponseWriter, r *http.Request) {
1830 w.Header().Set(helpers.ContentTypeHeader, "application/xml")
1831 w.WriteHeader(http.StatusOK)
1832 _, _ = w.Write([]byte(body))
1833 }
1834
1835 // fire the request
1836 handler(res, request)
1837
1838 // record response
1839 response := res.Result()
1840
1841 // validate!
1842 valid, errors := v.ValidateResponseBody(request, response)
1843
1844 assert.False(t, valid)
1845 assert.Len(t, errors, 1)
1846 assert.Len(t, errors[0].SchemaValidationErrors, 1)
1847 }
1848
1849 func TestValidateBody_IgnoreXmlValidation(t *testing.T) {
1850 spec := `openapi: 3.1.0
1851 paths:
1852 /burgers/createBurger:
1853 post:
1854 responses:
1855 default:
1856 content:
1857 application/xml:
1858 schema:
1859 type: object
1860 properties:
1861 name:
1862 type: string
1863 patties:
1864 type: integer
1865 vegetarian:
1866 type: boolean`
1867
1868 doc, _ := libopenapi.NewDocument([]byte(spec))
1869
1870 m, _ := doc.BuildV3Model()
1871 v := NewResponseBodyValidator(&m.Model)
1872
1873 body := "invalidbodycausenoxml"
1874
1875 // build a request
1876 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader([]byte(body)))
1877 request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1878
1879 // simulate a request/response
1880 res := httptest.NewRecorder()
1881 handler := func(w http.ResponseWriter, r *http.Request) {
1882 w.Header().Set(helpers.ContentTypeHeader, "application/xml")
1883 w.WriteHeader(http.StatusOK)
1884 _, _ = w.Write([]byte(body))
1885 }
1886
1887 // fire the request
1888 handler(res, request)
1889
1890 // record response
1891 response := res.Result()
1892
1893 // validate!
1894 valid, errors := v.ValidateResponseBody(request, response)
1895
1896 assert.True(t, valid)
1897 assert.Len(t, errors, 0)
1898 }
1899
1900 func TestValidateBody_InvalidXmlParse(t *testing.T) {
1901 spec := `openapi: 3.1.0
1902 paths:
1903 /burgers/createBurger:
1904 post:
1905 responses:
1906 default:
1907 content:
1908 application/xml:
1909 schema:
1910 type: object
1911 properties:
1912 name:
1913 type: string
1914 patties:
1915 type: integer
1916 vegetarian:
1917 type: boolean`
1918
1919 doc, _ := libopenapi.NewDocument([]byte(spec))
1920
1921 m, _ := doc.BuildV3Model()
1922 v := NewResponseBodyValidator(&m.Model, config.WithXmlBodyValidation())
1923
1924 body := ""
1925
1926 // build a request
1927 request, _ := http.NewRequest(http.MethodPost, "https://things.com/burgers/createBurger", bytes.NewReader([]byte(body)))
1928 request.Header.Set(helpers.ContentTypeHeader, helpers.JSONContentType)
1929
1930 // simulate a request/response
1931 res := httptest.NewRecorder()
1932 handler := func(w http.ResponseWriter, r *http.Request) {
1933 w.Header().Set(helpers.ContentTypeHeader, "application/xml")
1934 w.WriteHeader(http.StatusOK)
1935 _, _ = w.Write([]byte(body))
1936 }
1937
1938 // fire the request
1939 handler(res, request)
1940
1941 // record response
1942 response := res.Result()
1943
1944 // validate!
1945 valid, errors := v.ValidateResponseBody(request, response)
1946
1947 assert.False(t, valid)
1948 assert.Len(t, errors, 1)
1949 assert.Equal(t, "xml example is malformed", errors[0].Message)
1950 }
1951
1952 func TestValidateResponseBodyWithPathItem_NilResponses(t *testing.T) {
1953 // Operation with nil Responses — should not panic (fix for wiretap #134)
1954 spec := []byte(`openapi: 3.1.0
1955 paths:
1956 /test:
1957 get:
1958 responses:
1959 '200':
1960 description: ok
1961 `)
1962 doc, err := libopenapi.NewDocument(spec)
1963 require.NoError(t, err)
1964 m, errs := doc.BuildV3Model()
1965 require.Empty(t, errs)
1966
1967 v := NewResponseBodyValidator(&m.Model)
1968
1969 request, _ := http.NewRequest(http.MethodGet, "/test", nil)
1970 response := &http.Response{
1971 StatusCode: 200,
1972 Header: http.Header{},
1973 Body: io.NopCloser(bytes.NewBufferString("")),
1974 }
1975
1976 // Should not panic even with no content in the response definition
1977 valid, validationErrors := v.ValidateResponseBodyWithPathItem(request, response,
1978 m.Model.Paths.PathItems.GetOrZero("/test"), "/test")
1979 assert.True(t, valid)
1980 assert.Empty(t, validationErrors)
1981 }
1982
1983 type errorReader struct{}
1984
1985 func (er *errorReader) Read(p []byte) (n int, err error) {
1986 return 0, errors.New("some io error")
1987 }
1988
1989 func (er *errorReader) Close() error {
1990 return nil
1991 }