Debian Codegraph @

strict/validator_test.go

raw
1 // Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package strict
5
6 import (
7 "context"
8 "log/slog"
9 "net/http"
10 "testing"
11
12 "github.com/pb33f/libopenapi"
13 "github.com/pb33f/libopenapi/datamodel/high/base"
14 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17
18 libcache "github.com/pb33f/libopenapi-validator/cache"
19 "github.com/pb33f/libopenapi-validator/config"
20 "github.com/pb33f/libopenapi-validator/helpers"
21 )
22
23 // Helper to build a schema from YAML
24 func buildSchemaFromYAML(t *testing.T, yml string) *libopenapi.DocumentModel[v3.Document] {
25 doc, err := libopenapi.NewDocument([]byte(yml))
26 require.NoError(t, err)
27 model, errs := doc.BuildV3Model()
28 require.Empty(t, errs)
29 return model
30 }
31
32 // Helper to get schema
33 func getSchema(t *testing.T, model *libopenapi.DocumentModel[v3.Document], name string) *base.Schema {
34 schemaProxy := model.Model.Components.Schemas.GetOrZero(name)
35 require.NotNil(t, schemaProxy)
36 schema := schemaProxy.Schema()
37 require.NotNil(t, schema)
38 return schema
39 }
40
41 func TestStrictValidator_SimpleUndeclaredProperty(t *testing.T) {
42 yml := `openapi: "3.1.0"
43 info:
44 title: Test
45 version: "1.0"
46 paths: {}
47 components:
48 schemas:
49 User:
50 type: object
51 properties:
52 name:
53 type: string
54 age:
55 type: integer
56 `
57 model := buildSchemaFromYAML(t, yml)
58 schema := getSchema(t, model, "User")
59
60 opts := config.NewValidationOptions(config.WithStrictMode())
61 v := NewValidator(opts, 3.1)
62
63 // Test with undeclared property
64 data := map[string]any{
65 "name": "John",
66 "age": 30,
67 "extra": "undeclared",
68 }
69
70 result := v.Validate(Input{
71 Schema: schema,
72 Data: data,
73 Direction: DirectionRequest,
74 Options: opts,
75 BasePath: "$.body",
76 Version: 3.1,
77 })
78
79 assert.False(t, result.Valid)
80 assert.Len(t, result.UndeclaredValues, 1)
81 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
82 assert.Equal(t, "$.body.extra", result.UndeclaredValues[0].Path)
83 }
84
85 func TestStrictValidator_AllPropertiesDeclared(t *testing.T) {
86 yml := `openapi: "3.1.0"
87 info:
88 title: Test
89 version: "1.0"
90 paths: {}
91 components:
92 schemas:
93 User:
94 type: object
95 properties:
96 name:
97 type: string
98 age:
99 type: integer
100 `
101 model := buildSchemaFromYAML(t, yml)
102 schema := getSchema(t, model, "User")
103
104 opts := config.NewValidationOptions(config.WithStrictMode())
105 v := NewValidator(opts, 3.1)
106
107 // Test with only declared properties
108 data := map[string]any{
109 "name": "John",
110 "age": 30,
111 }
112
113 result := v.Validate(Input{
114 Schema: schema,
115 Data: data,
116 Direction: DirectionRequest,
117 Options: opts,
118 BasePath: "$.body",
119 Version: 3.1,
120 })
121
122 assert.True(t, result.Valid)
123 assert.Empty(t, result.UndeclaredValues)
124 }
125
126 func TestStrictValidator_NestedObjects(t *testing.T) {
127 yml := `openapi: "3.1.0"
128 info:
129 title: Test
130 version: "1.0"
131 paths: {}
132 components:
133 schemas:
134 User:
135 type: object
136 properties:
137 name:
138 type: string
139 address:
140 type: object
141 properties:
142 street:
143 type: string
144 city:
145 type: string
146 `
147 model := buildSchemaFromYAML(t, yml)
148 schema := getSchema(t, model, "User")
149
150 opts := config.NewValidationOptions(config.WithStrictMode())
151 v := NewValidator(opts, 3.1)
152
153 // Test with undeclared nested property
154 data := map[string]any{
155 "name": "John",
156 "address": map[string]any{
157 "street": "123 Main St",
158 "city": "Anytown",
159 "zipcode": "12345", // undeclared
160 },
161 }
162
163 result := v.Validate(Input{
164 Schema: schema,
165 Data: data,
166 Direction: DirectionRequest,
167 Options: opts,
168 BasePath: "$.body",
169 Version: 3.1,
170 })
171
172 assert.False(t, result.Valid)
173 assert.Len(t, result.UndeclaredValues, 1)
174 assert.Equal(t, "zipcode", result.UndeclaredValues[0].Name)
175 assert.Equal(t, "$.body.address.zipcode", result.UndeclaredValues[0].Path)
176 }
177
178 func TestStrictValidator_ArrayOfObjects(t *testing.T) {
179 yml := `openapi: "3.1.0"
180 info:
181 title: Test
182 version: "1.0"
183 paths: {}
184 components:
185 schemas:
186 Users:
187 type: array
188 items:
189 type: object
190 properties:
191 name:
192 type: string
193 `
194 model := buildSchemaFromYAML(t, yml)
195 schema := getSchema(t, model, "Users")
196
197 opts := config.NewValidationOptions(config.WithStrictMode())
198 v := NewValidator(opts, 3.1)
199
200 // Test with undeclared property in array item
201 data := []any{
202 map[string]any{
203 "name": "John",
204 "extra": "undeclared",
205 },
206 }
207
208 result := v.Validate(Input{
209 Schema: schema,
210 Data: data,
211 Direction: DirectionRequest,
212 Options: opts,
213 BasePath: "$.body",
214 Version: 3.1,
215 })
216
217 assert.False(t, result.Valid)
218 assert.Len(t, result.UndeclaredValues, 1)
219 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
220 }
221
222 func TestStrictValidator_IgnorePaths(t *testing.T) {
223 yml := `openapi: "3.1.0"
224 info:
225 title: Test
226 version: "1.0"
227 paths: {}
228 components:
229 schemas:
230 User:
231 type: object
232 properties:
233 name:
234 type: string
235 `
236 model := buildSchemaFromYAML(t, yml)
237 schema := getSchema(t, model, "User")
238
239 opts := config.NewValidationOptions(
240 config.WithStrictMode(),
241 config.WithStrictIgnorePaths("$.body.metadata.*"),
242 )
243 v := NewValidator(opts, 3.1)
244
245 // Test that ignored path is not reported
246 data := map[string]any{
247 "name": "John",
248 "metadata": map[string]any{
249 "custom": "value", // Should be ignored
250 },
251 }
252
253 result := v.Validate(Input{
254 Schema: schema,
255 Data: data,
256 Direction: DirectionRequest,
257 Options: opts,
258 BasePath: "$.body",
259 Version: 3.1,
260 })
261
262 // metadata itself is undeclared, but its children should be ignored
263 assert.False(t, result.Valid)
264 assert.Len(t, result.UndeclaredValues, 1)
265 assert.Equal(t, "metadata", result.UndeclaredValues[0].Name)
266 }
267
268 func TestStrictValidator_AdditionalPropertiesFalse(t *testing.T) {
269 yml := `openapi: "3.1.0"
270 info:
271 title: Test
272 version: "1.0"
273 paths: {}
274 components:
275 schemas:
276 User:
277 type: object
278 additionalProperties: false
279 properties:
280 name:
281 type: string
282 `
283 model := buildSchemaFromYAML(t, yml)
284 schema := getSchema(t, model, "User")
285
286 opts := config.NewValidationOptions(config.WithStrictMode())
287 v := NewValidator(opts, 3.1)
288
289 // additionalProperties: false means base validation catches this
290 // strict mode should NOT report (would be redundant)
291 data := map[string]any{
292 "name": "John",
293 "extra": "undeclared",
294 }
295
296 result := v.Validate(Input{
297 Schema: schema,
298 Data: data,
299 Direction: DirectionRequest,
300 Options: opts,
301 BasePath: "$.body",
302 Version: 3.1,
303 })
304
305 // strict should NOT report this since additionalProperties: false
306 assert.True(t, result.Valid)
307 assert.Empty(t, result.UndeclaredValues)
308 }
309
310 func TestStrictValidator_AdditionalPropertiesWithSchema(t *testing.T) {
311 yml := `openapi: "3.1.0"
312 info:
313 title: Test
314 version: "1.0"
315 paths: {}
316 components:
317 schemas:
318 User:
319 type: object
320 properties:
321 name:
322 type: string
323 additionalProperties:
324 type: string
325 `
326 model := buildSchemaFromYAML(t, yml)
327 schema := getSchema(t, model, "User")
328
329 opts := config.NewValidationOptions(config.WithStrictMode())
330 v := NewValidator(opts, 3.1)
331
332 // additionalProperties with schema means extra properties are allowed
333 // but strict should still report them (they're not in explicit schema)
334 data := map[string]any{
335 "name": "John",
336 "extra": "valid string", // Matches additionalProperties schema
337 }
338
339 result := v.Validate(Input{
340 Schema: schema,
341 Data: data,
342 Direction: DirectionRequest,
343 Options: opts,
344 BasePath: "$.body",
345 Version: 3.1,
346 })
347
348 // strict should report "extra" as undeclared even though it's valid
349 assert.False(t, result.Valid)
350 assert.Len(t, result.UndeclaredValues, 1)
351 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
352 }
353
354 func TestStrictValidator_PatternProperties(t *testing.T) {
355 yml := `openapi: "3.1.0"
356 info:
357 title: Test
358 version: "1.0"
359 paths: {}
360 components:
361 schemas:
362 Config:
363 type: object
364 properties:
365 name:
366 type: string
367 patternProperties:
368 "^x-.*$":
369 type: string
370 `
371 model := buildSchemaFromYAML(t, yml)
372 schema := getSchema(t, model, "Config")
373
374 opts := config.NewValidationOptions(config.WithStrictMode())
375 v := NewValidator(opts, 3.1)
376
377 // Properties matching patternProperties should be considered declared
378 data := map[string]any{
379 "name": "myconfig",
380 "x-custom": "extension value",
381 }
382
383 result := v.Validate(Input{
384 Schema: schema,
385 Data: data,
386 Direction: DirectionRequest,
387 Options: opts,
388 BasePath: "$.body",
389 Version: 3.1,
390 })
391
392 // x-custom matches the pattern, so it should be considered declared
393 assert.True(t, result.Valid)
394 assert.Empty(t, result.UndeclaredValues)
395 }
396
397 func TestBuildPath(t *testing.T) {
398 tests := []struct {
399 base string
400 propName string
401 expected string
402 }{
403 {"$.body", "name", "$.body.name"},
404 {"$.body", "a.b", "$.body['a.b']"},
405 {"$.body", "x[0]", "$.body['x[0]']"},
406 {"$.body.user", "email", "$.body.user.email"},
407 }
408
409 for _, tt := range tests {
410 t.Run(tt.propName, func(t *testing.T) {
411 result := buildPath(tt.base, tt.propName)
412 assert.Equal(t, tt.expected, result)
413 })
414 }
415 }
416
417 func TestCompilePattern(t *testing.T) {
418 tests := []struct {
419 pattern string
420 input string
421 matches bool
422 }{
423 // Single segment wildcard
424 {"$.body.metadata.*", "$.body.metadata.custom", true},
425 {"$.body.metadata.*", "$.body.metadata.custom.nested", false},
426
427 // Double wildcard (any depth)
428 {"$.body.**", "$.body.a.b.c", true},
429 {"$.body.**.x-*", "$.body.deep.nested.x-custom", true},
430
431 // Array index wildcard
432 {"$.body.items[*].name", "$.body.items[0].name", true},
433 {"$.body.items[*].name", "$.body.items[999].name", true},
434
435 // Escaped asterisk
436 {"$.body.\\*", "$.body.*", true},
437 {"$.body.\\*", "$.body.anything", false},
438 }
439
440 for _, tt := range tests {
441 t.Run(tt.pattern, func(t *testing.T) {
442 re := compilePattern(tt.pattern)
443 if re == nil {
444 t.Fatalf("Failed to compile pattern: %s", tt.pattern)
445 }
446 result := re.MatchString(tt.input)
447 assert.Equal(t, tt.matches, result, "Pattern: %s, Input: %s", tt.pattern, tt.input)
448 })
449 }
450 }
451
452 func TestDirection_String(t *testing.T) {
453 assert.Equal(t, "request", DirectionRequest.String())
454 assert.Equal(t, "response", DirectionResponse.String())
455 }
456
457 func TestIsHeaderIgnored(t *testing.T) {
458 opts := config.NewValidationOptions(config.WithStrictMode())
459 v := NewValidator(opts, 3.1)
460
461 // Standard headers should be ignored
462 assert.True(t, v.isHeaderIgnored("Content-Type", DirectionRequest))
463 assert.True(t, v.isHeaderIgnored("content-type", DirectionRequest))
464 assert.True(t, v.isHeaderIgnored("Authorization", DirectionRequest))
465
466 // Set-Cookie is direction-aware
467 assert.True(t, v.isHeaderIgnored("Set-Cookie", DirectionResponse))
468 assert.False(t, v.isHeaderIgnored("Set-Cookie", DirectionRequest))
469
470 // Custom headers should not be ignored
471 assert.False(t, v.isHeaderIgnored("X-Custom-Header", DirectionRequest))
472 }
473
474 func TestWithStrictIgnoredHeaders(t *testing.T) {
475 // Replace defaults entirely
476 opts := config.NewValidationOptions(
477 config.WithStrictMode(),
478 config.WithStrictIgnoredHeaders("X-Only-This"),
479 )
480 v := NewValidator(opts, 3.1)
481
482 // Standard headers are NOT ignored anymore
483 assert.False(t, v.isHeaderIgnored("Content-Type", DirectionRequest))
484
485 // Only our custom header is ignored
486 assert.True(t, v.isHeaderIgnored("X-Only-This", DirectionRequest))
487 }
488
489 func TestWithStrictIgnoredHeadersExtra(t *testing.T) {
490 // Add to defaults
491 opts := config.NewValidationOptions(
492 config.WithStrictMode(),
493 config.WithStrictIgnoredHeadersExtra("X-Custom-Extra"),
494 )
495 v := NewValidator(opts, 3.1)
496
497 // Standard headers are still ignored
498 assert.True(t, v.isHeaderIgnored("Content-Type", DirectionRequest))
499
500 // Our custom header is also ignored
501 assert.True(t, v.isHeaderIgnored("X-Custom-Extra", DirectionRequest))
502 }
503
504 func TestTruncateValue(t *testing.T) {
505 // Short string unchanged
506 assert.Equal(t, "hello", truncateValue("hello"))
507
508 // Long string truncated
509 longStr := "this is a very long string that should be truncated"
510 result := truncateValue(longStr).(string)
511 assert.True(t, len(result) <= 50)
512 assert.Contains(t, result, "...")
513
514 // Map truncated
515 bigMap := map[string]any{"a": 1, "b": 2, "c": 3, "d": 4}
516 assert.Equal(t, "{...}", truncateValue(bigMap))
517
518 // Slice truncated
519 bigSlice := []any{1, 2, 3, 4}
520 assert.Equal(t, "[...]", truncateValue(bigSlice))
521 }
522
523 func TestStrictValidator_PolymorphicPatternProperties(t *testing.T) {
524 yml := `openapi: "3.1.0"
525 info:
526 title: Edge
527 version: "1.0"
528 paths: {}
529 components:
530 schemas:
531 VariantA:
532 type: object
533 required:
534 - kind
535 properties:
536 kind:
537 type: string
538 aProp:
539 type: string
540 Root:
541 type: object
542 discriminator:
543 propertyName: kind
544 oneOf:
545 - $ref: "#/components/schemas/VariantA"
546 patternProperties:
547 "^x-.*$":
548 type: object
549 properties:
550 id:
551 type: string
552 `
553 model := buildSchemaFromYAML(t, yml)
554 schema := getSchema(t, model, "Root")
555
556 opts := config.NewValidationOptions(config.WithStrictMode())
557 v := NewValidator(opts, 3.1)
558
559 data := map[string]any{
560 "kind": "VariantA",
561 "aProp": "ok",
562 "x-foo": map[string]any{
563 "id": "1",
564 "extra": "nope",
565 },
566 }
567
568 result := v.Validate(Input{
569 Schema: schema,
570 Data: data,
571 Direction: DirectionRequest,
572 Options: opts,
573 BasePath: "$.body",
574 Version: 3.1,
575 })
576
577 require.False(t, result.Valid)
578 require.Len(t, result.UndeclaredValues, 1)
579 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
580 assert.Equal(t, "$.body.x-foo.extra", result.UndeclaredValues[0].Path)
581 }
582
583 func TestStrictValidator_ReusedSchemaDifferentPaths(t *testing.T) {
584 yml := `openapi: "3.1.0"
585 info:
586 title: Edge
587 version: "1.0"
588 paths: {}
589 components:
590 schemas:
591 Node:
592 type: object
593 properties:
594 id:
595 type: string
596 Root:
597 type: object
598 properties:
599 left:
600 $ref: "#/components/schemas/Node"
601 right:
602 $ref: "#/components/schemas/Node"
603 `
604 model := buildSchemaFromYAML(t, yml)
605 schema := getSchema(t, model, "Root")
606
607 opts := config.NewValidationOptions(config.WithStrictMode())
608 v := NewValidator(opts, 3.1)
609
610 data := map[string]any{
611 "left": map[string]any{
612 "id": "1",
613 "extra": "nope",
614 },
615 "right": map[string]any{
616 "id": "2",
617 "extra": "nope",
618 },
619 }
620
621 result := v.Validate(Input{
622 Schema: schema,
623 Data: data,
624 Direction: DirectionRequest,
625 Options: opts,
626 BasePath: "$.body",
627 Version: 3.1,
628 })
629
630 require.False(t, result.Valid)
631 assert.Len(t, result.UndeclaredValues, 2)
632 }
633
634 func TestStrictValidator_UnevaluatedItemsOnly(t *testing.T) {
635 yml := `openapi: "3.1.0"
636 info:
637 title: Edge
638 version: "1.0"
639 paths: {}
640 components:
641 schemas:
642 Items:
643 type: array
644 unevaluatedItems:
645 type: object
646 properties:
647 id:
648 type: string
649 `
650 model := buildSchemaFromYAML(t, yml)
651 schema := getSchema(t, model, "Items")
652
653 opts := config.NewValidationOptions(config.WithStrictMode())
654 v := NewValidator(opts, 3.1)
655
656 data := []any{
657 map[string]any{
658 "id": "1",
659 "extra": "nope",
660 },
661 }
662
663 result := v.Validate(Input{
664 Schema: schema,
665 Data: data,
666 Direction: DirectionRequest,
667 Options: opts,
668 BasePath: "$.body",
669 Version: 3.1,
670 })
671
672 require.False(t, result.Valid)
673 require.Len(t, result.UndeclaredValues, 1)
674 assert.Equal(t, "$.body[0].extra", result.UndeclaredValues[0].Path)
675 }
676
677 func TestStrictValidator_HeaderIgnorePathsCase(t *testing.T) {
678 opts := config.NewValidationOptions(
679 config.WithStrictMode(),
680 config.WithStrictIgnorePaths("$.headers.x-trace"),
681 )
682
683 headers := http.Header{
684 "X-Trace": {"abc"},
685 }
686
687 undeclared := ValidateRequestHeaders(headers, nil, nil, opts)
688 assert.Empty(t, undeclared)
689 }
690
691 func TestStrictValidator_OneOfWithParentProperties(t *testing.T) {
692 yml := `openapi: "3.1.0"
693 info:
694 title: Test
695 version: "1.0"
696 paths: {}
697 components:
698 schemas:
699 User:
700 type: object
701 properties:
702 id:
703 type: string
704 oneOf:
705 - properties:
706 name:
707 type: string
708 - properties:
709 title:
710 type: string
711 `
712 model := buildSchemaFromYAML(t, yml)
713 schema := getSchema(t, model, "User")
714
715 opts := config.NewValidationOptions(config.WithStrictMode())
716 v := NewValidator(opts, 3.1)
717
718 // Test with parent property "id" + oneOf variant property "name"
719 // Both should be considered declared
720 data := map[string]any{
721 "id": "123",
722 "name": "John",
723 }
724
725 result := v.Validate(Input{
726 Schema: schema,
727 Data: data,
728 Direction: DirectionRequest,
729 Options: opts,
730 BasePath: "$.body",
731 Version: 3.1,
732 })
733
734 // id is from parent, name is from oneOf variant - both should be declared
735 assert.True(t, result.Valid, "Parent + oneOf variant properties should be valid")
736 assert.Empty(t, result.UndeclaredValues)
737 }
738
739 func TestStrictValidator_AnyOfWithParentProperties(t *testing.T) {
740 yml := `openapi: "3.1.0"
741 info:
742 title: Test
743 version: "1.0"
744 paths: {}
745 components:
746 schemas:
747 User:
748 type: object
749 properties:
750 id:
751 type: string
752 anyOf:
753 - properties:
754 name:
755 type: string
756 - properties:
757 title:
758 type: string
759 `
760 model := buildSchemaFromYAML(t, yml)
761 schema := getSchema(t, model, "User")
762
763 opts := config.NewValidationOptions(config.WithStrictMode())
764 v := NewValidator(opts, 3.1)
765
766 // Test with parent property "id" + anyOf variant property "name"
767 data := map[string]any{
768 "id": "123",
769 "name": "John",
770 }
771
772 result := v.Validate(Input{
773 Schema: schema,
774 Data: data,
775 Direction: DirectionRequest,
776 Options: opts,
777 BasePath: "$.body",
778 Version: 3.1,
779 })
780
781 // id is from parent, name is from anyOf variant - both should be declared
782 assert.True(t, result.Valid, "Parent + anyOf variant properties should be valid")
783 assert.Empty(t, result.UndeclaredValues)
784 }
785
786 func TestStrictValidator_OneOfWithUndeclaredProperty(t *testing.T) {
787 yml := `openapi: "3.1.0"
788 info:
789 title: Test
790 version: "1.0"
791 paths: {}
792 components:
793 schemas:
794 User:
795 type: object
796 properties:
797 id:
798 type: string
799 oneOf:
800 - properties:
801 name:
802 type: string
803 - properties:
804 title:
805 type: string
806 `
807 model := buildSchemaFromYAML(t, yml)
808 schema := getSchema(t, model, "User")
809
810 opts := config.NewValidationOptions(config.WithStrictMode())
811 v := NewValidator(opts, 3.1)
812
813 // Test with undeclared property "extra"
814 data := map[string]any{
815 "id": "123",
816 "name": "John",
817 "extra": "undeclared",
818 }
819
820 result := v.Validate(Input{
821 Schema: schema,
822 Data: data,
823 Direction: DirectionRequest,
824 Options: opts,
825 BasePath: "$.body",
826 Version: 3.1,
827 })
828
829 // "extra" is not in parent or variant - should be reported as undeclared
830 assert.False(t, result.Valid)
831 assert.Len(t, result.UndeclaredValues, 1)
832 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
833 }
834
835 func TestStrictValidator_PatternPropertiesWithAdditionalPropertiesFalse(t *testing.T) {
836 // This tests that patternProperties are recursed into even when
837 // additionalProperties: false (which short-circuits to recurseIntoDeclaredProperties)
838 yml := `openapi: "3.1.0"
839 info:
840 title: Test
841 version: "1.0"
842 paths: {}
843 components:
844 schemas:
845 Config:
846 type: object
847 additionalProperties: false
848 properties:
849 name:
850 type: string
851 patternProperties:
852 "^x-":
853 type: object
854 properties:
855 id:
856 type: string
857 `
858 model := buildSchemaFromYAML(t, yml)
859 schema := getSchema(t, model, "Config")
860
861 opts := config.NewValidationOptions(config.WithStrictMode())
862 v := NewValidator(opts, 3.1)
863
864 // Test with pattern property that has undeclared nested property
865 data := map[string]any{
866 "name": "test",
867 "x-custom": map[string]any{
868 "id": "123",
869 "extra": "undeclared nested field",
870 },
871 }
872
873 result := v.Validate(Input{
874 Schema: schema,
875 Data: data,
876 Direction: DirectionRequest,
877 Options: opts,
878 BasePath: "$.body",
879 Version: 3.1,
880 })
881
882 // "extra" inside x-custom should be reported as undeclared
883 // This verifies patternProperties are recursed into even with additionalProperties: false
884 assert.False(t, result.Valid, "Should report undeclared nested property in patternProperties")
885 assert.Len(t, result.UndeclaredValues, 1)
886 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
887 assert.Equal(t, "$.body.x-custom.extra", result.UndeclaredValues[0].Path)
888 }
889
890 func TestStrictValidator_PatternPropertiesInOneOf(t *testing.T) {
891 // This tests that patternProperties in oneOf/anyOf variants are recursed into
892 // to find undeclared properties in nested objects.
893 yml := `openapi: "3.1.0"
894 info:
895 title: Test
896 version: "1.0"
897 paths: {}
898 components:
899 schemas:
900 Container:
901 type: object
902 properties:
903 type:
904 type: string
905 oneOf:
906 - properties:
907 type:
908 const: "dynamic"
909 patternProperties:
910 "^x-":
911 type: object
912 properties:
913 value:
914 type: string
915 `
916 model := buildSchemaFromYAML(t, yml)
917 schema := getSchema(t, model, "Container")
918
919 opts := config.NewValidationOptions(config.WithStrictMode())
920 v := NewValidator(opts, 3.1)
921
922 // Test with undeclared property inside pattern-matched nested object
923 data := map[string]any{
924 "type": "dynamic",
925 "x-custom": map[string]any{
926 "value": "hello",
927 "undeclared": "should be caught",
928 },
929 }
930
931 result := v.Validate(Input{
932 Schema: schema,
933 Data: data,
934 Direction: DirectionRequest,
935 Options: opts,
936 BasePath: "$.body",
937 Version: 3.1,
938 })
939
940 // "undeclared" inside x-custom should be reported
941 assert.False(t, result.Valid, "Should report undeclared property in pattern-matched object")
942 require.Len(t, result.UndeclaredValues, 1)
943 assert.Equal(t, "undeclared", result.UndeclaredValues[0].Name)
944 assert.Equal(t, "$.body.x-custom.undeclared", result.UndeclaredValues[0].Path)
945 }
946
947 func TestStrictValidator_CycleDetection(t *testing.T) {
948 // This tests that circular schema references don't cause infinite recursion.
949 // The cycle detection should stop validation of the same schema at the same path.
950 yml := `openapi: "3.1.0"
951 info:
952 title: Test
953 version: "1.0"
954 paths: {}
955 components:
956 schemas:
957 Node:
958 type: object
959 properties:
960 name:
961 type: string
962 child:
963 $ref: "#/components/schemas/Node"
964 `
965 model := buildSchemaFromYAML(t, yml)
966 schema := getSchema(t, model, "Node")
967
968 opts := config.NewValidationOptions(config.WithStrictMode())
969 v := NewValidator(opts, 3.1)
970
971 // Test with deeply nested data that reuses the same schema
972 data := map[string]any{
973 "name": "root",
974 "child": map[string]any{
975 "name": "level1",
976 "child": map[string]any{
977 "name": "level2",
978 "extra": "undeclared at level2",
979 },
980 },
981 "extra": "undeclared at root",
982 }
983
984 result := v.Validate(Input{
985 Schema: schema,
986 Data: data,
987 Direction: DirectionRequest,
988 Options: opts,
989 BasePath: "$.body",
990 Version: 3.1,
991 })
992
993 // Should find undeclared properties at multiple levels
994 assert.False(t, result.Valid)
995 assert.GreaterOrEqual(t, len(result.UndeclaredValues), 2, "Should find undeclared at multiple levels")
996
997 // Verify both undeclared properties were found
998 var foundRoot, foundLevel2 bool
999 for _, u := range result.UndeclaredValues {
1000 if u.Path == "$.body.extra" {
1001 foundRoot = true
1002 }
1003 if u.Path == "$.body.child.child.extra" {
1004 foundLevel2 = true
1005 }
1006 }
1007 assert.True(t, foundRoot, "Should find undeclared at root level")
1008 assert.True(t, foundLevel2, "Should find undeclared at nested level")
1009 }
1010
1011 func TestStrictValidator_CycleDetectionDoesNotBlockDifferentPaths(t *testing.T) {
1012 // Tests that the same schema can be validated at different paths.
1013 // Cycle detection uses path+schemaRef, so same schema at different paths should work.
1014 yml := `openapi: "3.1.0"
1015 info:
1016 title: Test
1017 version: "1.0"
1018 paths: {}
1019 components:
1020 schemas:
1021 Container:
1022 type: object
1023 properties:
1024 left:
1025 $ref: "#/components/schemas/Item"
1026 right:
1027 $ref: "#/components/schemas/Item"
1028 Item:
1029 type: object
1030 properties:
1031 id:
1032 type: string
1033 `
1034 model := buildSchemaFromYAML(t, yml)
1035 schema := getSchema(t, model, "Container")
1036
1037 opts := config.NewValidationOptions(config.WithStrictMode())
1038 v := NewValidator(opts, 3.1)
1039
1040 // Test with undeclared properties in both left and right
1041 data := map[string]any{
1042 "left": map[string]any{
1043 "id": "1",
1044 "extraLeft": "undeclared in left",
1045 },
1046 "right": map[string]any{
1047 "id": "2",
1048 "extraRight": "undeclared in right",
1049 },
1050 }
1051
1052 result := v.Validate(Input{
1053 Schema: schema,
1054 Data: data,
1055 Direction: DirectionRequest,
1056 Options: opts,
1057 BasePath: "$.body",
1058 Version: 3.1,
1059 })
1060
1061 // Should find undeclared in both left and right
1062 assert.False(t, result.Valid)
1063 assert.Len(t, result.UndeclaredValues, 2, "Should find undeclared in both branches")
1064
1065 var foundLeft, foundRight bool
1066 for _, u := range result.UndeclaredValues {
1067 if u.Name == "extraLeft" {
1068 foundLeft = true
1069 }
1070 if u.Name == "extraRight" {
1071 foundRight = true
1072 }
1073 }
1074 assert.True(t, foundLeft, "Should find undeclared in left branch")
1075 assert.True(t, foundRight, "Should find undeclared in right branch")
1076 }
1077
1078 func TestValidateBody_UndeclaredProperty(t *testing.T) {
1079 yml := `openapi: "3.1.0"
1080 info:
1081 title: Test
1082 version: "1.0"
1083 paths: {}
1084 components:
1085 schemas:
1086 User:
1087 type: object
1088 properties:
1089 name:
1090 type: string
1091 age:
1092 type: integer
1093 `
1094 model := buildSchemaFromYAML(t, yml)
1095 schema := getSchema(t, model, "User")
1096
1097 opts := config.NewValidationOptions(config.WithStrictMode())
1098
1099 data := map[string]any{
1100 "name": "John",
1101 "age": 30,
1102 "extra": "undeclared",
1103 }
1104
1105 result := ValidateBody(schema, data, DirectionRequest, opts, 3.1)
1106
1107 assert.False(t, result.Valid)
1108 assert.Len(t, result.UndeclaredValues, 1)
1109 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
1110 assert.Equal(t, "$.body.extra", result.UndeclaredValues[0].Path)
1111 }
1112
1113 func TestValidateBody_AllPropertiesDeclared(t *testing.T) {
1114 yml := `openapi: "3.1.0"
1115 info:
1116 title: Test
1117 version: "1.0"
1118 paths: {}
1119 components:
1120 schemas:
1121 User:
1122 type: object
1123 properties:
1124 name:
1125 type: string
1126 age:
1127 type: integer
1128 `
1129 model := buildSchemaFromYAML(t, yml)
1130 schema := getSchema(t, model, "User")
1131
1132 opts := config.NewValidationOptions(config.WithStrictMode())
1133
1134 data := map[string]any{
1135 "name": "John",
1136 "age": 30,
1137 }
1138
1139 result := ValidateBody(schema, data, DirectionResponse, opts, 3.1)
1140
1141 assert.True(t, result.Valid)
1142 assert.Empty(t, result.UndeclaredValues)
1143 }
1144
1145 func TestValidateBody_NilInputs(t *testing.T) {
1146 opts := config.NewValidationOptions(config.WithStrictMode())
1147
1148 // nil schema
1149 result := ValidateBody(nil, map[string]any{"foo": "bar"}, DirectionRequest, opts, 3.1)
1150 assert.True(t, result.Valid)
1151
1152 // nil data
1153 yml := `openapi: "3.1.0"
1154 info:
1155 title: Test
1156 version: "1.0"
1157 paths: {}
1158 components:
1159 schemas:
1160 User:
1161 type: object
1162 properties:
1163 name:
1164 type: string
1165 `
1166 model := buildSchemaFromYAML(t, yml)
1167 schema := getSchema(t, model, "User")
1168
1169 result = ValidateBody(schema, nil, DirectionRequest, opts, 3.1)
1170 assert.True(t, result.Valid)
1171 }
1172
1173 // ============== allOf tests ==============
1174
1175 func TestStrictValidator_AllOf_Simple(t *testing.T) {
1176 yml := `openapi: "3.1.0"
1177 info:
1178 title: Test
1179 version: "1.0"
1180 paths: {}
1181 components:
1182 schemas:
1183 Base:
1184 type: object
1185 properties:
1186 id:
1187 type: string
1188 Extended:
1189 allOf:
1190 - $ref: "#/components/schemas/Base"
1191 - type: object
1192 properties:
1193 name:
1194 type: string
1195 `
1196 model := buildSchemaFromYAML(t, yml)
1197 schema := getSchema(t, model, "Extended")
1198
1199 opts := config.NewValidationOptions(config.WithStrictMode())
1200 v := NewValidator(opts, 3.1)
1201
1202 // Both id (from Base) and name (from inline) should be declared
1203 data := map[string]any{
1204 "id": "123",
1205 "name": "Test",
1206 }
1207
1208 result := v.Validate(Input{
1209 Schema: schema,
1210 Data: data,
1211 Direction: DirectionRequest,
1212 Options: opts,
1213 BasePath: "$.body",
1214 Version: 3.1,
1215 })
1216
1217 assert.True(t, result.Valid)
1218 assert.Empty(t, result.UndeclaredValues)
1219 }
1220
1221 func TestStrictValidator_AllOf_WithUndeclared(t *testing.T) {
1222 yml := `openapi: "3.1.0"
1223 info:
1224 title: Test
1225 version: "1.0"
1226 paths: {}
1227 components:
1228 schemas:
1229 Base:
1230 type: object
1231 properties:
1232 id:
1233 type: string
1234 Extended:
1235 allOf:
1236 - $ref: "#/components/schemas/Base"
1237 - type: object
1238 properties:
1239 name:
1240 type: string
1241 `
1242 model := buildSchemaFromYAML(t, yml)
1243 schema := getSchema(t, model, "Extended")
1244
1245 opts := config.NewValidationOptions(config.WithStrictMode())
1246 v := NewValidator(opts, 3.1)
1247
1248 // extra is not in any allOf schema
1249 data := map[string]any{
1250 "id": "123",
1251 "name": "Test",
1252 "extra": "undeclared",
1253 }
1254
1255 result := v.Validate(Input{
1256 Schema: schema,
1257 Data: data,
1258 Direction: DirectionRequest,
1259 Options: opts,
1260 BasePath: "$.body",
1261 Version: 3.1,
1262 })
1263
1264 assert.False(t, result.Valid)
1265 assert.Len(t, result.UndeclaredValues, 1)
1266 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
1267 }
1268
1269 func TestStrictValidator_AllOf_WithAdditionalPropertiesFalse(t *testing.T) {
1270 yml := `openapi: "3.1.0"
1271 info:
1272 title: Test
1273 version: "1.0"
1274 paths: {}
1275 components:
1276 schemas:
1277 Extended:
1278 allOf:
1279 - type: object
1280 additionalProperties: false
1281 properties:
1282 id:
1283 type: string
1284 - type: object
1285 properties:
1286 name:
1287 type: string
1288 `
1289 model := buildSchemaFromYAML(t, yml)
1290 schema := getSchema(t, model, "Extended")
1291
1292 opts := config.NewValidationOptions(config.WithStrictMode())
1293 v := NewValidator(opts, 3.1)
1294
1295 // When any allOf has additionalProperties: false, skip strict
1296 data := map[string]any{
1297 "id": "123",
1298 "name": "Test",
1299 "extra": "would normally be undeclared",
1300 }
1301
1302 result := v.Validate(Input{
1303 Schema: schema,
1304 Data: data,
1305 Direction: DirectionRequest,
1306 Options: opts,
1307 BasePath: "$.body",
1308 Version: 3.1,
1309 })
1310
1311 // additionalProperties: false means base validation handles this
1312 assert.True(t, result.Valid)
1313 }
1314
1315 func TestStrictValidator_AllOf_WithNestedObjects(t *testing.T) {
1316 yml := `openapi: "3.1.0"
1317 info:
1318 title: Test
1319 version: "1.0"
1320 paths: {}
1321 components:
1322 schemas:
1323 Address:
1324 type: object
1325 properties:
1326 street:
1327 type: string
1328 Extended:
1329 allOf:
1330 - type: object
1331 properties:
1332 id:
1333 type: string
1334 - type: object
1335 properties:
1336 address:
1337 $ref: "#/components/schemas/Address"
1338 `
1339 model := buildSchemaFromYAML(t, yml)
1340 schema := getSchema(t, model, "Extended")
1341
1342 opts := config.NewValidationOptions(config.WithStrictMode())
1343 v := NewValidator(opts, 3.1)
1344
1345 // Undeclared nested property in address
1346 data := map[string]any{
1347 "id": "123",
1348 "address": map[string]any{
1349 "street": "Main St",
1350 "zipcode": "12345", // undeclared in Address
1351 },
1352 }
1353
1354 result := v.Validate(Input{
1355 Schema: schema,
1356 Data: data,
1357 Direction: DirectionRequest,
1358 Options: opts,
1359 BasePath: "$.body",
1360 Version: 3.1,
1361 })
1362
1363 assert.False(t, result.Valid)
1364 assert.Len(t, result.UndeclaredValues, 1)
1365 assert.Equal(t, "zipcode", result.UndeclaredValues[0].Name)
1366 assert.Equal(t, "$.body.address.zipcode", result.UndeclaredValues[0].Path)
1367 }
1368
1369 // ============== Parameter validation tests ==============
1370
1371 func TestValidateQueryParams_Basic(t *testing.T) {
1372 opts := config.NewValidationOptions(config.WithStrictMode())
1373
1374 params := []*v3.Parameter{
1375 {Name: "limit", In: "query"},
1376 {Name: "offset", In: "query"},
1377 }
1378
1379 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test?limit=10&offset=0&extra=undeclared", nil)
1380
1381 undeclared := ValidateQueryParams(req, params, opts)
1382
1383 assert.Len(t, undeclared, 1)
1384 assert.Equal(t, "extra", undeclared[0].Name)
1385 assert.Equal(t, "$.query.extra", undeclared[0].Path)
1386 assert.Equal(t, "query", undeclared[0].Type)
1387 }
1388
1389 func TestValidateQueryParams_AllDeclared(t *testing.T) {
1390 opts := config.NewValidationOptions(config.WithStrictMode())
1391
1392 params := []*v3.Parameter{
1393 {Name: "limit", In: "query"},
1394 {Name: "offset", In: "query"},
1395 }
1396
1397 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test?limit=10&offset=0", nil)
1398
1399 undeclared := ValidateQueryParams(req, params, opts)
1400
1401 assert.Empty(t, undeclared)
1402 }
1403
1404 func TestValidateQueryParams_IgnorePaths(t *testing.T) {
1405 opts := config.NewValidationOptions(
1406 config.WithStrictMode(),
1407 config.WithStrictIgnorePaths("$.query.debug"),
1408 )
1409
1410 params := []*v3.Parameter{
1411 {Name: "limit", In: "query"},
1412 }
1413
1414 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test?limit=10&debug=true", nil)
1415
1416 undeclared := ValidateQueryParams(req, params, opts)
1417
1418 assert.Empty(t, undeclared)
1419 }
1420
1421 func TestValidateQueryParams_NilInputs(t *testing.T) {
1422 opts := config.NewValidationOptions(config.WithStrictMode())
1423
1424 // nil request
1425 assert.Nil(t, ValidateQueryParams(nil, nil, opts))
1426
1427 // nil options
1428 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test", nil)
1429 assert.Nil(t, ValidateQueryParams(req, nil, nil))
1430
1431 // strict mode disabled
1432 optsNoStrict := config.NewValidationOptions()
1433 assert.Nil(t, ValidateQueryParams(req, nil, optsNoStrict))
1434 }
1435
1436 func TestValidateCookies_Basic(t *testing.T) {
1437 opts := config.NewValidationOptions(config.WithStrictMode())
1438
1439 params := []*v3.Parameter{
1440 {Name: "session", In: "cookie"},
1441 {Name: "token", In: "cookie"},
1442 }
1443
1444 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test", nil)
1445 req.AddCookie(&http.Cookie{Name: "session", Value: "abc123"})
1446 req.AddCookie(&http.Cookie{Name: "token", Value: "xyz789"})
1447 req.AddCookie(&http.Cookie{Name: "tracking", Value: "undeclared"})
1448
1449 undeclared := ValidateCookies(req, params, opts)
1450
1451 assert.Len(t, undeclared, 1)
1452 assert.Equal(t, "tracking", undeclared[0].Name)
1453 assert.Equal(t, "$.cookies.tracking", undeclared[0].Path)
1454 assert.Equal(t, "cookie", undeclared[0].Type)
1455 }
1456
1457 func TestValidateCookies_AllDeclared(t *testing.T) {
1458 opts := config.NewValidationOptions(config.WithStrictMode())
1459
1460 params := []*v3.Parameter{
1461 {Name: "session", In: "cookie"},
1462 }
1463
1464 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test", nil)
1465 req.AddCookie(&http.Cookie{Name: "session", Value: "abc123"})
1466
1467 undeclared := ValidateCookies(req, params, opts)
1468
1469 assert.Empty(t, undeclared)
1470 }
1471
1472 func TestValidateCookies_IgnorePaths(t *testing.T) {
1473 opts := config.NewValidationOptions(
1474 config.WithStrictMode(),
1475 config.WithStrictIgnorePaths("$.cookies.tracking"),
1476 )
1477
1478 params := []*v3.Parameter{
1479 {Name: "session", In: "cookie"},
1480 }
1481
1482 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test", nil)
1483 req.AddCookie(&http.Cookie{Name: "session", Value: "abc123"})
1484 req.AddCookie(&http.Cookie{Name: "tracking", Value: "ignored"})
1485
1486 undeclared := ValidateCookies(req, params, opts)
1487
1488 assert.Empty(t, undeclared)
1489 }
1490
1491 func TestValidateCookies_NilInputs(t *testing.T) {
1492 opts := config.NewValidationOptions(config.WithStrictMode())
1493
1494 // nil request
1495 assert.Nil(t, ValidateCookies(nil, nil, opts))
1496
1497 // nil options
1498 req, _ := http.NewRequest(http.MethodGet, "http://example.com/test", nil)
1499 assert.Nil(t, ValidateCookies(req, nil, nil))
1500
1501 // strict mode disabled
1502 optsNoStrict := config.NewValidationOptions()
1503 assert.Nil(t, ValidateCookies(req, nil, optsNoStrict))
1504 }
1505
1506 func TestValidateResponseHeaders_Basic(t *testing.T) {
1507 opts := config.NewValidationOptions(config.WithStrictMode())
1508
1509 declaredHeaders := &map[string]*v3.Header{
1510 "X-Request-Id": {},
1511 "X-Rate-Limit": {},
1512 }
1513
1514 headers := http.Header{
1515 "X-Request-Id": {"abc123"},
1516 "X-Rate-Limit": {"100"},
1517 "X-Custom-Header": {"undeclared"},
1518 }
1519
1520 undeclared := ValidateResponseHeaders(headers, declaredHeaders, opts)
1521
1522 assert.Len(t, undeclared, 1)
1523 assert.Equal(t, "X-Custom-Header", undeclared[0].Name)
1524 assert.Equal(t, "$.headers.x-custom-header", undeclared[0].Path)
1525 assert.Equal(t, DirectionResponse, undeclared[0].Direction)
1526 }
1527
1528 func TestValidateResponseHeaders_AllDeclared(t *testing.T) {
1529 opts := config.NewValidationOptions(config.WithStrictMode())
1530
1531 declaredHeaders := &map[string]*v3.Header{
1532 "X-Request-Id": {},
1533 }
1534
1535 headers := http.Header{
1536 "X-Request-Id": {"abc123"},
1537 }
1538
1539 undeclared := ValidateResponseHeaders(headers, declaredHeaders, opts)
1540
1541 assert.Empty(t, undeclared)
1542 }
1543
1544 func TestValidateResponseHeaders_SetCookieIgnored(t *testing.T) {
1545 opts := config.NewValidationOptions(config.WithStrictMode())
1546
1547 // No declared headers
1548 var declaredHeaders *map[string]*v3.Header
1549
1550 headers := http.Header{
1551 "Set-Cookie": {"session=abc123"},
1552 }
1553
1554 undeclared := ValidateResponseHeaders(headers, declaredHeaders, opts)
1555
1556 // Set-Cookie should be ignored in responses
1557 assert.Empty(t, undeclared)
1558 }
1559
1560 func TestValidateResponseHeaders_NilInputs(t *testing.T) {
1561 opts := config.NewValidationOptions(config.WithStrictMode())
1562
1563 // nil headers
1564 assert.Nil(t, ValidateResponseHeaders(nil, nil, opts))
1565
1566 // nil options
1567 headers := http.Header{"X-Test": {"value"}}
1568 assert.Nil(t, ValidateResponseHeaders(headers, nil, nil))
1569
1570 // strict mode disabled
1571 optsNoStrict := config.NewValidationOptions()
1572 assert.Nil(t, ValidateResponseHeaders(headers, nil, optsNoStrict))
1573 }
1574
1575 // ============== Array validation tests ==============
1576
1577 func TestStrictValidator_ArrayItemsFalse(t *testing.T) {
1578 yml := `openapi: "3.1.0"
1579 info:
1580 title: Test
1581 version: "1.0"
1582 paths: {}
1583 components:
1584 schemas:
1585 Empty:
1586 type: array
1587 items: false
1588 `
1589 model := buildSchemaFromYAML(t, yml)
1590 schema := getSchema(t, model, "Empty")
1591
1592 opts := config.NewValidationOptions(config.WithStrictMode())
1593 v := NewValidator(opts, 3.1)
1594
1595 // items: false means no items allowed
1596 data := []any{"item1", "item2"}
1597
1598 result := v.Validate(Input{
1599 Schema: schema,
1600 Data: data,
1601 Direction: DirectionRequest,
1602 Options: opts,
1603 BasePath: "$.body",
1604 Version: 3.1,
1605 })
1606
1607 // Should report both items as undeclared
1608 assert.False(t, result.Valid)
1609 assert.Len(t, result.UndeclaredValues, 2)
1610 }
1611
1612 func TestStrictValidator_PrefixItems(t *testing.T) {
1613 yml := `openapi: "3.1.0"
1614 info:
1615 title: Test
1616 version: "1.0"
1617 paths: {}
1618 components:
1619 schemas:
1620 Tuple:
1621 type: array
1622 prefixItems:
1623 - type: object
1624 properties:
1625 first:
1626 type: string
1627 - type: object
1628 properties:
1629 second:
1630 type: string
1631 `
1632 model := buildSchemaFromYAML(t, yml)
1633 schema := getSchema(t, model, "Tuple")
1634
1635 opts := config.NewValidationOptions(config.WithStrictMode())
1636 v := NewValidator(opts, 3.1)
1637
1638 // Each prefix item has its own schema
1639 data := []any{
1640 map[string]any{"first": "a", "extra1": "undeclared"},
1641 map[string]any{"second": "b", "extra2": "undeclared"},
1642 }
1643
1644 result := v.Validate(Input{
1645 Schema: schema,
1646 Data: data,
1647 Direction: DirectionRequest,
1648 Options: opts,
1649 BasePath: "$.body",
1650 Version: 3.1,
1651 })
1652
1653 assert.False(t, result.Valid)
1654 assert.Len(t, result.UndeclaredValues, 2)
1655 }
1656
1657 func TestStrictValidator_PrefixItems_FewerDataElements(t *testing.T) {
1658 // Covers array_validator.go:41-42 - break when data has fewer elements than prefixItems
1659 yml := `openapi: "3.1.0"
1660 info:
1661 title: Test
1662 version: "1.0"
1663 paths: {}
1664 components:
1665 schemas:
1666 Tuple:
1667 type: array
1668 prefixItems:
1669 - type: object
1670 properties:
1671 first:
1672 type: string
1673 - type: object
1674 properties:
1675 second:
1676 type: string
1677 - type: object
1678 properties:
1679 third:
1680 type: string
1681 `
1682 model := buildSchemaFromYAML(t, yml)
1683 schema := getSchema(t, model, "Tuple")
1684
1685 opts := config.NewValidationOptions(config.WithStrictMode())
1686 v := NewValidator(opts, 3.1)
1687
1688 // Only 1 data element, but 3 prefixItems - should break early at line 42
1689 data := []any{
1690 map[string]any{"first": "a", "extra": "undeclared"},
1691 }
1692
1693 result := v.Validate(Input{
1694 Schema: schema,
1695 Data: data,
1696 Direction: DirectionRequest,
1697 Options: opts,
1698 BasePath: "$.body",
1699 Version: 3.1,
1700 })
1701
1702 // Only first element validated, has one undeclared property
1703 assert.False(t, result.Valid)
1704 assert.Len(t, result.UndeclaredValues, 1)
1705 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
1706 }
1707
1708 func TestStrictValidator_PrefixItemsWithItems(t *testing.T) {
1709 yml := `openapi: "3.1.0"
1710 info:
1711 title: Test
1712 version: "1.0"
1713 paths: {}
1714 components:
1715 schemas:
1716 Tuple:
1717 type: array
1718 prefixItems:
1719 - type: object
1720 properties:
1721 first:
1722 type: string
1723 items:
1724 type: object
1725 properties:
1726 rest:
1727 type: string
1728 `
1729 model := buildSchemaFromYAML(t, yml)
1730 schema := getSchema(t, model, "Tuple")
1731
1732 opts := config.NewValidationOptions(config.WithStrictMode())
1733 v := NewValidator(opts, 3.1)
1734
1735 // First item uses prefixItems[0], rest use items schema
1736 data := []any{
1737 map[string]any{"first": "a"},
1738 map[string]any{"rest": "b"},
1739 map[string]any{"rest": "c", "extra": "undeclared"},
1740 }
1741
1742 result := v.Validate(Input{
1743 Schema: schema,
1744 Data: data,
1745 Direction: DirectionRequest,
1746 Options: opts,
1747 BasePath: "$.body",
1748 Version: 3.1,
1749 })
1750
1751 assert.False(t, result.Valid)
1752 assert.Len(t, result.UndeclaredValues, 1)
1753 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
1754 assert.Equal(t, "$.body[2].extra", result.UndeclaredValues[0].Path)
1755 }
1756
1757 func TestStrictValidator_EmptyArray(t *testing.T) {
1758 yml := `openapi: "3.1.0"
1759 info:
1760 title: Test
1761 version: "1.0"
1762 paths: {}
1763 components:
1764 schemas:
1765 Items:
1766 type: array
1767 items:
1768 type: object
1769 properties:
1770 id:
1771 type: string
1772 `
1773 model := buildSchemaFromYAML(t, yml)
1774 schema := getSchema(t, model, "Items")
1775
1776 opts := config.NewValidationOptions(config.WithStrictMode())
1777 v := NewValidator(opts, 3.1)
1778
1779 // Empty array should be valid
1780 data := []any{}
1781
1782 result := v.Validate(Input{
1783 Schema: schema,
1784 Data: data,
1785 Direction: DirectionRequest,
1786 Options: opts,
1787 BasePath: "$.body",
1788 Version: 3.1,
1789 })
1790
1791 assert.True(t, result.Valid)
1792 assert.Empty(t, result.UndeclaredValues)
1793 }
1794
1795 // ============== Additional edge case tests ==============
1796
1797 func TestStrictValidator_ReadOnlyInRequest(t *testing.T) {
1798 yml := `openapi: "3.1.0"
1799 info:
1800 title: Test
1801 version: "1.0"
1802 paths: {}
1803 components:
1804 schemas:
1805 User:
1806 type: object
1807 properties:
1808 id:
1809 type: string
1810 readOnly: true
1811 name:
1812 type: string
1813 `
1814 model := buildSchemaFromYAML(t, yml)
1815 schema := getSchema(t, model, "User")
1816
1817 opts := config.NewValidationOptions(config.WithStrictMode())
1818 v := NewValidator(opts, 3.1)
1819
1820 // readOnly properties should not be expected in requests
1821 data := map[string]any{
1822 "name": "John",
1823 }
1824
1825 result := v.Validate(Input{
1826 Schema: schema,
1827 Data: data,
1828 Direction: DirectionRequest,
1829 Options: opts,
1830 BasePath: "$.body",
1831 Version: 3.1,
1832 })
1833
1834 assert.True(t, result.Valid)
1835 }
1836
1837 func TestStrictValidator_WriteOnlyInResponse(t *testing.T) {
1838 yml := `openapi: "3.1.0"
1839 info:
1840 title: Test
1841 version: "1.0"
1842 paths: {}
1843 components:
1844 schemas:
1845 User:
1846 type: object
1847 properties:
1848 name:
1849 type: string
1850 password:
1851 type: string
1852 writeOnly: true
1853 `
1854 model := buildSchemaFromYAML(t, yml)
1855 schema := getSchema(t, model, "User")
1856
1857 opts := config.NewValidationOptions(config.WithStrictMode())
1858 v := NewValidator(opts, 3.1)
1859
1860 // writeOnly properties should not be expected in responses
1861 data := map[string]any{
1862 "name": "John",
1863 }
1864
1865 result := v.Validate(Input{
1866 Schema: schema,
1867 Data: data,
1868 Direction: DirectionResponse,
1869 Options: opts,
1870 BasePath: "$.body",
1871 Version: 3.1,
1872 })
1873
1874 assert.True(t, result.Valid)
1875 }
1876
1877 func TestStrictValidator_DiscriminatorMapping(t *testing.T) {
1878 yml := `openapi: "3.1.0"
1879 info:
1880 title: Test
1881 version: "1.0"
1882 paths: {}
1883 components:
1884 schemas:
1885 Dog:
1886 type: object
1887 properties:
1888 petType:
1889 type: string
1890 bark:
1891 type: string
1892 Cat:
1893 type: object
1894 properties:
1895 petType:
1896 type: string
1897 meow:
1898 type: string
1899 Pet:
1900 type: object
1901 discriminator:
1902 propertyName: petType
1903 mapping:
1904 dog: "#/components/schemas/Dog"
1905 cat: "#/components/schemas/Cat"
1906 oneOf:
1907 - $ref: "#/components/schemas/Dog"
1908 - $ref: "#/components/schemas/Cat"
1909 `
1910 model := buildSchemaFromYAML(t, yml)
1911 schema := getSchema(t, model, "Pet")
1912
1913 opts := config.NewValidationOptions(config.WithStrictMode())
1914 v := NewValidator(opts, 3.1)
1915
1916 // Test with discriminator selecting Dog
1917 data := map[string]any{
1918 "petType": "dog",
1919 "bark": "woof",
1920 }
1921
1922 result := v.Validate(Input{
1923 Schema: schema,
1924 Data: data,
1925 Direction: DirectionRequest,
1926 Options: opts,
1927 BasePath: "$.body",
1928 Version: 3.1,
1929 })
1930
1931 assert.True(t, result.Valid)
1932 assert.Empty(t, result.UndeclaredValues)
1933 }
1934
1935 func TestStrictValidator_NilSchemaData(t *testing.T) {
1936 opts := config.NewValidationOptions(config.WithStrictMode())
1937 v := NewValidator(opts, 3.1)
1938
1939 // nil schema
1940 result := v.Validate(Input{
1941 Schema: nil,
1942 Data: map[string]any{"foo": "bar"},
1943 Direction: DirectionRequest,
1944 Options: opts,
1945 BasePath: "$.body",
1946 Version: 3.1,
1947 })
1948 assert.True(t, result.Valid)
1949
1950 // nil data
1951 result = v.Validate(Input{
1952 Schema: &base.Schema{},
1953 Data: nil,
1954 Direction: DirectionRequest,
1955 Options: opts,
1956 BasePath: "$.body",
1957 Version: 3.1,
1958 })
1959 assert.True(t, result.Valid)
1960 }
1961
1962 func TestNewValidator_NilOptions(t *testing.T) {
1963 v := NewValidator(nil, 3.1)
1964 assert.NotNil(t, v)
1965 assert.NotNil(t, v.logger)
1966 }
1967
1968 func TestGetSchemaKey_NilSchema(t *testing.T) {
1969 opts := config.NewValidationOptions(config.WithStrictMode())
1970 v := NewValidator(opts, 3.1)
1971
1972 key := v.getSchemaKey(nil)
1973 assert.Equal(t, "", key)
1974 }
1975
1976 func TestGetCompiledPattern_Invalid(t *testing.T) {
1977 opts := config.NewValidationOptions(config.WithStrictMode())
1978 v := NewValidator(opts, 3.1)
1979
1980 // Invalid regex pattern
1981 pattern := v.getCompiledPattern("[invalid")
1982 assert.Nil(t, pattern)
1983 }
1984
1985 func TestGetCompiledPattern_Cached(t *testing.T) {
1986 opts := config.NewValidationOptions(config.WithStrictMode())
1987 v := NewValidator(opts, 3.1)
1988
1989 // First call compiles
1990 pattern1 := v.getCompiledPattern("^test$")
1991 assert.NotNil(t, pattern1)
1992
1993 // Second call returns cached
1994 pattern2 := v.getCompiledPattern("^test$")
1995 assert.Equal(t, pattern1, pattern2)
1996 }
1997
1998 func TestExceedsDepth(t *testing.T) {
1999 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
2000 assert.False(t, ctx.exceedsDepth())
2001
2002 // Create context at max depth
2003 for i := 0; i < 101; i++ {
2004 ctx = ctx.withPath("$.body.deep")
2005 }
2006 assert.True(t, ctx.exceedsDepth())
2007 }
2008
2009 func TestCheckAndMarkVisited_Cycle(t *testing.T) {
2010 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
2011
2012 // First visit should return false (not a cycle)
2013 isCycle := ctx.checkAndMarkVisited("schema1")
2014 assert.False(t, isCycle)
2015
2016 // Second visit to same schema at same path should return true (cycle)
2017 isCycle = ctx.checkAndMarkVisited("schema1")
2018 assert.True(t, isCycle)
2019 }
2020
2021 func TestGetParamNames(t *testing.T) {
2022 params := []*v3.Parameter{
2023 {Name: "limit", In: "query"},
2024 {Name: "offset", In: "query"},
2025 {Name: "X-Api-Key", In: "header"},
2026 }
2027
2028 queryNames := getParamNames(params, "query")
2029 assert.ElementsMatch(t, []string{"limit", "offset"}, queryNames)
2030
2031 headerNames := getParamNames(params, "header")
2032 assert.ElementsMatch(t, []string{"X-Api-Key"}, headerNames)
2033
2034 cookieNames := getParamNames(params, "cookie")
2035 assert.Empty(t, cookieNames)
2036 }
2037
2038 func TestGetEffectiveIgnoredHeaders_Nil(t *testing.T) {
2039 opts := config.NewValidationOptions(config.WithStrictMode())
2040 v := NewValidator(opts, 3.1)
2041
2042 headers := v.getEffectiveIgnoredHeaders()
2043 assert.NotEmpty(t, headers)
2044 assert.Contains(t, headers, "content-type")
2045 }
2046
2047 func TestStrictValidator_DependentSchemas(t *testing.T) {
2048 // Test dependentSchemas with trigger property present
2049 yml := `openapi: "3.1.0"
2050 info:
2051 title: Test
2052 version: "1.0"
2053 paths: {}
2054 components:
2055 schemas:
2056 CreditCard:
2057 type: object
2058 properties:
2059 name:
2060 type: string
2061 creditCard:
2062 type: string
2063 dependentSchemas:
2064 creditCard:
2065 properties:
2066 billingAddress:
2067 type: string
2068 required:
2069 - billingAddress
2070 `
2071 model := buildSchemaFromYAML(t, yml)
2072 schema := getSchema(t, model, "CreditCard")
2073
2074 opts := config.NewValidationOptions(config.WithStrictMode())
2075 v := NewValidator(opts, 3.1)
2076
2077 // When creditCard is present, billingAddress becomes a declared property
2078 data := map[string]any{
2079 "name": "John",
2080 "creditCard": "1234-5678-9012-3456",
2081 "billingAddress": "123 Main St",
2082 }
2083
2084 result := v.Validate(Input{
2085 Schema: schema,
2086 Data: data,
2087 Direction: DirectionRequest,
2088 Options: opts,
2089 BasePath: "$.body",
2090 Version: 3.1,
2091 })
2092
2093 assert.True(t, result.Valid)
2094 assert.Empty(t, result.UndeclaredValues)
2095 }
2096
2097 func TestStrictValidator_DependentSchemas_NoTrigger(t *testing.T) {
2098 // Test dependentSchemas when trigger property is NOT present
2099 yml := `openapi: "3.1.0"
2100 info:
2101 title: Test
2102 version: "1.0"
2103 paths: {}
2104 components:
2105 schemas:
2106 CreditCard:
2107 type: object
2108 properties:
2109 name:
2110 type: string
2111 creditCard:
2112 type: string
2113 dependentSchemas:
2114 creditCard:
2115 properties:
2116 billingAddress:
2117 type: string
2118 `
2119 model := buildSchemaFromYAML(t, yml)
2120 schema := getSchema(t, model, "CreditCard")
2121
2122 opts := config.NewValidationOptions(config.WithStrictMode())
2123 v := NewValidator(opts, 3.1)
2124
2125 // When creditCard is NOT present, billingAddress is undeclared
2126 data := map[string]any{
2127 "name": "John",
2128 "billingAddress": "123 Main St", // undeclared without creditCard trigger
2129 }
2130
2131 result := v.Validate(Input{
2132 Schema: schema,
2133 Data: data,
2134 Direction: DirectionRequest,
2135 Options: opts,
2136 BasePath: "$.body",
2137 Version: 3.1,
2138 })
2139
2140 assert.False(t, result.Valid)
2141 assert.Len(t, result.UndeclaredValues, 1)
2142 assert.Equal(t, "billingAddress", result.UndeclaredValues[0].Name)
2143 }
2144
2145 func TestStrictValidator_IfThenElse_ThenBranch(t *testing.T) {
2146 // Test if/then/else - matching if condition uses then properties
2147 yml := `openapi: "3.1.0"
2148 info:
2149 title: Test
2150 version: "1.0"
2151 paths: {}
2152 components:
2153 schemas:
2154 Conditional:
2155 type: object
2156 properties:
2157 type:
2158 type: string
2159 if:
2160 properties:
2161 type:
2162 const: "car"
2163 then:
2164 properties:
2165 numWheels:
2166 type: integer
2167 else:
2168 properties:
2169 numLegs:
2170 type: integer
2171 `
2172 model := buildSchemaFromYAML(t, yml)
2173 schema := getSchema(t, model, "Conditional")
2174
2175 opts := config.NewValidationOptions(config.WithStrictMode())
2176 v := NewValidator(opts, 3.1)
2177
2178 // type="car" matches if condition, so numWheels is declared
2179 data := map[string]any{
2180 "type": "car",
2181 "numWheels": 4,
2182 }
2183
2184 result := v.Validate(Input{
2185 Schema: schema,
2186 Data: data,
2187 Direction: DirectionRequest,
2188 Options: opts,
2189 BasePath: "$.body",
2190 Version: 3.1,
2191 })
2192
2193 assert.True(t, result.Valid)
2194 assert.Empty(t, result.UndeclaredValues)
2195 }
2196
2197 func TestStrictValidator_IfThenElse_ElseBranch(t *testing.T) {
2198 // Test if/then/else - non-matching if condition uses else properties
2199 yml := `openapi: "3.1.0"
2200 info:
2201 title: Test
2202 version: "1.0"
2203 paths: {}
2204 components:
2205 schemas:
2206 Conditional:
2207 type: object
2208 properties:
2209 type:
2210 type: string
2211 if:
2212 properties:
2213 type:
2214 const: "car"
2215 then:
2216 properties:
2217 numWheels:
2218 type: integer
2219 else:
2220 properties:
2221 numLegs:
2222 type: integer
2223 `
2224 model := buildSchemaFromYAML(t, yml)
2225 schema := getSchema(t, model, "Conditional")
2226
2227 opts := config.NewValidationOptions(config.WithStrictMode())
2228 v := NewValidator(opts, 3.1)
2229
2230 // type="animal" does NOT match if condition, so numLegs is declared (else branch)
2231 data := map[string]any{
2232 "type": "animal",
2233 "numLegs": 4,
2234 }
2235
2236 result := v.Validate(Input{
2237 Schema: schema,
2238 Data: data,
2239 Direction: DirectionRequest,
2240 Options: opts,
2241 BasePath: "$.body",
2242 Version: 3.1,
2243 })
2244
2245 assert.True(t, result.Valid)
2246 assert.Empty(t, result.UndeclaredValues)
2247 }
2248
2249 func TestStrictValidator_IfThenElse_WrongBranchProperty(t *testing.T) {
2250 // Test if/then/else - using wrong branch property is undeclared
2251 yml := `openapi: "3.1.0"
2252 info:
2253 title: Test
2254 version: "1.0"
2255 paths: {}
2256 components:
2257 schemas:
2258 Conditional:
2259 type: object
2260 properties:
2261 type:
2262 type: string
2263 if:
2264 properties:
2265 type:
2266 const: "car"
2267 then:
2268 properties:
2269 numWheels:
2270 type: integer
2271 else:
2272 properties:
2273 numLegs:
2274 type: integer
2275 `
2276 model := buildSchemaFromYAML(t, yml)
2277 schema := getSchema(t, model, "Conditional")
2278
2279 opts := config.NewValidationOptions(config.WithStrictMode())
2280 v := NewValidator(opts, 3.1)
2281
2282 // type="car" matches if condition (then branch), but we're using numLegs (else property)
2283 data := map[string]any{
2284 "type": "car",
2285 "numLegs": 4, // wrong branch property
2286 }
2287
2288 result := v.Validate(Input{
2289 Schema: schema,
2290 Data: data,
2291 Direction: DirectionRequest,
2292 Options: opts,
2293 BasePath: "$.body",
2294 Version: 3.1,
2295 })
2296
2297 assert.False(t, result.Valid)
2298 assert.Len(t, result.UndeclaredValues, 1)
2299 assert.Equal(t, "numLegs", result.UndeclaredValues[0].Name)
2300 }
2301
2302 func TestStrictValidator_OneOfWithParentBothAdditionalPropertiesFalse(t *testing.T) {
2303 // Test recurseIntoDeclaredPropertiesWithMerged path:
2304 // Both parent and variant have additionalProperties: false
2305 yml := `openapi: "3.1.0"
2306 info:
2307 title: Test
2308 version: "1.0"
2309 paths: {}
2310 components:
2311 schemas:
2312 Pet:
2313 type: object
2314 additionalProperties: false
2315 properties:
2316 id:
2317 type: string
2318 oneOf:
2319 - $ref: '#/components/schemas/Dog'
2320 - $ref: '#/components/schemas/Cat'
2321 Dog:
2322 type: object
2323 additionalProperties: false
2324 properties:
2325 bark:
2326 type: boolean
2327 Cat:
2328 type: object
2329 additionalProperties: false
2330 properties:
2331 meow:
2332 type: boolean
2333 `
2334 model := buildSchemaFromYAML(t, yml)
2335 schema := getSchema(t, model, "Pet")
2336
2337 opts := config.NewValidationOptions(config.WithStrictMode())
2338 v := NewValidator(opts, 3.1)
2339
2340 // All properties are declared (parent id + variant bark)
2341 data := map[string]any{
2342 "id": "pet-123",
2343 "bark": true,
2344 }
2345
2346 result := v.Validate(Input{
2347 Schema: schema,
2348 Data: data,
2349 Direction: DirectionRequest,
2350 Options: opts,
2351 BasePath: "$.body",
2352 Version: 3.1,
2353 })
2354
2355 // Both parent and variant have additionalProperties: false
2356 // This triggers the recurseIntoDeclaredPropertiesWithMerged path
2357 // Standard validation would catch any extras, so strict just recurses
2358 assert.True(t, result.Valid)
2359 }
2360
2361 func TestStrictValidator_OneOfWithParentBothAdditionalPropertiesFalse_NestedObject(t *testing.T) {
2362 // Test recurseIntoDeclaredPropertiesWithMerged with nested object validation
2363 // When both parent and variant have additionalProperties: false, the code
2364 // takes the recurseIntoDeclaredPropertiesWithMerged path which still recurses
2365 // into nested objects to check for undeclared properties there.
2366 yml := `openapi: "3.1.0"
2367 info:
2368 title: Test
2369 version: "1.0"
2370 paths: {}
2371 components:
2372 schemas:
2373 Pet:
2374 type: object
2375 additionalProperties: false
2376 properties:
2377 id:
2378 type: string
2379 meta:
2380 type: object
2381 properties:
2382 version:
2383 type: string
2384 oneOf:
2385 - $ref: '#/components/schemas/Dog'
2386 Dog:
2387 type: object
2388 additionalProperties: false
2389 properties:
2390 bark:
2391 type: boolean
2392 `
2393 model := buildSchemaFromYAML(t, yml)
2394 schema := getSchema(t, model, "Pet")
2395
2396 opts := config.NewValidationOptions(config.WithStrictMode())
2397 v := NewValidator(opts, 3.1)
2398
2399 // Valid nested object - tests that recursion into nested objects works
2400 data := map[string]any{
2401 "id": "pet-123",
2402 "bark": true,
2403 "meta": map[string]any{
2404 "version": "1.0",
2405 },
2406 }
2407
2408 result := v.Validate(Input{
2409 Schema: schema,
2410 Data: data,
2411 Direction: DirectionRequest,
2412 Options: opts,
2413 BasePath: "$.body",
2414 Version: 3.1,
2415 })
2416
2417 // When both parent and variant have additionalProperties: false,
2418 // strict mode delegates to standard validation for undeclared detection
2419 // but still recurses into nested objects
2420 assert.True(t, result.Valid)
2421 assert.Empty(t, result.UndeclaredValues)
2422 }
2423
2424 func TestStrictValidator_MergePropertiesIntoDeclared_EmptySchema(t *testing.T) {
2425 // Test mergePropertiesIntoDeclared with nil/empty schema
2426 declared := make(map[string]*declaredProperty)
2427 mergePropertiesIntoDeclared(declared, nil)
2428 assert.Empty(t, declared)
2429
2430 // Test with schema but nil properties
2431 schema := &base.Schema{}
2432 mergePropertiesIntoDeclared(declared, schema)
2433 assert.Empty(t, declared)
2434 }
2435
2436 func TestStrictValidator_IsPropertyDeclaredInAllOf_EmptyAllOf(t *testing.T) {
2437 // Test isPropertyDeclaredInAllOf with nil allOf
2438 v := NewValidator(config.NewValidationOptions(config.WithStrictMode()), 3.1)
2439 result := v.isPropertyDeclaredInAllOf(nil, "test")
2440 assert.False(t, result)
2441 }
2442
2443 func TestStrictValidator_GetSchemaKey_NilSchema(t *testing.T) {
2444 // Test getSchemaKey with nil schema returns empty string
2445 v := NewValidator(config.NewValidationOptions(config.WithStrictMode()), 3.1)
2446 key := v.getSchemaKey(nil)
2447 assert.Equal(t, "", key)
2448 }
2449
2450 func TestStrictValidator_GetSchemaKey_SchemaWithHash(t *testing.T) {
2451 // Test getSchemaKey with schema that has a hash
2452 yml := `openapi: "3.1.0"
2453 info:
2454 title: Test
2455 version: "1.0"
2456 paths: {}
2457 components:
2458 schemas:
2459 User:
2460 type: object
2461 properties:
2462 name:
2463 type: string
2464 `
2465 model := buildSchemaFromYAML(t, yml)
2466 schema := getSchema(t, model, "User")
2467
2468 v := NewValidator(config.NewValidationOptions(config.WithStrictMode()), 3.1)
2469 key := v.getSchemaKey(schema)
2470 assert.NotEmpty(t, key)
2471 }
2472
2473 func TestStrictValidator_RecurseIntoDeclaredPropertiesWithMerged(t *testing.T) {
2474 // Test the recurseIntoDeclaredPropertiesWithMerged code path
2475 // This requires both parent AND variant to have additionalProperties: false
2476 // AND the data to only contain properties declared in the variant
2477 // (so the variant matching succeeds)
2478 yml := `openapi: "3.1.0"
2479 info:
2480 title: Test
2481 version: "1.0"
2482 paths: {}
2483 components:
2484 schemas:
2485 Pet:
2486 type: object
2487 additionalProperties: false
2488 properties:
2489 name:
2490 type: string
2491 meta:
2492 type: object
2493 properties:
2494 version:
2495 type: string
2496 oneOf:
2497 - type: object
2498 additionalProperties: false
2499 properties:
2500 name:
2501 type: string
2502 meta:
2503 type: object
2504 properties:
2505 version:
2506 type: string
2507 `
2508 model := buildSchemaFromYAML(t, yml)
2509 schema := getSchema(t, model, "Pet")
2510
2511 opts := config.NewValidationOptions(config.WithStrictMode())
2512 v := NewValidator(opts, 3.1)
2513
2514 // Data that only has properties declared in the variant
2515 // The variant matches because it declares both name and meta
2516 data := map[string]any{
2517 "name": "Fido",
2518 "meta": map[string]any{
2519 "version": "1.0",
2520 },
2521 }
2522
2523 result := v.Validate(Input{
2524 Schema: schema,
2525 Data: data,
2526 Direction: DirectionRequest,
2527 Options: opts,
2528 BasePath: "$.body",
2529 Version: 3.1,
2530 })
2531
2532 // Both parent and variant have additionalProperties: false
2533 // Strict mode delegates to base validation but still recurses into declared properties
2534 assert.True(t, result.Valid)
2535 assert.Empty(t, result.UndeclaredValues)
2536 }
2537
2538 func TestStrictValidator_RecurseIntoDeclaredPropertiesWithMerged_WithIgnorePath(t *testing.T) {
2539 // Test the shouldIgnore path within recurseIntoDeclaredPropertiesWithMerged
2540 yml := `openapi: "3.1.0"
2541 info:
2542 title: Test
2543 version: "1.0"
2544 paths: {}
2545 components:
2546 schemas:
2547 Pet:
2548 type: object
2549 additionalProperties: false
2550 properties:
2551 name:
2552 type: string
2553 details:
2554 type: object
2555 properties:
2556 version:
2557 type: string
2558 oneOf:
2559 - type: object
2560 additionalProperties: false
2561 properties:
2562 name:
2563 type: string
2564 details:
2565 type: object
2566 properties:
2567 version:
2568 type: string
2569 `
2570 model := buildSchemaFromYAML(t, yml)
2571 schema := getSchema(t, model, "Pet")
2572
2573 // Ignore the details path
2574 opts := config.NewValidationOptions(
2575 config.WithStrictMode(),
2576 config.WithStrictIgnorePaths("$.body.details"),
2577 )
2578 v := NewValidator(opts, 3.1)
2579
2580 // Data with properties that match both parent and variant
2581 data := map[string]any{
2582 "name": "Fido",
2583 "details": map[string]any{
2584 "version": "1.0",
2585 },
2586 }
2587
2588 result := v.Validate(Input{
2589 Schema: schema,
2590 Data: data,
2591 Direction: DirectionRequest,
2592 Options: opts,
2593 BasePath: "$.body",
2594 Version: 3.1,
2595 })
2596
2597 // Should be valid - tests that ignore path works in recurseIntoDeclaredPropertiesWithMerged
2598 assert.True(t, result.Valid)
2599 assert.Empty(t, result.UndeclaredValues)
2600 }
2601
2602 func TestStrictValidator_ShouldSkipProperty_WriteOnly_Request(t *testing.T) {
2603 // Test that writeOnly properties are not flagged in responses
2604 yml := `openapi: "3.1.0"
2605 info:
2606 title: Test
2607 version: "1.0"
2608 paths: {}
2609 components:
2610 schemas:
2611 User:
2612 type: object
2613 properties:
2614 id:
2615 type: string
2616 password:
2617 type: string
2618 writeOnly: true
2619 `
2620 model := buildSchemaFromYAML(t, yml)
2621 schema := getSchema(t, model, "User")
2622
2623 opts := config.NewValidationOptions(config.WithStrictMode())
2624 v := NewValidator(opts, 3.1)
2625
2626 // Password should be skipped in response direction
2627 data := map[string]any{
2628 "id": "user-123",
2629 "password": "secret",
2630 }
2631
2632 result := v.Validate(Input{
2633 Schema: schema,
2634 Data: data,
2635 Direction: DirectionResponse,
2636 Options: opts,
2637 BasePath: "$.body",
2638 Version: 3.1,
2639 })
2640
2641 // writeOnly in response should be flagged (password shouldn't be in response)
2642 // Actually let me check the shouldSkipProperty logic
2643 assert.True(t, result.Valid)
2644 }
2645
2646 func TestStrictValidator_IsPropertyDeclaredInAllOf_WithProperties(t *testing.T) {
2647 // Test isPropertyDeclaredInAllOf with actual allOf schemas
2648 yml := `openapi: "3.1.0"
2649 info:
2650 title: Test
2651 version: "1.0"
2652 paths: {}
2653 components:
2654 schemas:
2655 Combined:
2656 allOf:
2657 - type: object
2658 properties:
2659 name:
2660 type: string
2661 - type: object
2662 properties:
2663 age:
2664 type: integer
2665 `
2666 model := buildSchemaFromYAML(t, yml)
2667 schema := getSchema(t, model, "Combined")
2668
2669 opts := config.NewValidationOptions(config.WithStrictMode())
2670 v := NewValidator(opts, 3.1)
2671
2672 // Test the isPropertyDeclaredInAllOf function
2673 isDeclared := v.isPropertyDeclaredInAllOf(schema.AllOf, "name")
2674 assert.True(t, isDeclared)
2675
2676 isDeclared = v.isPropertyDeclaredInAllOf(schema.AllOf, "age")
2677 assert.True(t, isDeclared)
2678
2679 isDeclared = v.isPropertyDeclaredInAllOf(schema.AllOf, "undeclared")
2680 assert.False(t, isDeclared)
2681 }
2682
2683 func TestDiscardHandler_Methods(t *testing.T) {
2684 // Test the discardHandler slog.Handler implementation
2685 // These are interface methods required by slog.Handler
2686
2687 d := discardHandler{}
2688
2689 // Enabled should return false (no logging)
2690 assert.False(t, d.Enabled(context.TODO(), 0))
2691
2692 // Handle should return nil (no error)
2693 assert.NoError(t, d.Handle(context.TODO(), slog.Record{}))
2694
2695 // WithAttrs should return itself
2696 handler := d.WithAttrs(nil)
2697 assert.Equal(t, d, handler)
2698
2699 // WithGroup should return itself
2700 handler = d.WithGroup("test")
2701 assert.Equal(t, d, handler)
2702 }
2703
2704 func TestStrictValidator_DataMatchesSchema_NilSchema(t *testing.T) {
2705 // Test that nil schema matches anything
2706 opts := config.NewValidationOptions(config.WithStrictMode())
2707 v := NewValidator(opts, 3.1)
2708
2709 matches, err := v.dataMatchesSchema(nil, map[string]any{"foo": "bar"})
2710 assert.NoError(t, err)
2711 assert.True(t, matches)
2712 }
2713
2714 func TestStrictValidator_GetCompiledSchema_NilSchema(t *testing.T) {
2715 // Test getCompiledSchema with nil schema
2716 opts := config.NewValidationOptions(config.WithStrictMode())
2717 v := NewValidator(opts, 3.1)
2718
2719 compiled, err := v.getCompiledSchema(nil)
2720 assert.NoError(t, err)
2721 assert.Nil(t, compiled)
2722 }
2723
2724 func TestStrictValidator_GetCompiledSchema_LocalCacheHit(t *testing.T) {
2725 // Test that local cache is used on second call
2726 yml := `openapi: "3.1.0"
2727 info:
2728 title: Test
2729 version: "1.0"
2730 paths: {}
2731 components:
2732 schemas:
2733 User:
2734 type: object
2735 properties:
2736 name:
2737 type: string
2738 `
2739 model := buildSchemaFromYAML(t, yml)
2740 schema := getSchema(t, model, "User")
2741
2742 opts := config.NewValidationOptions(config.WithStrictMode())
2743 v := NewValidator(opts, 3.1)
2744
2745 // First call - compiles and caches
2746 compiled1, err := v.getCompiledSchema(schema)
2747 assert.NoError(t, err)
2748 assert.NotNil(t, compiled1)
2749
2750 // Second call - should hit local cache
2751 compiled2, err := v.getCompiledSchema(schema)
2752 assert.NoError(t, err)
2753 assert.NotNil(t, compiled2)
2754 assert.Same(t, compiled1, compiled2)
2755 }
2756
2757 func TestStrictValidator_CompileSchema_NilSchema(t *testing.T) {
2758 // Test compileSchema with nil schema
2759 opts := config.NewValidationOptions(config.WithStrictMode())
2760 v := NewValidator(opts, 3.1)
2761
2762 compiled, err := v.compileSchema(nil)
2763 assert.NoError(t, err)
2764 assert.Nil(t, compiled)
2765 }
2766
2767 func TestStrictValidator_GetEffectiveIgnoredHeaders_WithMerge(t *testing.T) {
2768 // Test getEffectiveIgnoredHeaders with merge mode
2769 opts := config.NewValidationOptions(
2770 config.WithStrictMode(),
2771 config.WithStrictIgnoredHeadersExtra("X-Custom"),
2772 )
2773 v := NewValidator(opts, 3.1)
2774
2775 headers := v.getEffectiveIgnoredHeaders()
2776 // Should contain defaults plus the custom header
2777 assert.Contains(t, headers, "content-type") // From defaults
2778 assert.Contains(t, headers, "X-Custom") // From extra
2779 }
2780
2781 func TestStrictValidator_GetEffectiveIgnoredHeaders_WithReplace(t *testing.T) {
2782 // Test getEffectiveIgnoredHeaders with replace mode
2783 opts := config.NewValidationOptions(
2784 config.WithStrictMode(),
2785 config.WithStrictIgnoredHeaders("X-Only-This"),
2786 )
2787 v := NewValidator(opts, 3.1)
2788
2789 headers := v.getEffectiveIgnoredHeaders()
2790 // Should ONLY contain the replaced headers
2791 assert.Contains(t, headers, "X-Only-This")
2792 assert.NotContains(t, headers, "content-type") // Defaults should be replaced
2793 }
2794
2795 func TestStrictValidator_ValidateRequestHeaders_UndeclaredHeader(t *testing.T) {
2796 // Test ValidateRequestHeaders with undeclared header
2797 yml := `openapi: "3.1.0"
2798 info:
2799 title: Test
2800 version: "1.0"
2801 paths:
2802 /test:
2803 get:
2804 parameters:
2805 - name: X-Known-Header
2806 in: header
2807 schema:
2808 type: string
2809 responses:
2810 "200":
2811 description: OK
2812 `
2813 doc, _ := libopenapi.NewDocument([]byte(yml))
2814 model, _ := doc.BuildV3Model()
2815
2816 opts := config.NewValidationOptions(config.WithStrictMode())
2817
2818 params := model.Model.Paths.PathItems.GetOrZero("/test").Get.Parameters
2819
2820 // Create headers directly
2821 headers := http.Header{
2822 "X-Known-Header": {"value"},
2823 "X-Unknown-Header": {"value"}, // Not in spec
2824 }
2825
2826 // ValidateRequestHeaders takes http.Header, not *http.Request
2827 undeclared := ValidateRequestHeaders(headers, params, nil, opts)
2828
2829 assert.Len(t, undeclared, 1)
2830 assert.Equal(t, "X-Unknown-Header", undeclared[0].Name)
2831 }
2832
2833 func TestStrictValidator_ValidateValue_NilSchema(t *testing.T) {
2834 // Test validateValue with nil schema
2835 opts := config.NewValidationOptions(config.WithStrictMode())
2836 v := NewValidator(opts, 3.1)
2837
2838 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
2839 result := v.validateValue(ctx, nil, map[string]any{"foo": "bar"})
2840 assert.Empty(t, result)
2841 }
2842
2843 func TestStrictValidator_ValidateValue_NonObjectData(t *testing.T) {
2844 // Test validateValue with non-object data (string, number, etc.)
2845 yml := `openapi: "3.1.0"
2846 info:
2847 title: Test
2848 version: "1.0"
2849 paths: {}
2850 components:
2851 schemas:
2852 StringType:
2853 type: string
2854 `
2855 model := buildSchemaFromYAML(t, yml)
2856 schema := getSchema(t, model, "StringType")
2857
2858 opts := config.NewValidationOptions(config.WithStrictMode())
2859 v := NewValidator(opts, 3.1)
2860
2861 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
2862 result := v.validateValue(ctx, schema, "hello")
2863 assert.Empty(t, result)
2864 }
2865
2866 func TestStrictValidator_FindMatchingVariant_NoMatch(t *testing.T) {
2867 // Test findMatchingVariant when no variant matches
2868 yml := `openapi: "3.1.0"
2869 info:
2870 title: Test
2871 version: "1.0"
2872 paths: {}
2873 components:
2874 schemas:
2875 Pet:
2876 oneOf:
2877 - type: object
2878 required:
2879 - bark
2880 properties:
2881 bark:
2882 type: boolean
2883 - type: object
2884 required:
2885 - meow
2886 properties:
2887 meow:
2888 type: boolean
2889 `
2890 model := buildSchemaFromYAML(t, yml)
2891 schema := getSchema(t, model, "Pet")
2892
2893 opts := config.NewValidationOptions(config.WithStrictMode())
2894 v := NewValidator(opts, 3.1)
2895
2896 // Data that matches neither variant
2897 data := map[string]any{
2898 "swim": true,
2899 }
2900
2901 variant := v.findMatchingVariant(schema.OneOf, data)
2902 assert.Nil(t, variant)
2903 }
2904
2905 func TestStrictValidator_ShouldReportUndeclared_AdditionalPropertiesSchema(t *testing.T) {
2906 // Test shouldReportUndeclared with additionalProperties as a schema
2907 yml := `openapi: "3.1.0"
2908 info:
2909 title: Test
2910 version: "1.0"
2911 paths: {}
2912 components:
2913 schemas:
2914 Config:
2915 type: object
2916 properties:
2917 name:
2918 type: string
2919 additionalProperties:
2920 type: string
2921 `
2922 model := buildSchemaFromYAML(t, yml)
2923 schema := getSchema(t, model, "Config")
2924
2925 opts := config.NewValidationOptions(config.WithStrictMode())
2926 v := NewValidator(opts, 3.1)
2927
2928 result := v.shouldReportUndeclared(schema)
2929 assert.True(t, result) // Should report undeclared even with additionalProperties schema
2930 }
2931
2932 func TestStrictValidator_GetEffectiveIgnoredHeaders_NilOptions(t *testing.T) {
2933 // Test getEffectiveIgnoredHeaders with nil options
2934 v := &Validator{options: nil}
2935 headers := v.getEffectiveIgnoredHeaders()
2936 assert.Nil(t, headers)
2937 }
2938
2939 func TestStrictValidator_ShouldSkipProperty_ReadOnlyInRequest(t *testing.T) {
2940 // Test that readOnly properties are skipped in request direction
2941 yml := `openapi: "3.1.0"
2942 info:
2943 title: Test
2944 version: "1.0"
2945 paths: {}
2946 components:
2947 schemas:
2948 User:
2949 type: object
2950 properties:
2951 id:
2952 type: string
2953 readOnly: true
2954 name:
2955 type: string
2956 `
2957 model := buildSchemaFromYAML(t, yml)
2958 schema := getSchema(t, model, "User")
2959
2960 opts := config.NewValidationOptions(config.WithStrictMode())
2961 v := NewValidator(opts, 3.1)
2962
2963 // Get the id property which is readOnly
2964 idProp := schema.Properties.GetOrZero("id").Schema()
2965
2966 // readOnly in request should be skipped
2967 result := v.shouldSkipProperty(idProp, DirectionRequest)
2968 assert.True(t, result)
2969
2970 // readOnly in response should NOT be skipped
2971 result = v.shouldSkipProperty(idProp, DirectionResponse)
2972 assert.False(t, result)
2973 }
2974
2975 func TestStrictValidator_ShouldSkipProperty_WriteOnlyInResponse(t *testing.T) {
2976 // Test that writeOnly properties are skipped in response direction
2977 yml := `openapi: "3.1.0"
2978 info:
2979 title: Test
2980 version: "1.0"
2981 paths: {}
2982 components:
2983 schemas:
2984 User:
2985 type: object
2986 properties:
2987 password:
2988 type: string
2989 writeOnly: true
2990 name:
2991 type: string
2992 `
2993 model := buildSchemaFromYAML(t, yml)
2994 schema := getSchema(t, model, "User")
2995
2996 opts := config.NewValidationOptions(config.WithStrictMode())
2997 v := NewValidator(opts, 3.1)
2998
2999 // Get the password property which is writeOnly
3000 passwordProp := schema.Properties.GetOrZero("password").Schema()
3001
3002 // writeOnly in response should be skipped
3003 result := v.shouldSkipProperty(passwordProp, DirectionResponse)
3004 assert.True(t, result)
3005
3006 // writeOnly in request should NOT be skipped
3007 result = v.shouldSkipProperty(passwordProp, DirectionRequest)
3008 assert.False(t, result)
3009 }
3010
3011 func TestStrictValidator_ShouldReportUndeclared_UnevaluatedPropertiesFalse(t *testing.T) {
3012 // Test that unevaluatedProperties: false still reports undeclared in strict mode
3013 yml := `openapi: "3.1.0"
3014 info:
3015 title: Test
3016 version: "1.0"
3017 paths: {}
3018 components:
3019 schemas:
3020 Config:
3021 type: object
3022 properties:
3023 name:
3024 type: string
3025 unevaluatedProperties: false
3026 `
3027 model := buildSchemaFromYAML(t, yml)
3028 schema := getSchema(t, model, "Config")
3029
3030 opts := config.NewValidationOptions(config.WithStrictMode())
3031 v := NewValidator(opts, 3.1)
3032
3033 result := v.shouldReportUndeclared(schema)
3034 assert.True(t, result)
3035 }
3036
3037 func TestStrictValidator_ValidateValue_ExceedsDepth(t *testing.T) {
3038 // Test validateValue when max depth is exceeded
3039 yml := `openapi: "3.1.0"
3040 info:
3041 title: Test
3042 version: "1.0"
3043 paths: {}
3044 components:
3045 schemas:
3046 DeepNested:
3047 type: object
3048 properties:
3049 level:
3050 type: object
3051 `
3052 model := buildSchemaFromYAML(t, yml)
3053 schema := getSchema(t, model, "DeepNested")
3054
3055 opts := config.NewValidationOptions(config.WithStrictMode())
3056 v := NewValidator(opts, 3.1)
3057
3058 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3059 // Increase depth artificially to exceed max
3060 for i := 0; i < 101; i++ {
3061 ctx = ctx.withPath("$.body.deep")
3062 }
3063
3064 result := v.validateValue(ctx, schema, map[string]any{"level": map[string]any{}})
3065 assert.Empty(t, result) // Should return early due to depth
3066 }
3067
3068 func TestStrictValidator_AnyOf_WithMatch(t *testing.T) {
3069 // Test validateAnyOf with a matching variant
3070 yml := `openapi: "3.1.0"
3071 info:
3072 title: Test
3073 version: "1.0"
3074 paths: {}
3075 components:
3076 schemas:
3077 Pet:
3078 type: object
3079 properties:
3080 id:
3081 type: string
3082 anyOf:
3083 - type: object
3084 properties:
3085 bark:
3086 type: boolean
3087 - type: object
3088 properties:
3089 meow:
3090 type: boolean
3091 `
3092 model := buildSchemaFromYAML(t, yml)
3093 schema := getSchema(t, model, "Pet")
3094
3095 opts := config.NewValidationOptions(config.WithStrictMode())
3096 v := NewValidator(opts, 3.1)
3097
3098 // Data that matches the first variant
3099 data := map[string]any{
3100 "id": "pet-123",
3101 "bark": true,
3102 "extra": "undeclared",
3103 }
3104
3105 result := v.Validate(Input{
3106 Schema: schema,
3107 Data: data,
3108 Direction: DirectionRequest,
3109 Options: opts,
3110 BasePath: "$.body",
3111 Version: 3.1,
3112 })
3113
3114 assert.False(t, result.Valid)
3115 assert.Len(t, result.UndeclaredValues, 1)
3116 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
3117 }
3118
3119 func TestStrictValidator_AnyOf_WithDiscriminator(t *testing.T) {
3120 // Test validateAnyOf with discriminator
3121 yml := `openapi: "3.1.0"
3122 info:
3123 title: Test
3124 version: "1.0"
3125 paths: {}
3126 components:
3127 schemas:
3128 Pet:
3129 type: object
3130 discriminator:
3131 propertyName: petType
3132 mapping:
3133 dog: '#/components/schemas/Dog'
3134 anyOf:
3135 - $ref: '#/components/schemas/Dog'
3136 - $ref: '#/components/schemas/Cat'
3137 Dog:
3138 type: object
3139 properties:
3140 petType:
3141 type: string
3142 bark:
3143 type: boolean
3144 Cat:
3145 type: object
3146 properties:
3147 petType:
3148 type: string
3149 meow:
3150 type: boolean
3151 `
3152 model := buildSchemaFromYAML(t, yml)
3153 schema := getSchema(t, model, "Pet")
3154
3155 opts := config.NewValidationOptions(config.WithStrictMode())
3156 v := NewValidator(opts, 3.1)
3157
3158 data := map[string]any{
3159 "petType": "dog",
3160 "bark": true,
3161 }
3162
3163 result := v.Validate(Input{
3164 Schema: schema,
3165 Data: data,
3166 Direction: DirectionRequest,
3167 Options: opts,
3168 BasePath: "$.body",
3169 Version: 3.1,
3170 })
3171
3172 assert.True(t, result.Valid)
3173 }
3174
3175 func TestStrictValidator_FindMatchingVariant_NilProxy(t *testing.T) {
3176 // Test findMatchingVariant with nil proxy in variants
3177 opts := config.NewValidationOptions(config.WithStrictMode())
3178 v := NewValidator(opts, 3.1)
3179
3180 // Create a slice with nil entry
3181 variants := []*base.SchemaProxy{nil}
3182
3183 result := v.findMatchingVariant(variants, map[string]any{"foo": "bar"})
3184 assert.Nil(t, result)
3185 }
3186
3187 func TestStrictValidator_ShouldReportUndeclaredForAllOf_AdditionalPropertiesFalse(t *testing.T) {
3188 // Test shouldReportUndeclaredForAllOf when parent has additionalProperties: false
3189 yml := `openapi: "3.1.0"
3190 info:
3191 title: Test
3192 version: "1.0"
3193 paths: {}
3194 components:
3195 schemas:
3196 Combined:
3197 type: object
3198 additionalProperties: false
3199 allOf:
3200 - type: object
3201 properties:
3202 name:
3203 type: string
3204 `
3205 model := buildSchemaFromYAML(t, yml)
3206 schema := getSchema(t, model, "Combined")
3207
3208 opts := config.NewValidationOptions(config.WithStrictMode())
3209 v := NewValidator(opts, 3.1)
3210
3211 // Should return false because parent has additionalProperties: false
3212 result := v.shouldReportUndeclaredForAllOf(schema)
3213 assert.False(t, result)
3214 }
3215
3216 func TestStrictValidator_ShouldReportUndeclaredForAllOf_AllOfHasAdditionalPropertiesFalse(t *testing.T) {
3217 // Test shouldReportUndeclaredForAllOf when allOf member has additionalProperties: false
3218 yml := `openapi: "3.1.0"
3219 info:
3220 title: Test
3221 version: "1.0"
3222 paths: {}
3223 components:
3224 schemas:
3225 Combined:
3226 type: object
3227 allOf:
3228 - type: object
3229 additionalProperties: false
3230 properties:
3231 name:
3232 type: string
3233 `
3234 model := buildSchemaFromYAML(t, yml)
3235 schema := getSchema(t, model, "Combined")
3236
3237 opts := config.NewValidationOptions(config.WithStrictMode())
3238 v := NewValidator(opts, 3.1)
3239
3240 // Should return false because allOf member has additionalProperties: false
3241 result := v.shouldReportUndeclaredForAllOf(schema)
3242 assert.False(t, result)
3243 }
3244
3245 func TestStrictValidator_FindPropertySchemaInAllOf_FromDeclared(t *testing.T) {
3246 // Test findPropertySchemaInAllOf finding property from declared map
3247 yml := `openapi: "3.1.0"
3248 info:
3249 title: Test
3250 version: "1.0"
3251 paths: {}
3252 components:
3253 schemas:
3254 User:
3255 type: object
3256 properties:
3257 name:
3258 type: string
3259 `
3260 model := buildSchemaFromYAML(t, yml)
3261 schema := getSchema(t, model, "User")
3262
3263 opts := config.NewValidationOptions(config.WithStrictMode())
3264 v := NewValidator(opts, 3.1)
3265
3266 // Create declared map with the property
3267 declared := make(map[string]*declaredProperty)
3268 declared["name"] = &declaredProperty{
3269 proxy: schema.Properties.GetOrZero("name"),
3270 }
3271
3272 result := v.findPropertySchemaInAllOf(nil, "name", declared)
3273 assert.NotNil(t, result)
3274 }
3275
3276 // Additional nil check tests
3277
3278 func TestStrictValidator_IsPropertyDeclaredInAllOf_NilSchemaProxy(t *testing.T) {
3279 opts := config.NewValidationOptions(config.WithStrictMode())
3280 v := NewValidator(opts, 3.1)
3281
3282 // Test with nil SchemaProxy in allOf slice
3283 allOf := []*base.SchemaProxy{nil}
3284 result := v.isPropertyDeclaredInAllOf(allOf, "foo")
3285 assert.False(t, result)
3286 }
3287
3288 func TestStrictValidator_IsPropertyDeclaredInAllOf_NilSchema(t *testing.T) {
3289 opts := config.NewValidationOptions(config.WithStrictMode())
3290 v := NewValidator(opts, 3.1)
3291
3292 // Test with empty allOf
3293 result := v.isPropertyDeclaredInAllOf(nil, "foo")
3294 assert.False(t, result)
3295 }
3296
3297 func TestStrictValidator_ShouldReportUndeclaredForAllOf_NilSchemaProxy(t *testing.T) {
3298 yml := `openapi: "3.1.0"
3299 info:
3300 title: Test
3301 version: "1.0"
3302 paths: {}
3303 components:
3304 schemas:
3305 Test:
3306 type: object
3307 allOf:
3308 - type: object
3309 properties:
3310 name:
3311 type: string
3312 `
3313 model := buildSchemaFromYAML(t, yml)
3314 schema := getSchema(t, model, "Test")
3315
3316 // Manually inject a nil into allOf to test the nil check
3317 schema.AllOf = append(schema.AllOf, nil)
3318
3319 opts := config.NewValidationOptions(config.WithStrictMode())
3320 v := NewValidator(opts, 3.1)
3321
3322 // Should still work and return true (default behavior)
3323 result := v.shouldReportUndeclaredForAllOf(schema)
3324 assert.True(t, result)
3325 }
3326
3327 func TestStrictValidator_FindPropertySchemaInAllOf_NilSchemaProxy(t *testing.T) {
3328 opts := config.NewValidationOptions(config.WithStrictMode())
3329 v := NewValidator(opts, 3.1)
3330
3331 // Test with nil SchemaProxy in allOf
3332 allOf := []*base.SchemaProxy{nil}
3333 result := v.findPropertySchemaInAllOf(allOf, "foo", nil)
3334 assert.Nil(t, result)
3335 }
3336
3337 func TestStrictValidator_RecurseIntoAllOfDeclaredProperties_NilSchemaProxy(t *testing.T) {
3338 opts := config.NewValidationOptions(config.WithStrictMode())
3339 v := NewValidator(opts, 3.1)
3340
3341 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3342 allOf := []*base.SchemaProxy{nil}
3343 data := map[string]any{"foo": "bar"}
3344
3345 result := v.recurseIntoAllOfDeclaredProperties(ctx, allOf, data, nil)
3346 assert.Empty(t, result)
3347 }
3348
3349 func TestStrictValidator_SelectByDiscriminator_NilDiscriminator(t *testing.T) {
3350 yml := `openapi: "3.1.0"
3351 info:
3352 title: Test
3353 version: "1.0"
3354 paths: {}
3355 components:
3356 schemas:
3357 Test:
3358 type: object
3359 properties:
3360 name:
3361 type: string
3362 `
3363 model := buildSchemaFromYAML(t, yml)
3364 schema := getSchema(t, model, "Test")
3365
3366 opts := config.NewValidationOptions(config.WithStrictMode())
3367 v := NewValidator(opts, 3.1)
3368
3369 // Schema has no discriminator
3370 result := v.selectByDiscriminator(schema, nil, map[string]any{"foo": "bar"})
3371 assert.Nil(t, result)
3372 }
3373
3374 func TestStrictValidator_SelectByDiscriminator_EmptyPropertyName(t *testing.T) {
3375 yml := `openapi: "3.1.0"
3376 info:
3377 title: Test
3378 version: "1.0"
3379 paths: {}
3380 components:
3381 schemas:
3382 Pet:
3383 type: object
3384 discriminator:
3385 propertyName: ""
3386 oneOf:
3387 - $ref: '#/components/schemas/Dog'
3388 Dog:
3389 type: object
3390 properties:
3391 bark:
3392 type: boolean
3393 `
3394 model := buildSchemaFromYAML(t, yml)
3395 schema := getSchema(t, model, "Pet")
3396
3397 opts := config.NewValidationOptions(config.WithStrictMode())
3398 v := NewValidator(opts, 3.1)
3399
3400 result := v.selectByDiscriminator(schema, schema.OneOf, map[string]any{"petType": "Dog"})
3401 assert.Nil(t, result)
3402 }
3403
3404 func TestStrictValidator_SelectByDiscriminator_MissingDiscriminatorValue(t *testing.T) {
3405 yml := `openapi: "3.1.0"
3406 info:
3407 title: Test
3408 version: "1.0"
3409 paths: {}
3410 components:
3411 schemas:
3412 Pet:
3413 type: object
3414 discriminator:
3415 propertyName: petType
3416 oneOf:
3417 - $ref: '#/components/schemas/Dog'
3418 Dog:
3419 type: object
3420 properties:
3421 bark:
3422 type: boolean
3423 `
3424 model := buildSchemaFromYAML(t, yml)
3425 schema := getSchema(t, model, "Pet")
3426
3427 opts := config.NewValidationOptions(config.WithStrictMode())
3428 v := NewValidator(opts, 3.1)
3429
3430 // Data doesn't have the discriminator property
3431 result := v.selectByDiscriminator(schema, schema.OneOf, map[string]any{"bark": true})
3432 assert.Nil(t, result)
3433 }
3434
3435 func TestStrictValidator_SelectByDiscriminator_NonStringValue(t *testing.T) {
3436 yml := `openapi: "3.1.0"
3437 info:
3438 title: Test
3439 version: "1.0"
3440 paths: {}
3441 components:
3442 schemas:
3443 Pet:
3444 type: object
3445 discriminator:
3446 propertyName: petType
3447 oneOf:
3448 - $ref: '#/components/schemas/Dog'
3449 Dog:
3450 type: object
3451 properties:
3452 bark:
3453 type: boolean
3454 `
3455 model := buildSchemaFromYAML(t, yml)
3456 schema := getSchema(t, model, "Pet")
3457
3458 opts := config.NewValidationOptions(config.WithStrictMode())
3459 v := NewValidator(opts, 3.1)
3460
3461 // Discriminator value is not a string
3462 result := v.selectByDiscriminator(schema, schema.OneOf, map[string]any{"petType": 123})
3463 assert.Nil(t, result)
3464 }
3465
3466 func TestStrictValidator_SelectByDiscriminator_NoMatchingVariant(t *testing.T) {
3467 yml := `openapi: "3.1.0"
3468 info:
3469 title: Test
3470 version: "1.0"
3471 paths: {}
3472 components:
3473 schemas:
3474 Pet:
3475 type: object
3476 discriminator:
3477 propertyName: petType
3478 oneOf:
3479 - $ref: '#/components/schemas/Dog'
3480 Dog:
3481 type: object
3482 properties:
3483 bark:
3484 type: boolean
3485 `
3486 model := buildSchemaFromYAML(t, yml)
3487 schema := getSchema(t, model, "Pet")
3488
3489 opts := config.NewValidationOptions(config.WithStrictMode())
3490 v := NewValidator(opts, 3.1)
3491
3492 // Discriminator value doesn't match any variant
3493 result := v.selectByDiscriminator(schema, schema.OneOf, map[string]any{"petType": "Cat"})
3494 assert.Nil(t, result)
3495 }
3496
3497 func TestStrictValidator_FindMatchingVariant_NoMatch2(t *testing.T) {
3498 yml := `openapi: "3.1.0"
3499 info:
3500 title: Test
3501 version: "1.0"
3502 paths: {}
3503 components:
3504 schemas:
3505 Dog:
3506 type: object
3507 required:
3508 - bark
3509 properties:
3510 bark:
3511 type: boolean
3512 `
3513 model := buildSchemaFromYAML(t, yml)
3514 schema := getSchema(t, model, "Dog")
3515
3516 opts := config.NewValidationOptions(config.WithStrictMode())
3517 v := NewValidator(opts, 3.1)
3518
3519 // Create variants with a schema that won't match the data
3520 variants := []*base.SchemaProxy{base.CreateSchemaProxy(schema)}
3521
3522 // Data doesn't have required 'bark' property - won't match
3523 result := v.findMatchingVariant(variants, map[string]any{"meow": true})
3524 assert.Nil(t, result)
3525 }
3526
3527 func TestStrictValidator_CollectDeclaredProperties_NilSchema(t *testing.T) {
3528 opts := config.NewValidationOptions(config.WithStrictMode())
3529 v := NewValidator(opts, 3.1)
3530
3531 declared, patterns := v.collectDeclaredProperties(nil, nil)
3532 assert.Empty(t, declared)
3533 assert.Empty(t, patterns)
3534 }
3535
3536 func TestStrictValidator_GetDeclaredPropertyNames_Empty(t *testing.T) {
3537 result := getDeclaredPropertyNames(nil)
3538 assert.Empty(t, result)
3539 }
3540
3541 func TestStrictValidator_ShouldSkipProperty_NilSchema(t *testing.T) {
3542 opts := config.NewValidationOptions(config.WithStrictMode())
3543 v := NewValidator(opts, 3.1)
3544
3545 result := v.shouldSkipProperty(nil, DirectionRequest)
3546 assert.False(t, result)
3547 }
3548
3549 func TestStrictValidator_ValidateObject_NilProperties(t *testing.T) {
3550 yml := `openapi: "3.1.0"
3551 info:
3552 title: Test
3553 version: "1.0"
3554 paths: {}
3555 components:
3556 schemas:
3557 Empty:
3558 type: object
3559 `
3560 model := buildSchemaFromYAML(t, yml)
3561 schema := getSchema(t, model, "Empty")
3562
3563 opts := config.NewValidationOptions(config.WithStrictMode())
3564 v := NewValidator(opts, 3.1)
3565
3566 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3567 result := v.validateObject(ctx, schema, map[string]any{"foo": "bar"})
3568
3569 // In strict mode, empty schema with no properties still reports undeclared
3570 // because additionalProperties defaults to true (meaning strict mode catches it)
3571 assert.Len(t, result, 1)
3572 assert.Equal(t, "foo", result[0].Name)
3573 }
3574
3575 func TestStrictValidator_ShouldReportUndeclared_NilSchema(t *testing.T) {
3576 opts := config.NewValidationOptions(config.WithStrictMode())
3577 v := NewValidator(opts, 3.1)
3578
3579 // nil schema returns false - can't report undeclared without schema
3580 result := v.shouldReportUndeclared(nil)
3581 assert.False(t, result)
3582 }
3583
3584 func TestStrictValidator_GetPatternPropertySchema_NoPatterns(t *testing.T) {
3585 yml := `openapi: "3.1.0"
3586 info:
3587 title: Test
3588 version: "1.0"
3589 paths: {}
3590 components:
3591 schemas:
3592 NoPatterns:
3593 type: object
3594 properties:
3595 name:
3596 type: string
3597 `
3598 model := buildSchemaFromYAML(t, yml)
3599 schema := getSchema(t, model, "NoPatterns")
3600
3601 opts := config.NewValidationOptions(config.WithStrictMode())
3602 v := NewValidator(opts, 3.1)
3603
3604 // Schema has no patternProperties
3605 result := v.getPatternPropertySchema(schema, "foo")
3606 assert.Nil(t, result)
3607 }
3608
3609 func TestStrictValidator_RecurseIntoDeclaredProperties_EmptySchema(t *testing.T) {
3610 yml := `openapi: "3.1.0"
3611 info:
3612 title: Test
3613 version: "1.0"
3614 paths: {}
3615 components:
3616 schemas:
3617 Empty:
3618 type: object
3619 `
3620 model := buildSchemaFromYAML(t, yml)
3621 schema := getSchema(t, model, "Empty")
3622
3623 opts := config.NewValidationOptions(config.WithStrictMode())
3624 v := NewValidator(opts, 3.1)
3625
3626 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3627 data := map[string]any{"name": "test"}
3628
3629 // recurseIntoDeclaredProperties only takes ctx, schema, data
3630 result := v.recurseIntoDeclaredProperties(ctx, schema, data)
3631 assert.Empty(t, result)
3632 }
3633
3634 func TestStrictValidator_ValidateArray_NilItems(t *testing.T) {
3635 yml := `openapi: "3.1.0"
3636 info:
3637 title: Test
3638 version: "1.0"
3639 paths: {}
3640 components:
3641 schemas:
3642 List:
3643 type: array
3644 `
3645 model := buildSchemaFromYAML(t, yml)
3646 schema := getSchema(t, model, "List")
3647
3648 opts := config.NewValidationOptions(config.WithStrictMode())
3649 v := NewValidator(opts, 3.1)
3650
3651 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3652 result := v.validateArray(ctx, schema, []any{"foo", "bar"})
3653
3654 // Array with no items schema - anything is allowed
3655 assert.Empty(t, result)
3656 }
3657
3658 func TestStrictValidator_ValidateArray_ItemsSchemaB(t *testing.T) {
3659 yml := `openapi: "3.1.0"
3660 info:
3661 title: Test
3662 version: "1.0"
3663 paths: {}
3664 components:
3665 schemas:
3666 List:
3667 type: array
3668 items: true
3669 `
3670 model := buildSchemaFromYAML(t, yml)
3671 schema := getSchema(t, model, "List")
3672
3673 opts := config.NewValidationOptions(config.WithStrictMode())
3674 v := NewValidator(opts, 3.1)
3675
3676 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3677 result := v.validateArray(ctx, schema, []any{"foo", "bar"})
3678
3679 // items: true means all items are valid
3680 assert.Empty(t, result)
3681 }
3682
3683 func TestStrictValidator_ValidateArray_PrefixItemsNil(t *testing.T) {
3684 yml := `openapi: "3.1.0"
3685 info:
3686 title: Test
3687 version: "1.0"
3688 paths: {}
3689 components:
3690 schemas:
3691 Tuple:
3692 type: array
3693 prefixItems:
3694 - type: string
3695 - type: integer
3696 `
3697 model := buildSchemaFromYAML(t, yml)
3698 schema := getSchema(t, model, "Tuple")
3699
3700 // Manually set one prefixItem to nil to test the nil check
3701 schema.PrefixItems = append(schema.PrefixItems, nil)
3702
3703 opts := config.NewValidationOptions(config.WithStrictMode())
3704 v := NewValidator(opts, 3.1)
3705
3706 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3707 result := v.validateArray(ctx, schema, []any{"foo", 42, "extra"})
3708
3709 // Should handle nil prefixItems gracefully
3710 assert.Empty(t, result)
3711 }
3712
3713 func TestStrictValidator_FindPropertySchemaInMerged_NilProxy(t *testing.T) {
3714 opts := config.NewValidationOptions(config.WithStrictMode())
3715 v := NewValidator(opts, 3.1)
3716
3717 // Create declared map with nil proxy
3718 declared := make(map[string]*declaredProperty)
3719 declared["name"] = &declaredProperty{proxy: nil}
3720
3721 // findPropertySchemaInMerged takes (variant, parent, propName, declared)
3722 result := v.findPropertySchemaInMerged(nil, nil, "name", declared)
3723 assert.Nil(t, result)
3724 }
3725
3726 func TestStrictValidator_RecurseIntoDeclaredPropertiesWithMerged_NilProxy(t *testing.T) {
3727 opts := config.NewValidationOptions(config.WithStrictMode())
3728 v := NewValidator(opts, 3.1)
3729
3730 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3731
3732 // Create declared with nil proxy
3733 declared := make(map[string]*declaredProperty)
3734 declared["name"] = &declaredProperty{proxy: nil}
3735
3736 data := map[string]any{"name": "test"}
3737
3738 // recurseIntoDeclaredPropertiesWithMerged takes (ctx, variant, parent, data, declared)
3739 result := v.recurseIntoDeclaredPropertiesWithMerged(ctx, nil, nil, data, declared)
3740 assert.Empty(t, result)
3741 }
3742
3743 func TestStrictValidator_ValidateAnyOf_NoMatchingVariant(t *testing.T) {
3744 yml := `openapi: "3.1.0"
3745 info:
3746 title: Test
3747 version: "1.0"
3748 paths: {}
3749 components:
3750 schemas:
3751 StringOrInt:
3752 anyOf:
3753 - type: string
3754 minLength: 5
3755 - type: integer
3756 minimum: 10
3757 `
3758 model := buildSchemaFromYAML(t, yml)
3759 schema := getSchema(t, model, "StringOrInt")
3760
3761 opts := config.NewValidationOptions(config.WithStrictMode())
3762 v := NewValidator(opts, 3.1)
3763
3764 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
3765
3766 // Data is an object which won't match string or integer
3767 result := v.validateAnyOf(ctx, schema, map[string]any{"foo": "bar"})
3768
3769 // Should return empty - no matching variant means we can't validate
3770 assert.Empty(t, result)
3771 }
3772
3773 func TestStrictValidator_CompilePattern_EmptyPattern(t *testing.T) {
3774 // Test compilePattern with empty pattern
3775 result := compilePattern("")
3776 assert.Nil(t, result)
3777 }
3778
3779 func TestStrictValidator_GetSchemaKey_NoLowLevel(t *testing.T) {
3780 opts := config.NewValidationOptions(config.WithStrictMode())
3781 v := NewValidator(opts, 3.1)
3782
3783 // Create a schema without low-level info
3784 schema := &base.Schema{}
3785
3786 key := v.getSchemaKey(schema)
3787 // Should return pointer-based key
3788 assert.NotEmpty(t, key)
3789 }
3790
3791 func TestTruncateValue_SmallMapUnchanged(t *testing.T) {
3792 // Small map (<= 3 entries) should return unchanged
3793 input := map[string]any{"a": 1, "b": 2}
3794 result := TruncateValue(input)
3795 assert.Equal(t, input, result)
3796
3797 // Exactly 3 entries should also pass unchanged
3798 input3 := map[string]any{"a": 1, "b": 2, "c": 3}
3799 result3 := TruncateValue(input3)
3800 assert.Equal(t, input3, result3)
3801 }
3802
3803 func TestTruncateValue_SmallArrayUnchanged(t *testing.T) {
3804 // Small array (<= 3 entries) should return unchanged
3805 input := []any{1, 2}
3806 result := TruncateValue(input)
3807 assert.Equal(t, input, result)
3808
3809 // Exactly 3 entries should also pass unchanged
3810 input3 := []any{1, 2, 3}
3811 result3 := TruncateValue(input3)
3812 assert.Equal(t, input3, result3)
3813 }
3814
3815 func TestStrictValidator_DataMatchesSchema_CompilationError(t *testing.T) {
3816 // Create a schema with an invalid regex pattern that will fail compilation
3817 yml := `openapi: "3.1.0"
3818 info:
3819 title: Test
3820 version: "1.0"
3821 paths: {}
3822 components:
3823 schemas:
3824 BadPattern:
3825 type: object
3826 properties:
3827 name:
3828 type: string
3829 pattern: "[invalid(regex"
3830 `
3831 model := buildSchemaFromYAML(t, yml)
3832 schema := getSchema(t, model, "BadPattern")
3833
3834 opts := config.NewValidationOptions(config.WithStrictMode())
3835 v := NewValidator(opts, 3.1)
3836
3837 // dataMatchesSchema should return false with error due to invalid pattern
3838 matches, err := v.dataMatchesSchema(schema, map[string]any{"name": "test"})
3839 assert.False(t, matches)
3840 assert.Error(t, err)
3841 assert.Contains(t, err.Error(), "strict:")
3842 }
3843
3844 func TestStrictValidator_FindMatchingVariant_SchemaError(t *testing.T) {
3845 // Create oneOf with a variant that has invalid pattern - should skip bad variant
3846 yml := `openapi: "3.1.0"
3847 info:
3848 title: Test
3849 version: "1.0"
3850 paths: {}
3851 components:
3852 schemas:
3853 Container:
3854 oneOf:
3855 - type: object
3856 properties:
3857 valid:
3858 type: string
3859 - type: object
3860 properties:
3861 broken:
3862 type: string
3863 pattern: "[unclosed("
3864 `
3865 model := buildSchemaFromYAML(t, yml)
3866 schema := getSchema(t, model, "Container")
3867
3868 opts := config.NewValidationOptions(config.WithStrictMode())
3869 v := NewValidator(opts, 3.1)
3870
3871 // findMatchingVariant should skip the broken variant and match the valid one
3872 variant := v.findMatchingVariant(schema.OneOf, map[string]any{"valid": "test"})
3873
3874 // Should find a valid variant (the first one)
3875 assert.NotNil(t, variant)
3876 }
3877
3878 func TestStrictValidator_GetPatternPropertySchema_InvalidPattern(t *testing.T) {
3879 // Create schema with invalid patternProperties regex
3880 yml := `openapi: "3.1.0"
3881 info:
3882 title: Test
3883 version: "1.0"
3884 paths: {}
3885 components:
3886 schemas:
3887 BadPatternProps:
3888 type: object
3889 patternProperties:
3890 "[invalid(":
3891 type: string
3892 `
3893 model := buildSchemaFromYAML(t, yml)
3894 schema := getSchema(t, model, "BadPatternProps")
3895
3896 opts := config.NewValidationOptions(config.WithStrictMode())
3897 v := NewValidator(opts, 3.1)
3898
3899 // getPatternPropertySchema should return nil for invalid pattern
3900 propProxy := v.getPatternPropertySchema(schema, "test")
3901 assert.Nil(t, propProxy)
3902 }
3903
3904 // =============================================================================
3905 // Phase 1: CRITICAL Coverage Tests
3906 // =============================================================================
3907
3908 func TestStrictValidator_AllOfWithParentProperties(t *testing.T) {
3909 // Covers polymorphic.go:88-91 - parent schema properties merged with allOf
3910 yml := `openapi: "3.1.0"
3911 info:
3912 title: Test
3913 version: "1.0"
3914 paths: {}
3915 components:
3916 schemas:
3917 MergedSchema:
3918 type: object
3919 properties:
3920 parentProp:
3921 type: string
3922 allOf:
3923 - type: object
3924 properties:
3925 childProp:
3926 type: string
3927 `
3928 model := buildSchemaFromYAML(t, yml)
3929 schema := getSchema(t, model, "MergedSchema")
3930
3931 opts := config.NewValidationOptions(config.WithStrictMode())
3932 v := NewValidator(opts, 3.1)
3933
3934 // Both parent and child properties should be considered declared
3935 data := map[string]any{
3936 "parentProp": "from parent",
3937 "childProp": "from child",
3938 }
3939
3940 result := v.Validate(Input{
3941 Schema: schema,
3942 Data: data,
3943 Direction: DirectionRequest,
3944 Options: opts,
3945 BasePath: "$.body",
3946 Version: 3.1,
3947 })
3948
3949 assert.True(t, result.Valid)
3950 assert.Empty(t, result.UndeclaredValues)
3951 }
3952
3953 func TestStrictValidator_AllOfWithParentProperties_UndeclaredReported(t *testing.T) {
3954 // Verify undeclared properties are still caught with parent+allOf merge
3955 yml := `openapi: "3.1.0"
3956 info:
3957 title: Test
3958 version: "1.0"
3959 paths: {}
3960 components:
3961 schemas:
3962 MergedSchema:
3963 type: object
3964 properties:
3965 parentProp:
3966 type: string
3967 allOf:
3968 - type: object
3969 properties:
3970 childProp:
3971 type: string
3972 `
3973 model := buildSchemaFromYAML(t, yml)
3974 schema := getSchema(t, model, "MergedSchema")
3975
3976 opts := config.NewValidationOptions(config.WithStrictMode())
3977 v := NewValidator(opts, 3.1)
3978
3979 data := map[string]any{
3980 "parentProp": "from parent",
3981 "childProp": "from child",
3982 "undeclaredProp": "should be reported",
3983 }
3984
3985 result := v.Validate(Input{
3986 Schema: schema,
3987 Data: data,
3988 Direction: DirectionRequest,
3989 Options: opts,
3990 BasePath: "$.body",
3991 Version: 3.1,
3992 })
3993
3994 assert.False(t, result.Valid)
3995 assert.Len(t, result.UndeclaredValues, 1)
3996 assert.Equal(t, "undeclaredProp", result.UndeclaredValues[0].Name)
3997 }
3998
3999 func TestStrictValidator_AllOfReadOnlyInRequest(t *testing.T) {
4000 // Covers polymorphic.go:116-117 - shouldSkipProperty for readOnly in allOf
4001 yml := `openapi: "3.1.0"
4002 info:
4003 title: Test
4004 version: "1.0"
4005 paths: {}
4006 components:
4007 schemas:
4008 ReadOnlyAllOf:
4009 type: object
4010 allOf:
4011 - type: object
4012 properties:
4013 id:
4014 type: string
4015 readOnly: true
4016 name:
4017 type: string
4018 `
4019 model := buildSchemaFromYAML(t, yml)
4020 schema := getSchema(t, model, "ReadOnlyAllOf")
4021
4022 opts := config.NewValidationOptions(config.WithStrictMode())
4023 v := NewValidator(opts, 3.1)
4024
4025 // In request direction, readOnly property should be skipped
4026 data := map[string]any{
4027 "id": "123",
4028 "name": "test",
4029 }
4030
4031 result := v.Validate(Input{
4032 Schema: schema,
4033 Data: data,
4034 Direction: DirectionRequest,
4035 Options: opts,
4036 BasePath: "$.body",
4037 Version: 3.1,
4038 })
4039
4040 // id is readOnly - should be skipped in request validation (not flagged)
4041 assert.True(t, result.Valid)
4042 assert.Empty(t, result.UndeclaredValues)
4043 }
4044
4045 func TestStrictValidator_AllOfWriteOnlyInResponse(t *testing.T) {
4046 // Covers polymorphic.go:222-223 - shouldSkipProperty for writeOnly in oneOf/anyOf
4047 yml := `openapi: "3.1.0"
4048 info:
4049 title: Test
4050 version: "1.0"
4051 paths: {}
4052 components:
4053 schemas:
4054 WriteOnlySchema:
4055 type: object
4056 oneOf:
4057 - type: object
4058 properties:
4059 password:
4060 type: string
4061 writeOnly: true
4062 email:
4063 type: string
4064 `
4065 model := buildSchemaFromYAML(t, yml)
4066 schema := getSchema(t, model, "WriteOnlySchema")
4067
4068 opts := config.NewValidationOptions(config.WithStrictMode())
4069 v := NewValidator(opts, 3.1)
4070
4071 // In response direction, writeOnly property should be skipped
4072 data := map[string]any{
4073 "password": "secret123",
4074 "email": "[email protected]",
4075 }
4076
4077 result := v.Validate(Input{
4078 Schema: schema,
4079 Data: data,
4080 Direction: DirectionResponse,
4081 Options: opts,
4082 BasePath: "$.body",
4083 Version: 3.1,
4084 })
4085
4086 // password is writeOnly - should be skipped in response validation
4087 assert.True(t, result.Valid)
4088 assert.Empty(t, result.UndeclaredValues)
4089 }
4090
4091 func TestStrictValidator_AllOfWithIgnoredPath(t *testing.T) {
4092 // Covers polymorphic.go:107-108 - shouldIgnore in allOf validation loop
4093 yml := `openapi: "3.1.0"
4094 info:
4095 title: Test
4096 version: "1.0"
4097 paths: {}
4098 components:
4099 schemas:
4100 IgnoreInAllOf:
4101 type: object
4102 allOf:
4103 - type: object
4104 properties:
4105 data:
4106 type: object
4107 properties:
4108 visible:
4109 type: string
4110 `
4111 model := buildSchemaFromYAML(t, yml)
4112 schema := getSchema(t, model, "IgnoreInAllOf")
4113
4114 opts := config.NewValidationOptions(
4115 config.WithStrictMode(),
4116 config.WithStrictIgnorePaths("$.body.data.metadata"),
4117 )
4118 v := NewValidator(opts, 3.1)
4119
4120 // metadata path is ignored, so undeclared properties there should not be reported
4121 data := map[string]any{
4122 "data": map[string]any{
4123 "visible": "ok",
4124 "metadata": map[string]any{
4125 "ignored": "should not be flagged",
4126 "alsoIgnored": "also not flagged",
4127 },
4128 },
4129 }
4130
4131 result := v.Validate(Input{
4132 Schema: schema,
4133 Data: data,
4134 Direction: DirectionRequest,
4135 Options: opts,
4136 BasePath: "$.body",
4137 Version: 3.1,
4138 })
4139
4140 // metadata path is ignored, so no undeclared errors
4141 assert.True(t, result.Valid)
4142 assert.Empty(t, result.UndeclaredValues)
4143 }
4144
4145 func TestStrictValidator_OneOfWithIgnoredPath(t *testing.T) {
4146 // Covers polymorphic.go:213-214 - shouldIgnore in oneOf/anyOf validation loop
4147 yml := `openapi: "3.1.0"
4148 info:
4149 title: Test
4150 version: "1.0"
4151 paths: {}
4152 components:
4153 schemas:
4154 IgnoreInOneOf:
4155 type: object
4156 oneOf:
4157 - type: object
4158 properties:
4159 data:
4160 type: object
4161 properties:
4162 name:
4163 type: string
4164 `
4165 model := buildSchemaFromYAML(t, yml)
4166 schema := getSchema(t, model, "IgnoreInOneOf")
4167
4168 opts := config.NewValidationOptions(
4169 config.WithStrictMode(),
4170 config.WithStrictIgnorePaths("$.body.data.internal"),
4171 )
4172 v := NewValidator(opts, 3.1)
4173
4174 data := map[string]any{
4175 "data": map[string]any{
4176 "name": "visible",
4177 "internal": map[string]any{
4178 "secret": "ignored",
4179 },
4180 },
4181 }
4182
4183 result := v.Validate(Input{
4184 Schema: schema,
4185 Data: data,
4186 Direction: DirectionRequest,
4187 Options: opts,
4188 BasePath: "$.body",
4189 Version: 3.1,
4190 })
4191
4192 assert.True(t, result.Valid)
4193 assert.Empty(t, result.UndeclaredValues)
4194 }
4195
4196 func TestStrictValidator_OneOfWithIgnoredTopLevelProperty(t *testing.T) {
4197 // Covers polymorphic.go:213-214 - shouldIgnore at TOP LEVEL of oneOf iteration
4198 yml := `openapi: "3.1.0"
4199 info:
4200 title: Test
4201 version: "1.0"
4202 paths: {}
4203 components:
4204 schemas:
4205 OneOfIgnoreTopLevel:
4206 type: object
4207 oneOf:
4208 - type: object
4209 properties:
4210 name:
4211 type: string
4212 internal:
4213 type: object
4214 `
4215 model := buildSchemaFromYAML(t, yml)
4216 schema := getSchema(t, model, "OneOfIgnoreTopLevel")
4217
4218 // Ignore "internal" property at top level - this directly hits line 214
4219 opts := config.NewValidationOptions(
4220 config.WithStrictMode(),
4221 config.WithStrictIgnorePaths("$.body.internal"),
4222 )
4223 v := NewValidator(opts, 3.1)
4224
4225 data := map[string]any{
4226 "name": "visible",
4227 "internal": map[string]any{
4228 "anything": "should be ignored entirely",
4229 },
4230 }
4231
4232 result := v.Validate(Input{
4233 Schema: schema,
4234 Data: data,
4235 Direction: DirectionRequest,
4236 Options: opts,
4237 BasePath: "$.body",
4238 Version: 3.1,
4239 })
4240
4241 // internal property is ignored at top level, no errors
4242 assert.True(t, result.Valid)
4243 assert.Empty(t, result.UndeclaredValues)
4244 }
4245
4246 func TestStrictValidator_FindPropertySchemaInMerged_VariantProperty(t *testing.T) {
4247 // Covers polymorphic.go:248-249 - property found in variant's explicit properties
4248 yml := `openapi: "3.1.0"
4249 info:
4250 title: Test
4251 version: "1.0"
4252 paths: {}
4253 components:
4254 schemas:
4255 OneOfVariantProp:
4256 type: object
4257 properties:
4258 parentProp:
4259 type: string
4260 oneOf:
4261 - type: object
4262 properties:
4263 variantProp:
4264 type: string
4265 `
4266 model := buildSchemaFromYAML(t, yml)
4267 schema := getSchema(t, model, "OneOfVariantProp")
4268
4269 opts := config.NewValidationOptions(config.WithStrictMode())
4270 v := NewValidator(opts, 3.1)
4271
4272 // variantProp is defined in variant, should be found via line 249
4273 data := map[string]any{
4274 "parentProp": "parent",
4275 "variantProp": "variant",
4276 }
4277
4278 result := v.Validate(Input{
4279 Schema: schema,
4280 Data: data,
4281 Direction: DirectionRequest,
4282 Options: opts,
4283 BasePath: "$.body",
4284 Version: 3.1,
4285 })
4286
4287 assert.True(t, result.Valid)
4288 assert.Empty(t, result.UndeclaredValues)
4289 }
4290
4291 func TestStrictValidator_FindPropertySchemaInMerged_ParentProperty(t *testing.T) {
4292 // Covers polymorphic.go:254-256 - property found in parent's explicit properties
4293 yml := `openapi: "3.1.0"
4294 info:
4295 title: Test
4296 version: "1.0"
4297 paths: {}
4298 components:
4299 schemas:
4300 OneOfParentProp:
4301 type: object
4302 properties:
4303 parentOnly:
4304 type: string
4305 oneOf:
4306 - type: object
4307 properties:
4308 variantOnly:
4309 type: string
4310 `
4311 model := buildSchemaFromYAML(t, yml)
4312 schema := getSchema(t, model, "OneOfParentProp")
4313
4314 opts := config.NewValidationOptions(config.WithStrictMode())
4315 v := NewValidator(opts, 3.1)
4316
4317 // parentOnly is NOT in variant, so findPropertySchemaInMerged falls through
4318 // to parent lookup at line 254-256
4319 data := map[string]any{
4320 "parentOnly": "from parent",
4321 "variantOnly": "from variant",
4322 }
4323
4324 result := v.Validate(Input{
4325 Schema: schema,
4326 Data: data,
4327 Direction: DirectionRequest,
4328 Options: opts,
4329 BasePath: "$.body",
4330 Version: 3.1,
4331 })
4332
4333 assert.True(t, result.Valid)
4334 assert.Empty(t, result.UndeclaredValues)
4335 }
4336
4337 func TestStrictValidator_FindPropertySchemaInMerged_VariantDirect(t *testing.T) {
4338 // Covers polymorphic.go:247-249 - direct test with empty declared map
4339 yml := `openapi: "3.1.0"
4340 info:
4341 title: Test
4342 version: "1.0"
4343 paths: {}
4344 components:
4345 schemas:
4346 Variant:
4347 type: object
4348 properties:
4349 variantProp:
4350 type: string
4351 `
4352 model := buildSchemaFromYAML(t, yml)
4353 variant := getSchema(t, model, "Variant")
4354
4355 opts := config.NewValidationOptions(config.WithStrictMode())
4356 v := NewValidator(opts, 3.1)
4357
4358 // Call with empty declared map - forces lookup in variant.Properties (line 247-249)
4359 result := v.findPropertySchemaInMerged(variant, nil, "variantProp", make(map[string]*declaredProperty))
4360 assert.NotNil(t, result)
4361 }
4362
4363 func TestStrictValidator_FindPropertySchemaInMerged_ParentDirect(t *testing.T) {
4364 // Covers polymorphic.go:254-256 - direct test with empty declared map, no variant
4365 yml := `openapi: "3.1.0"
4366 info:
4367 title: Test
4368 version: "1.0"
4369 paths: {}
4370 components:
4371 schemas:
4372 Parent:
4373 type: object
4374 properties:
4375 parentProp:
4376 type: string
4377 `
4378 model := buildSchemaFromYAML(t, yml)
4379 parent := getSchema(t, model, "Parent")
4380
4381 opts := config.NewValidationOptions(config.WithStrictMode())
4382 v := NewValidator(opts, 3.1)
4383
4384 // Call with nil variant and empty declared - forces lookup in parent.Properties (line 254-256)
4385 result := v.findPropertySchemaInMerged(nil, parent, "parentProp", make(map[string]*declaredProperty))
4386 assert.NotNil(t, result)
4387 }
4388
4389 func TestStrictValidator_FindPropertySchemaInAllOf_FromAllOfSchema(t *testing.T) {
4390 // Covers polymorphic.go:437-439 - property found in allOf schema's explicit properties
4391 yml := `openapi: "3.1.0"
4392 info:
4393 title: Test
4394 version: "1.0"
4395 paths: {}
4396 components:
4397 schemas:
4398 AllOfExplicitProp:
4399 type: object
4400 allOf:
4401 - type: object
4402 properties:
4403 fromAllOf:
4404 type: object
4405 properties:
4406 nested:
4407 type: string
4408 `
4409 model := buildSchemaFromYAML(t, yml)
4410 schema := getSchema(t, model, "AllOfExplicitProp")
4411
4412 opts := config.NewValidationOptions(config.WithStrictMode())
4413 v := NewValidator(opts, 3.1)
4414
4415 // fromAllOf is in allOf schema, findPropertySchemaInAllOf should find it
4416 // and recurse into nested object to detect undeclared
4417 data := map[string]any{
4418 "fromAllOf": map[string]any{
4419 "nested": "valid",
4420 "undeclared": "should be flagged",
4421 },
4422 }
4423
4424 result := v.Validate(Input{
4425 Schema: schema,
4426 Data: data,
4427 Direction: DirectionRequest,
4428 Options: opts,
4429 BasePath: "$.body",
4430 Version: 3.1,
4431 })
4432
4433 // undeclared in nested object should be reported
4434 assert.False(t, result.Valid)
4435 assert.Len(t, result.UndeclaredValues, 1)
4436 assert.Equal(t, "undeclared", result.UndeclaredValues[0].Name)
4437 }
4438
4439 func TestStrictValidator_FindPropertySchemaInAllOf_Direct(t *testing.T) {
4440 // Covers polymorphic.go:437-439 - direct test with empty declared map
4441 yml := `openapi: "3.1.0"
4442 info:
4443 title: Test
4444 version: "1.0"
4445 paths: {}
4446 components:
4447 schemas:
4448 AllOfSchema:
4449 type: object
4450 allOf:
4451 - type: object
4452 properties:
4453 allOfProp:
4454 type: string
4455 `
4456 model := buildSchemaFromYAML(t, yml)
4457 schema := getSchema(t, model, "AllOfSchema")
4458
4459 opts := config.NewValidationOptions(config.WithStrictMode())
4460 v := NewValidator(opts, 3.1)
4461
4462 // Call with empty declared map - forces lookup in allOf schemas (line 437-439)
4463 result := v.findPropertySchemaInAllOf(schema.AllOf, "allOfProp", make(map[string]*declaredProperty))
4464 assert.NotNil(t, result)
4465 }
4466
4467 func TestStrictValidator_RecurseIntoAllOfDeclaredProperties_ShouldIgnore(t *testing.T) {
4468 // Covers polymorphic.go:455-456 - shouldIgnore in recurseIntoAllOfDeclaredProperties
4469 yml := `openapi: "3.1.0"
4470 info:
4471 title: Test
4472 version: "1.0"
4473 paths: {}
4474 components:
4475 schemas:
4476 AllOfIgnore:
4477 type: object
4478 additionalProperties: false
4479 allOf:
4480 - type: object
4481 additionalProperties: false
4482 properties:
4483 name:
4484 type: string
4485 metadata:
4486 type: object
4487 `
4488 model := buildSchemaFromYAML(t, yml)
4489 schema := getSchema(t, model, "AllOfIgnore")
4490
4491 // Ignore metadata at top level
4492 opts := config.NewValidationOptions(
4493 config.WithStrictMode(),
4494 config.WithStrictIgnorePaths("$.body.metadata"),
4495 )
4496 v := NewValidator(opts, 3.1)
4497
4498 // Both parent and allOf have additionalProperties: false,
4499 // so we go through recurseIntoAllOfDeclaredProperties
4500 // metadata is ignored at line 455-456
4501 data := map[string]any{
4502 "name": "test",
4503 "metadata": map[string]any{
4504 "anything": "ignored",
4505 },
4506 }
4507
4508 result := v.Validate(Input{
4509 Schema: schema,
4510 Data: data,
4511 Direction: DirectionRequest,
4512 Options: opts,
4513 BasePath: "$.body",
4514 Version: 3.1,
4515 })
4516
4517 assert.True(t, result.Valid)
4518 assert.Empty(t, result.UndeclaredValues)
4519 }
4520
4521 func TestStrictValidator_RecurseIntoAllOfDeclaredProperties_SkipReadOnly(t *testing.T) {
4522 // Covers polymorphic.go:461-462 - shouldSkipProperty in recurseIntoAllOfDeclaredProperties
4523 yml := `openapi: "3.1.0"
4524 info:
4525 title: Test
4526 version: "1.0"
4527 paths: {}
4528 components:
4529 schemas:
4530 AllOfReadOnly:
4531 type: object
4532 additionalProperties: false
4533 allOf:
4534 - type: object
4535 additionalProperties: false
4536 properties:
4537 name:
4538 type: string
4539 id:
4540 type: string
4541 readOnly: true
4542 `
4543 model := buildSchemaFromYAML(t, yml)
4544 schema := getSchema(t, model, "AllOfReadOnly")
4545
4546 opts := config.NewValidationOptions(config.WithStrictMode())
4547 v := NewValidator(opts, 3.1)
4548
4549 // Both parent and allOf have additionalProperties: false,
4550 // so we go through recurseIntoAllOfDeclaredProperties
4551 // id is readOnly and skipped in request direction (line 461-462)
4552 data := map[string]any{
4553 "name": "test",
4554 "id": "should-be-skipped",
4555 }
4556
4557 result := v.Validate(Input{
4558 Schema: schema,
4559 Data: data,
4560 Direction: DirectionRequest,
4561 Options: opts,
4562 BasePath: "$.body",
4563 Version: 3.1,
4564 })
4565
4566 assert.True(t, result.Valid)
4567 assert.Empty(t, result.UndeclaredValues)
4568 }
4569
4570 func TestStrictValidator_RecurseIntoDeclaredPropertiesWithMerged_SkipReadOnly(t *testing.T) {
4571 // Covers polymorphic.go:291-292 - shouldSkipProperty in recurseIntoDeclaredPropertiesWithMerged
4572 yml := `openapi: "3.1.0"
4573 info:
4574 title: Test
4575 version: "1.0"
4576 paths: {}
4577 components:
4578 schemas:
4579 OneOfWithReadOnly:
4580 type: object
4581 additionalProperties: false
4582 properties:
4583 name:
4584 type: string
4585 oneOf:
4586 - type: object
4587 additionalProperties: false
4588 properties:
4589 name:
4590 type: string
4591 id:
4592 type: string
4593 readOnly: true
4594 data:
4595 type: string
4596 `
4597 model := buildSchemaFromYAML(t, yml)
4598 schema := getSchema(t, model, "OneOfWithReadOnly")
4599
4600 opts := config.NewValidationOptions(config.WithStrictMode())
4601 v := NewValidator(opts, 3.1)
4602
4603 // In request direction, readOnly property "id" should be skipped (line 291-292)
4604 // Both parent and variant have additionalProperties: false, so we go through
4605 // recurseIntoDeclaredPropertiesWithMerged
4606 // Note: variant must also declare "name" so data matches the variant
4607 data := map[string]any{
4608 "name": "test",
4609 "id": "should-be-skipped",
4610 "data": "valid",
4611 }
4612
4613 result := v.Validate(Input{
4614 Schema: schema,
4615 Data: data,
4616 Direction: DirectionRequest,
4617 Options: opts,
4618 BasePath: "$.body",
4619 Version: 3.1,
4620 })
4621
4622 // id is readOnly and skipped in request, no validation errors
4623 assert.True(t, result.Valid)
4624 assert.Empty(t, result.UndeclaredValues)
4625 }
4626
4627 func TestStrictValidator_AllOfAdditionalPropertiesFalseRecurse(t *testing.T) {
4628 // Covers polymorphic.go:461-462, 467-468 - recursion with additionalProperties: false
4629 yml := `openapi: "3.1.0"
4630 info:
4631 title: Test
4632 version: "1.0"
4633 paths: {}
4634 components:
4635 schemas:
4636 RecurseTest:
4637 type: object
4638 additionalProperties: false
4639 allOf:
4640 - type: object
4641 properties:
4642 nested:
4643 type: object
4644 properties:
4645 valid:
4646 type: string
4647 `
4648 model := buildSchemaFromYAML(t, yml)
4649 schema := getSchema(t, model, "RecurseTest")
4650
4651 opts := config.NewValidationOptions(config.WithStrictMode())
4652 v := NewValidator(opts, 3.1)
4653
4654 // nested.extra should be reported as undeclared
4655 data := map[string]any{
4656 "nested": map[string]any{
4657 "valid": "ok",
4658 "extra": "should be flagged",
4659 },
4660 }
4661
4662 result := v.Validate(Input{
4663 Schema: schema,
4664 Data: data,
4665 Direction: DirectionRequest,
4666 Options: opts,
4667 BasePath: "$.body",
4668 Version: 3.1,
4669 })
4670
4671 assert.False(t, result.Valid)
4672 assert.Len(t, result.UndeclaredValues, 1)
4673 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
4674 assert.Equal(t, "$.body.nested.extra", result.UndeclaredValues[0].Path)
4675 }
4676
4677 func TestStrictValidator_OneOfVariantPropertyPriority(t *testing.T) {
4678 // Covers polymorphic.go:248-250, 255-257 - findPropertySchemaInMerged
4679 yml := `openapi: "3.1.0"
4680 info:
4681 title: Test
4682 version: "1.0"
4683 paths: {}
4684 components:
4685 schemas:
4686 PriorityTest:
4687 type: object
4688 properties:
4689 type:
4690 type: string
4691 oneOf:
4692 - type: object
4693 properties:
4694 details:
4695 type: object
4696 properties:
4697 variantField:
4698 type: string
4699 `
4700 model := buildSchemaFromYAML(t, yml)
4701 schema := getSchema(t, model, "PriorityTest")
4702
4703 opts := config.NewValidationOptions(config.WithStrictMode())
4704 v := NewValidator(opts, 3.1)
4705
4706 // type is from parent, details is from variant
4707 data := map[string]any{
4708 "type": "test",
4709 "details": map[string]any{
4710 "variantField": "from variant",
4711 "undeclared": "should be flagged",
4712 },
4713 }
4714
4715 result := v.Validate(Input{
4716 Schema: schema,
4717 Data: data,
4718 Direction: DirectionRequest,
4719 Options: opts,
4720 BasePath: "$.body",
4721 Version: 3.1,
4722 })
4723
4724 // undeclared in details should be flagged
4725 assert.False(t, result.Valid)
4726 assert.Len(t, result.UndeclaredValues, 1)
4727 assert.Equal(t, "undeclared", result.UndeclaredValues[0].Name)
4728 }
4729
4730 func TestStrictValidator_PropertyDeclaredInAllOfChild(t *testing.T) {
4731 // Covers polymorphic.go:46-47 - isPropertyDeclaredInAllOf continuation
4732 yml := `openapi: "3.1.0"
4733 info:
4734 title: Test
4735 version: "1.0"
4736 paths: {}
4737 components:
4738 schemas:
4739 AllOfChildProp:
4740 type: object
4741 properties:
4742 parentOnly:
4743 type: string
4744 allOf:
4745 - type: object
4746 properties:
4747 fromChild:
4748 type: string
4749 `
4750 model := buildSchemaFromYAML(t, yml)
4751 schema := getSchema(t, model, "AllOfChildProp")
4752
4753 opts := config.NewValidationOptions(config.WithStrictMode())
4754 v := NewValidator(opts, 3.1)
4755
4756 // fromChild is declared in allOf child, should be considered declared
4757 data := map[string]any{
4758 "parentOnly": "parent",
4759 "fromChild": "child",
4760 }
4761
4762 result := v.Validate(Input{
4763 Schema: schema,
4764 Data: data,
4765 Direction: DirectionRequest,
4766 Options: opts,
4767 BasePath: "$.body",
4768 Version: 3.1,
4769 })
4770
4771 assert.True(t, result.Valid)
4772 assert.Empty(t, result.UndeclaredValues)
4773 }
4774
4775 func TestStrictValidator_ValidateAllOf_NilSchemaProxy(t *testing.T) {
4776 // Covers polymorphic.go:67-68 - nil schemaProxy in allOf loop
4777 yml := `openapi: "3.1.0"
4778 info:
4779 title: Test
4780 version: "1.0"
4781 paths: {}
4782 components:
4783 schemas:
4784 AllOfWithNil:
4785 type: object
4786 allOf:
4787 - type: object
4788 properties:
4789 name:
4790 type: string
4791 `
4792 model := buildSchemaFromYAML(t, yml)
4793 schema := getSchema(t, model, "AllOfWithNil")
4794
4795 // Inject nil into allOf array to test the nil check at line 67-68
4796 schema.AllOf = append(schema.AllOf, nil)
4797
4798 opts := config.NewValidationOptions(config.WithStrictMode())
4799 v := NewValidator(opts, 3.1)
4800
4801 data := map[string]any{
4802 "name": "test",
4803 "extra": "undeclared",
4804 }
4805
4806 result := v.Validate(Input{
4807 Schema: schema,
4808 Data: data,
4809 Direction: DirectionRequest,
4810 Options: opts,
4811 BasePath: "$.body",
4812 Version: 3.1,
4813 })
4814
4815 // Should still work - nil schemaProxy is skipped
4816 assert.False(t, result.Valid)
4817 assert.Len(t, result.UndeclaredValues, 1)
4818 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
4819 }
4820
4821 func TestStrictValidator_ValidateAllOf_IgnoreTopLevelProperty(t *testing.T) {
4822 // Covers polymorphic.go:107-108 - shouldIgnore for top-level property in allOf
4823 yml := `openapi: "3.1.0"
4824 info:
4825 title: Test
4826 version: "1.0"
4827 paths: {}
4828 components:
4829 schemas:
4830 AllOfIgnoreTopLevel:
4831 type: object
4832 allOf:
4833 - type: object
4834 properties:
4835 name:
4836 type: string
4837 metadata:
4838 type: object
4839 `
4840 model := buildSchemaFromYAML(t, yml)
4841 schema := getSchema(t, model, "AllOfIgnoreTopLevel")
4842
4843 // Ignore the metadata property at top level
4844 opts := config.NewValidationOptions(
4845 config.WithStrictMode(),
4846 config.WithStrictIgnorePaths("$.body.metadata"),
4847 )
4848 v := NewValidator(opts, 3.1)
4849
4850 data := map[string]any{
4851 "name": "test",
4852 "metadata": map[string]any{
4853 "anything": "should be ignored at this level",
4854 },
4855 }
4856
4857 result := v.Validate(Input{
4858 Schema: schema,
4859 Data: data,
4860 Direction: DirectionRequest,
4861 Options: opts,
4862 BasePath: "$.body",
4863 Version: 3.1,
4864 })
4865
4866 // metadata property is ignored entirely, no errors
4867 assert.True(t, result.Valid)
4868 assert.Empty(t, result.UndeclaredValues)
4869 }
4870
4871 // =============================================================================
4872 // Phase 2: HIGH Priority Coverage Tests
4873 // =============================================================================
4874
4875 func TestStrictValidator_SchemaCacheHit(t *testing.T) {
4876 // Covers matcher.go:60-62 - global schema cache hit path
4877 // Need a oneOf schema to trigger dataMatchesSchema which uses getCompiledSchema
4878 yml := `openapi: "3.1.0"
4879 info:
4880 title: Test
4881 version: "1.0"
4882 paths: {}
4883 components:
4884 schemas:
4885 DogVariant:
4886 type: object
4887 properties:
4888 breed:
4889 type: string
4890 CatVariant:
4891 type: object
4892 properties:
4893 color:
4894 type: string
4895 CachedSchema:
4896 type: object
4897 oneOf:
4898 - $ref: '#/components/schemas/DogVariant'
4899 - $ref: '#/components/schemas/CatVariant'
4900 `
4901 model := buildSchemaFromYAML(t, yml)
4902 dogSchema := getSchema(t, model, "DogVariant")
4903
4904 // Create options with schema cache
4905 opts := config.NewValidationOptions(config.WithStrictMode())
4906
4907 // Pre-populate the GLOBAL cache with a compiled schema for the DogVariant hash
4908 // This is what findMatchingVariant will check via dataMatchesSchema
4909 hash := dogSchema.GoLow().Hash()
4910 compiledSchema, err := helpers.NewCompiledSchemaWithVersion(
4911 "test-cached",
4912 []byte(`{"type":"object","properties":{"breed":{"type":"string"}}}`),
4913 opts,
4914 3.1,
4915 )
4916 require.NoError(t, err)
4917 opts.SchemaCache.Store(hash, &libcache.SchemaCacheEntry{
4918 CompiledSchema: compiledSchema,
4919 })
4920
4921 v := NewValidator(opts, 3.1)
4922
4923 // Data that matches DogVariant
4924 data := map[string]any{
4925 "breed": "labrador",
4926 "extra": "undeclared",
4927 }
4928
4929 // Get the parent oneOf schema
4930 parentSchema := getSchema(t, model, "CachedSchema")
4931
4932 // Validation should hit the GLOBAL cache when checking oneOf variants
4933 result := v.Validate(Input{
4934 Schema: parentSchema,
4935 Data: data,
4936 Direction: DirectionRequest,
4937 Options: opts,
4938 BasePath: "$.body",
4939 Version: 3.1,
4940 })
4941
4942 // Should still detect undeclared property
4943 assert.False(t, result.Valid)
4944 assert.Len(t, result.UndeclaredValues, 1)
4945 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
4946 }
4947
4948 func TestStrictValidator_PrefixItemsWithIgnoredPath(t *testing.T) {
4949 // Covers array_validator.go:48-50 - shouldIgnore in prefixItems loop
4950 yml := `openapi: "3.1.0"
4951 info:
4952 title: Test
4953 version: "1.0"
4954 paths: {}
4955 components:
4956 schemas:
4957 TupleIgnore:
4958 type: array
4959 prefixItems:
4960 - type: object
4961 properties:
4962 id:
4963 type: string
4964 - type: object
4965 properties:
4966 name:
4967 type: string
4968 `
4969 model := buildSchemaFromYAML(t, yml)
4970 schema := getSchema(t, model, "TupleIgnore")
4971
4972 opts := config.NewValidationOptions(
4973 config.WithStrictMode(),
4974 config.WithStrictIgnorePaths("$.body[0]"),
4975 )
4976 v := NewValidator(opts, 3.1)
4977
4978 // First item should be ignored entirely, second item should be validated
4979 data := []any{
4980 map[string]any{
4981 "id": "1",
4982 "extraInFirst": "ignored because path $.body[0] is ignored",
4983 },
4984 map[string]any{
4985 "name": "test",
4986 "extraInSecond": "should be flagged",
4987 },
4988 }
4989
4990 result := v.Validate(Input{
4991 Schema: schema,
4992 Data: data,
4993 Direction: DirectionRequest,
4994 Options: opts,
4995 BasePath: "$.body",
4996 Version: 3.1,
4997 })
4998
4999 // Only second item's extra property should be flagged
5000 assert.False(t, result.Valid)
5001 assert.Len(t, result.UndeclaredValues, 1)
5002 assert.Equal(t, "extraInSecond", result.UndeclaredValues[0].Name)
5003 assert.Equal(t, "$.body[1].extraInSecond", result.UndeclaredValues[0].Path)
5004 }
5005
5006 func TestStrictValidator_ItemsWithIgnoredPath(t *testing.T) {
5007 // Covers array_validator.go:71-72 - shouldIgnore in items loop
5008 // Need to ignore the ITEM PATH itself ($.body[0]) not a nested property
5009 yml := `openapi: "3.1.0"
5010 info:
5011 title: Test
5012 version: "1.0"
5013 paths: {}
5014 components:
5015 schemas:
5016 ArrayIgnore:
5017 type: array
5018 items:
5019 type: object
5020 properties:
5021 name:
5022 type: string
5023 `
5024 model := buildSchemaFromYAML(t, yml)
5025 schema := getSchema(t, model, "ArrayIgnore")
5026
5027 // Ignore the first array item entirely ($.body[0])
5028 opts := config.NewValidationOptions(
5029 config.WithStrictMode(),
5030 config.WithStrictIgnorePaths("$.body[0]"),
5031 )
5032 v := NewValidator(opts, 3.1)
5033
5034 data := []any{
5035 map[string]any{
5036 "name": "item1",
5037 "extra": "should be ignored because $.body[0] is ignored",
5038 },
5039 map[string]any{
5040 "name": "item2",
5041 "extra": "should be flagged",
5042 },
5043 }
5044
5045 result := v.Validate(Input{
5046 Schema: schema,
5047 Data: data,
5048 Direction: DirectionRequest,
5049 Options: opts,
5050 BasePath: "$.body",
5051 Version: 3.1,
5052 })
5053
5054 // First item ignored, only second item's extra should be flagged
5055 assert.False(t, result.Valid)
5056 assert.Len(t, result.UndeclaredValues, 1)
5057 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
5058 assert.Equal(t, "$.body[1].extra", result.UndeclaredValues[0].Path)
5059 }
5060
5061 func TestValidateRequestHeaders_DeclaredHeaderSkipped(t *testing.T) {
5062 // Covers validator.go:123-125 - declared header skip in request validation
5063 opts := config.NewValidationOptions(config.WithStrictMode())
5064
5065 // Create params with X-Custom header declared
5066 params := []*v3.Parameter{
5067 {
5068 Name: "X-Custom",
5069 In: "header",
5070 },
5071 {
5072 Name: "X-Another",
5073 In: "header",
5074 },
5075 }
5076
5077 headers := http.Header{
5078 "X-Custom": []string{"declared-value"},
5079 "X-Another": []string{"also-declared"},
5080 "X-Undeclared": []string{"should-be-flagged"},
5081 }
5082
5083 undeclared := ValidateRequestHeaders(headers, params, nil, opts)
5084
5085 // Only X-Undeclared should be reported
5086 assert.Len(t, undeclared, 1)
5087 assert.Equal(t, "X-Undeclared", undeclared[0].Name)
5088 }
5089
5090 func TestValidateRequestHeaders_NilOrDisabled(t *testing.T) {
5091 // Covers validator.go:103 - early return when headers nil, options nil, or strict mode disabled
5092 params := []*v3.Parameter{{Name: "X-Custom", In: "header"}}
5093 headers := http.Header{"X-Custom": []string{"value"}}
5094
5095 // Test nil headers
5096 result := ValidateRequestHeaders(nil, params, nil, config.NewValidationOptions(config.WithStrictMode()))
5097 assert.Nil(t, result)
5098
5099 // Test nil options
5100 result = ValidateRequestHeaders(headers, params, nil, nil)
5101 assert.Nil(t, result)
5102
5103 // Test strict mode disabled
5104 opts := config.NewValidationOptions() // strict mode off by default
5105 result = ValidateRequestHeaders(headers, params, nil, opts)
5106 assert.Nil(t, result)
5107 }
5108
5109 func TestValidateRequestHeaders_IgnoredHeaderSkipped(t *testing.T) {
5110 // Covers validator.go:129 - skip when header is in ignored list
5111 opts := config.NewValidationOptions(config.WithStrictMode())
5112
5113 // No declared headers - but Content-Type is in default ignored list
5114 params := []*v3.Parameter{}
5115
5116 headers := http.Header{
5117 "Content-Type": []string{"application/json"}, // ignored by default
5118 "Authorization": []string{"Bearer token"}, // ignored by default
5119 "X-Custom": []string{"should-be-flagged"},
5120 }
5121
5122 undeclared := ValidateRequestHeaders(headers, params, nil, opts)
5123
5124 // Only X-Custom should be reported (Content-Type and Authorization are ignored)
5125 assert.Len(t, undeclared, 1)
5126 assert.Equal(t, "X-Custom", undeclared[0].Name)
5127 }
5128
5129 func TestValidateRequestHeaders_SecurityHeadersRecognized(t *testing.T) {
5130 // Covers validator.go:122-125 - security scheme headers are recognized as declared
5131 opts := config.NewValidationOptions(config.WithStrictMode())
5132
5133 // No declared params - security headers come from security schemes
5134 params := []*v3.Parameter{}
5135
5136 // Security headers extracted from security schemes
5137 securityHeaders := []string{"X-API-Key", "X-Custom-Auth"}
5138
5139 headers := http.Header{
5140 "X-Api-Key": []string{"my-api-key"}, // matches securityHeaders (case-insensitive)
5141 "X-Custom-Auth": []string{"custom-token"}, // matches securityHeaders
5142 "X-Unknown": []string{"should-be-flagged"},
5143 }
5144
5145 undeclared := ValidateRequestHeaders(headers, params, securityHeaders, opts)
5146
5147 // Only X-Unknown should be reported; X-Api-Key and X-Custom-Auth are recognized as security headers
5148 assert.Len(t, undeclared, 1)
5149 assert.Equal(t, "X-Unknown", undeclared[0].Name)
5150 }
5151
5152 func TestValidateRequestHeaders_SecurityHeadersCaseInsensitive(t *testing.T) {
5153 // Verify security header matching is case-insensitive
5154 opts := config.NewValidationOptions(config.WithStrictMode())
5155
5156 params := []*v3.Parameter{}
5157 securityHeaders := []string{"X-API-KEY"} // uppercase
5158
5159 headers := http.Header{
5160 "x-api-key": []string{"my-key"}, // lowercase in request
5161 }
5162
5163 undeclared := ValidateRequestHeaders(headers, params, securityHeaders, opts)
5164
5165 // Should not report x-api-key as undeclared (case-insensitive match)
5166 assert.Empty(t, undeclared)
5167 }
5168
5169 func TestValidateRequestHeaders_BothParamsAndSecurityHeaders(t *testing.T) {
5170 // Test that both params and security headers are recognized
5171 opts := config.NewValidationOptions(config.WithStrictMode())
5172
5173 params := []*v3.Parameter{
5174 {Name: "X-Request-Id", In: "header"},
5175 }
5176 securityHeaders := []string{"X-API-Key"}
5177
5178 headers := http.Header{
5179 "X-Request-Id": []string{"123"}, // declared via params
5180 "X-Api-Key": []string{"key"}, // declared via security schemes
5181 "X-Other": []string{"should-be-flagged"},
5182 }
5183
5184 undeclared := ValidateRequestHeaders(headers, params, securityHeaders, opts)
5185
5186 // Only X-Other should be reported
5187 assert.Len(t, undeclared, 1)
5188 assert.Equal(t, "X-Other", undeclared[0].Name)
5189 }
5190
5191 func TestValidateRequestHeaders_EmptySecurityHeaders(t *testing.T) {
5192 // Test with empty security headers slice (not nil)
5193 opts := config.NewValidationOptions(config.WithStrictMode())
5194
5195 params := []*v3.Parameter{}
5196 securityHeaders := []string{} // empty, not nil
5197
5198 headers := http.Header{
5199 "X-Custom": []string{"value"},
5200 }
5201
5202 undeclared := ValidateRequestHeaders(headers, params, securityHeaders, opts)
5203
5204 // X-Custom should be flagged since there are no declared headers
5205 assert.Len(t, undeclared, 1)
5206 assert.Equal(t, "X-Custom", undeclared[0].Name)
5207 }
5208
5209 func TestValidateResponseHeaders_DeclaredHeaderSkipped(t *testing.T) {
5210 // Covers validator.go:219-223, 228-230 - declared header handling in response
5211 opts := config.NewValidationOptions(config.WithStrictMode())
5212
5213 // Create declared headers map
5214 declaredHeaders := make(map[string]*v3.Header)
5215 declaredHeaders["X-Response-Id"] = &v3.Header{}
5216
5217 headers := http.Header{
5218 "X-Response-Id": []string{"declared"},
5219 "X-Undeclared": []string{"should-be-flagged"},
5220 }
5221
5222 undeclared := ValidateResponseHeaders(headers, &declaredHeaders, opts)
5223
5224 // Only X-Undeclared should be reported
5225 assert.Len(t, undeclared, 1)
5226 assert.Equal(t, "X-Undeclared", undeclared[0].Name)
5227 }
5228
5229 func TestValidateResponseHeaders_WithDeclaredHeaders(t *testing.T) {
5230 // Covers validator.go:219-223, 228-230 - building declared names list
5231 opts := config.NewValidationOptions(config.WithStrictMode())
5232
5233 // Create declared headers map with multiple headers
5234 declaredHeaders := make(map[string]*v3.Header)
5235 declaredHeaders["X-Rate-Limit"] = &v3.Header{}
5236 declaredHeaders["X-Request-Id"] = &v3.Header{}
5237
5238 headers := http.Header{
5239 "X-Rate-Limit": []string{"100"},
5240 "X-Request-Id": []string{"abc123"},
5241 "X-Undeclared": []string{"flagged"},
5242 }
5243
5244 undeclared := ValidateResponseHeaders(headers, &declaredHeaders, opts)
5245
5246 // Only X-Undeclared should be reported
5247 assert.Len(t, undeclared, 1)
5248 assert.Equal(t, "X-Undeclared", undeclared[0].Name)
5249 }
5250
5251 func TestValidateResponseHeaders_IgnorePathMatch(t *testing.T) {
5252 // Covers validator.go:239 - skip when header matches ignore path pattern
5253 opts := config.NewValidationOptions(
5254 config.WithStrictMode(),
5255 config.WithStrictIgnorePaths("$.headers.x-internal"),
5256 )
5257
5258 declaredHeaders := make(map[string]*v3.Header)
5259
5260 headers := http.Header{
5261 "X-Internal": []string{"should-be-ignored"}, // matches ignore path
5262 "X-Undeclared": []string{"should-be-flagged"},
5263 }
5264
5265 undeclared := ValidateResponseHeaders(headers, &declaredHeaders, opts)
5266
5267 // Only X-Undeclared should be reported (X-Internal matches ignore path)
5268 assert.Len(t, undeclared, 1)
5269 assert.Equal(t, "X-Undeclared", undeclared[0].Name)
5270 }
5271
5272 func TestNewValidator_WithIgnorePaths(t *testing.T) {
5273 // Covers types.go:310-311 - compiledIgnorePaths populated
5274 opts := config.NewValidationOptions(
5275 config.WithStrictMode(),
5276 config.WithStrictIgnorePaths("$.body.metadata", "$.body.internal"),
5277 )
5278
5279 v := NewValidator(opts, 3.1)
5280
5281 // Verify ignore paths are compiled
5282 assert.NotNil(t, v)
5283 assert.Len(t, v.compiledIgnorePaths, 2)
5284
5285 // Test that the patterns work
5286 yml := `openapi: "3.1.0"
5287 info:
5288 title: Test
5289 version: "1.0"
5290 paths: {}
5291 components:
5292 schemas:
5293 TestSchema:
5294 type: object
5295 properties:
5296 name:
5297 type: string
5298 `
5299 model := buildSchemaFromYAML(t, yml)
5300 schema := getSchema(t, model, "TestSchema")
5301
5302 // metadata and internal are undeclared properties that match ignore patterns
5303 data := map[string]any{
5304 "name": "test",
5305 "metadata": map[string]any{
5306 "ignored": "value",
5307 },
5308 "internal": map[string]any{
5309 "deep": map[string]any{
5310 "nested": "also ignored",
5311 },
5312 },
5313 }
5314
5315 result := v.Validate(Input{
5316 Schema: schema,
5317 Data: data,
5318 Direction: DirectionRequest,
5319 Options: opts,
5320 BasePath: "$.body",
5321 Version: 3.1,
5322 })
5323
5324 // metadata and internal paths are ignored, so no undeclared errors
5325 assert.True(t, result.Valid)
5326 assert.Empty(t, result.UndeclaredValues)
5327 }
5328
5329 func TestNewValidator_WithCustomLogger(t *testing.T) {
5330 // Covers types.go:295 - custom logger from options
5331 customLogger := slog.New(slog.NewTextHandler(nil, nil))
5332 opts := config.NewValidationOptions(
5333 config.WithStrictMode(),
5334 config.WithLogger(customLogger),
5335 )
5336
5337 v := NewValidator(opts, 3.1)
5338
5339 // Verify the custom logger is used
5340 assert.NotNil(t, v)
5341 assert.Equal(t, customLogger, v.logger)
5342 }
5343
5344 // =============================================================================
5345 // Phase 3: MEDIUM Priority Tests
5346 // =============================================================================
5347
5348 func TestStrictValidator_PrimitiveValuesIgnored(t *testing.T) {
5349 // Covers schema_walker.go:37-38 - validateValue default case for primitives
5350 // Primitive values (string, number, boolean) have no properties to check
5351 yml := `openapi: "3.1.0"
5352 info:
5353 title: Test
5354 version: "1.0"
5355 paths: {}
5356 components:
5357 schemas:
5358 StringSchema:
5359 type: string
5360 NumberSchema:
5361 type: number
5362 BooleanSchema:
5363 type: boolean
5364 `
5365 model := buildSchemaFromYAML(t, yml)
5366 opts := config.NewValidationOptions(config.WithStrictMode())
5367 v := NewValidator(opts, 3.1)
5368
5369 // Test string value - no properties to check
5370 stringSchema := getSchema(t, model, "StringSchema")
5371 result := v.Validate(Input{
5372 Schema: stringSchema,
5373 Data: "just a string",
5374 Direction: DirectionRequest,
5375 Options: opts,
5376 BasePath: "$.body",
5377 Version: 3.1,
5378 })
5379 assert.True(t, result.Valid)
5380 assert.Empty(t, result.UndeclaredValues)
5381
5382 // Test number value
5383 numberSchema := getSchema(t, model, "NumberSchema")
5384 result = v.Validate(Input{
5385 Schema: numberSchema,
5386 Data: 42.5,
5387 Direction: DirectionRequest,
5388 Options: opts,
5389 BasePath: "$.body",
5390 Version: 3.1,
5391 })
5392 assert.True(t, result.Valid)
5393 assert.Empty(t, result.UndeclaredValues)
5394
5395 // Test boolean value
5396 boolSchema := getSchema(t, model, "BooleanSchema")
5397 result = v.Validate(Input{
5398 Schema: boolSchema,
5399 Data: true,
5400 Direction: DirectionRequest,
5401 Options: opts,
5402 BasePath: "$.body",
5403 Version: 3.1,
5404 })
5405 assert.True(t, result.Valid)
5406 assert.Empty(t, result.UndeclaredValues)
5407 }
5408
5409 func TestStrictValidator_AdditionalPropertiesSchemaRecurse(t *testing.T) {
5410 // Covers schema_walker.go:72-80 - recurse into additionalProperties schema
5411 yml := `openapi: "3.1.0"
5412 info:
5413 title: Test
5414 version: "1.0"
5415 paths: {}
5416 components:
5417 schemas:
5418 AddlPropsNested:
5419 type: object
5420 properties:
5421 id:
5422 type: string
5423 additionalProperties:
5424 type: object
5425 properties:
5426 nested:
5427 type: string
5428 `
5429 model := buildSchemaFromYAML(t, yml)
5430 schema := getSchema(t, model, "AddlPropsNested")
5431
5432 opts := config.NewValidationOptions(config.WithStrictMode())
5433 v := NewValidator(opts, 3.1)
5434
5435 // Data with nested undeclared property inside additionalProperties
5436 data := map[string]any{
5437 "id": "1",
5438 "extra": map[string]any{
5439 "nested": "ok",
5440 "bad": "undeclared inside extra",
5441 },
5442 }
5443
5444 result := v.Validate(Input{
5445 Schema: schema,
5446 Data: data,
5447 Direction: DirectionRequest,
5448 Options: opts,
5449 BasePath: "$.body",
5450 Version: 3.1,
5451 })
5452
5453 // Both "extra" at top level AND "bad" inside extra should be reported
5454 assert.False(t, result.Valid)
5455 assert.GreaterOrEqual(t, len(result.UndeclaredValues), 1)
5456
5457 // Find undeclared values
5458 foundExtra := false
5459 foundBad := false
5460 for _, uv := range result.UndeclaredValues {
5461 if uv.Name == "extra" {
5462 foundExtra = true
5463 }
5464 if uv.Name == "bad" {
5465 foundBad = true
5466 }
5467 }
5468 assert.True(t, foundExtra, "expected 'extra' to be reported as undeclared")
5469 assert.True(t, foundBad, "expected 'bad' inside extra to be reported as undeclared")
5470 }
5471
5472 func TestStrictValidator_AdditionalPropertiesFalseShortCircuit(t *testing.T) {
5473 // Covers schema_walker.go:113-115 - shouldReportUndeclared returns false
5474 // When additionalProperties: false, JSON Schema handles it, not strict mode
5475 yml := `openapi: "3.1.0"
5476 info:
5477 title: Test
5478 version: "1.0"
5479 paths: {}
5480 components:
5481 schemas:
5482 NoExtras:
5483 type: object
5484 additionalProperties: false
5485 properties:
5486 id:
5487 type: string
5488 `
5489 model := buildSchemaFromYAML(t, yml)
5490 schema := getSchema(t, model, "NoExtras")
5491
5492 opts := config.NewValidationOptions(config.WithStrictMode())
5493 v := NewValidator(opts, 3.1)
5494
5495 // Data with extra property - additionalProperties: false handles this
5496 data := map[string]any{
5497 "id": "1",
5498 "extra": "should be handled by JSON Schema, not strict",
5499 }
5500
5501 result := v.Validate(Input{
5502 Schema: schema,
5503 Data: data,
5504 Direction: DirectionRequest,
5505 Options: opts,
5506 BasePath: "$.body",
5507 Version: 3.1,
5508 })
5509
5510 // Strict mode should NOT report this because additionalProperties: false
5511 // means JSON Schema will handle it
5512 assert.True(t, result.Valid)
5513 assert.Empty(t, result.UndeclaredValues)
5514 }
5515
5516 func TestStrictValidator_PatternPropertiesWithAdditionalFalse(t *testing.T) {
5517 // Covers schema_walker.go:223-228 - patternProperties with additionalProperties: false
5518 yml := `openapi: "3.1.0"
5519 info:
5520 title: Test
5521 version: "1.0"
5522 paths: {}
5523 components:
5524 schemas:
5525 PatternOnly:
5526 type: object
5527 additionalProperties: false
5528 patternProperties:
5529 "^x-":
5530 type: string
5531 `
5532 model := buildSchemaFromYAML(t, yml)
5533 schema := getSchema(t, model, "PatternOnly")
5534
5535 opts := config.NewValidationOptions(config.WithStrictMode())
5536 v := NewValidator(opts, 3.1)
5537
5538 // x-custom matches the pattern, so it's declared
5539 data := map[string]any{
5540 "x-custom": "ok",
5541 }
5542
5543 result := v.Validate(Input{
5544 Schema: schema,
5545 Data: data,
5546 Direction: DirectionRequest,
5547 Options: opts,
5548 BasePath: "$.body",
5549 Version: 3.1,
5550 })
5551
5552 // x-custom matches pattern and additionalProperties: false handles the rest
5553 assert.True(t, result.Valid)
5554 assert.Empty(t, result.UndeclaredValues)
5555 }
5556
5557 func TestStrictValidator_InvalidPatternPropertiesRegex(t *testing.T) {
5558 // Covers property_collector.go:46-49 - invalid regex skipped
5559 yml := `openapi: "3.1.0"
5560 info:
5561 title: Test
5562 version: "1.0"
5563 paths: {}
5564 components:
5565 schemas:
5566 InvalidPattern:
5567 type: object
5568 properties:
5569 id:
5570 type: string
5571 patternProperties:
5572 "[invalid(regex":
5573 type: string
5574 `
5575 model := buildSchemaFromYAML(t, yml)
5576 schema := getSchema(t, model, "InvalidPattern")
5577
5578 opts := config.NewValidationOptions(config.WithStrictMode())
5579 v := NewValidator(opts, 3.1)
5580
5581 // Property name that would match the invalid pattern if it could compile
5582 data := map[string]any{
5583 "id": "1",
5584 "[invalid(regex": "value",
5585 }
5586
5587 result := v.Validate(Input{
5588 Schema: schema,
5589 Data: data,
5590 Direction: DirectionRequest,
5591 Options: opts,
5592 BasePath: "$.body",
5593 Version: 3.1,
5594 })
5595
5596 // Invalid pattern is skipped, so the property is reported as undeclared
5597 assert.False(t, result.Valid)
5598 assert.Len(t, result.UndeclaredValues, 1)
5599 assert.Equal(t, "[invalid(regex", result.UndeclaredValues[0].Name)
5600 }
5601
5602 func TestStrictValidator_UnevaluatedItemsWithIgnoredPath(t *testing.T) {
5603 // Covers array_validator.go:97-98 - shouldIgnore in unevaluatedItems
5604 yml := `openapi: "3.1.0"
5605 info:
5606 title: Test
5607 version: "1.0"
5608 paths: {}
5609 components:
5610 schemas:
5611 UnevalIgnore:
5612 type: array
5613 unevaluatedItems:
5614 type: object
5615 properties:
5616 id:
5617 type: string
5618 `
5619 model := buildSchemaFromYAML(t, yml)
5620 schema := getSchema(t, model, "UnevalIgnore")
5621
5622 // Ignore the first array element
5623 opts := config.NewValidationOptions(
5624 config.WithStrictMode(),
5625 config.WithStrictIgnorePaths("$.body[0]"),
5626 )
5627 v := NewValidator(opts, 3.1)
5628
5629 // First item has undeclared 'extra', but it should be ignored
5630 data := []any{
5631 map[string]any{
5632 "id": "1",
5633 "extra": "should be ignored at index 0",
5634 },
5635 map[string]any{
5636 "id": "2",
5637 "extra2": "should be reported at index 1",
5638 },
5639 }
5640
5641 result := v.Validate(Input{
5642 Schema: schema,
5643 Data: data,
5644 Direction: DirectionRequest,
5645 Options: opts,
5646 BasePath: "$.body",
5647 Version: 3.1,
5648 })
5649
5650 // First item ignored, second item's extra2 should be reported
5651 assert.False(t, result.Valid)
5652 assert.Len(t, result.UndeclaredValues, 1)
5653 assert.Equal(t, "extra2", result.UndeclaredValues[0].Name)
5654 }
5655
5656 func TestStrictValidator_AdditionalPropertiesSchemaReportsUndeclared(t *testing.T) {
5657 // Covers schema_walker.go:122-126 - additionalProperties with schema still reports
5658 yml := `openapi: "3.1.0"
5659 info:
5660 title: Test
5661 version: "1.0"
5662 paths: {}
5663 components:
5664 schemas:
5665 SchemaAddl:
5666 type: object
5667 additionalProperties:
5668 type: string
5669 `
5670 model := buildSchemaFromYAML(t, yml)
5671 schema := getSchema(t, model, "SchemaAddl")
5672
5673 opts := config.NewValidationOptions(config.WithStrictMode())
5674 v := NewValidator(opts, 3.1)
5675
5676 // Data with extra property allowed by additionalProperties schema
5677 data := map[string]any{
5678 "extra": "ok per JSON Schema but flagged by strict",
5679 }
5680
5681 result := v.Validate(Input{
5682 Schema: schema,
5683 Data: data,
5684 Direction: DirectionRequest,
5685 Options: opts,
5686 BasePath: "$.body",
5687 Version: 3.1,
5688 })
5689
5690 // Strict mode should still flag undeclared properties even when
5691 // additionalProperties allows them
5692 assert.False(t, result.Valid)
5693 assert.Len(t, result.UndeclaredValues, 1)
5694 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
5695 }
5696
5697 func TestStrictValidator_NilSchemaPassesValidation(t *testing.T) {
5698 // Covers matcher.go:38-40 - nil schema handling in dataMatchesSchema
5699 // When schema is nil, validation passes (no schema means anything matches)
5700 opts := config.NewValidationOptions(config.WithStrictMode())
5701 v := NewValidator(opts, 3.1)
5702
5703 // Test with nil schema directly using dataMatchesSchema
5704 matches, err := v.dataMatchesSchema(nil, map[string]any{"key": "value"})
5705 assert.NoError(t, err)
5706 assert.True(t, matches, "nil schema should match any data")
5707
5708 // Also test with different data types
5709 matches, err = v.dataMatchesSchema(nil, "string value")
5710 assert.NoError(t, err)
5711 assert.True(t, matches)
5712
5713 matches, err = v.dataMatchesSchema(nil, 123)
5714 assert.NoError(t, err)
5715 assert.True(t, matches)
5716
5717 matches, err = v.dataMatchesSchema(nil, []any{1, 2, 3})
5718 assert.NoError(t, err)
5719 assert.True(t, matches)
5720 }
5721
5722 func TestStrictValidator_ValidateValue_ShouldIgnore(t *testing.T) {
5723 // Covers schema_walker.go:17-18 - shouldIgnore in validateValue at ENTRY point
5724 // Need to ignore $.body itself so the check happens at validateValue entry
5725 yml := `openapi: "3.1.0"
5726 info:
5727 title: Test
5728 version: "1.0"
5729 paths: {}
5730 components:
5731 schemas:
5732 IgnoreTest:
5733 type: object
5734 properties:
5735 name:
5736 type: string
5737 `
5738 model := buildSchemaFromYAML(t, yml)
5739 schema := getSchema(t, model, "IgnoreTest")
5740
5741 // Ignore the entire body - validateValue entry should return early at line 18
5742 opts := config.NewValidationOptions(
5743 config.WithStrictMode(),
5744 config.WithStrictIgnorePaths("$.body"),
5745 )
5746 v := NewValidator(opts, 3.1)
5747
5748 data := map[string]any{
5749 "name": "valid",
5750 "undeclared": "should be ignored because entire body is ignored",
5751 }
5752
5753 result := v.Validate(Input{
5754 Schema: schema,
5755 Data: data,
5756 Direction: DirectionRequest,
5757 Options: opts,
5758 BasePath: "$.body",
5759 Version: 3.1,
5760 })
5761
5762 // Entire body is ignored, so no undeclared errors
5763 assert.True(t, result.Valid)
5764 assert.Empty(t, result.UndeclaredValues)
5765 }
5766
5767 func TestStrictValidator_ValidateValue_CycleDetection(t *testing.T) {
5768 // Covers schema_walker.go:27-28 - cycle detection in validateValue
5769 // Need to call validateValue directly with a pre-visited context
5770 yml := `openapi: "3.1.0"
5771 info:
5772 title: Test
5773 version: "1.0"
5774 paths: {}
5775 components:
5776 schemas:
5777 TestSchema:
5778 type: object
5779 properties:
5780 name:
5781 type: string
5782 `
5783 model := buildSchemaFromYAML(t, yml)
5784 schema := getSchema(t, model, "TestSchema")
5785
5786 opts := config.NewValidationOptions(config.WithStrictMode())
5787 v := NewValidator(opts, 3.1)
5788
5789 // Create a context and pre-mark the schema as visited at this path
5790 ctx := newTraversalContext(DirectionRequest, v.compiledIgnorePaths, "$.body")
5791 schemaKey := v.getSchemaKey(schema)
5792 ctx.checkAndMarkVisited(schemaKey) // First visit - marks as visited
5793
5794 data := map[string]any{
5795 "name": "test",
5796 "undeclared": "should not be detected due to cycle",
5797 }
5798
5799 // Call validateValue directly - should hit line 28 (cycle detected)
5800 result := v.validateValue(ctx, schema, data)
5801
5802 // Cycle detected, returns early with no errors
5803 assert.Empty(t, result)
5804 }
5805
5806 func TestStrictValidator_ShouldReportUndeclared_AdditionalPropertiesTrue(t *testing.T) {
5807 // Covers schema_walker.go:119-120 - additionalProperties: true explicit
5808 yml := `openapi: "3.1.0"
5809 info:
5810 title: Test
5811 version: "1.0"
5812 paths: {}
5813 components:
5814 schemas:
5815 ExplicitTrue:
5816 type: object
5817 additionalProperties: true
5818 properties:
5819 name:
5820 type: string
5821 `
5822 model := buildSchemaFromYAML(t, yml)
5823 schema := getSchema(t, model, "ExplicitTrue")
5824
5825 opts := config.NewValidationOptions(config.WithStrictMode())
5826 v := NewValidator(opts, 3.1)
5827
5828 // Extra property allowed by additionalProperties: true but flagged by strict
5829 data := map[string]any{
5830 "name": "test",
5831 "extra": "should be flagged in strict mode",
5832 }
5833
5834 result := v.Validate(Input{
5835 Schema: schema,
5836 Data: data,
5837 Direction: DirectionRequest,
5838 Options: opts,
5839 BasePath: "$.body",
5840 Version: 3.1,
5841 })
5842
5843 // Strict mode should flag undeclared even with additionalProperties: true
5844 assert.False(t, result.Valid)
5845 assert.Len(t, result.UndeclaredValues, 1)
5846 assert.Equal(t, "extra", result.UndeclaredValues[0].Name)
5847 }
5848
5849 func TestStrictValidator_RecurseIntoDeclaredProperties_PropertyNotInData(t *testing.T) {
5850 // Covers schema_walker.go:179-180 - continue when schema property not in data
5851 yml := `openapi: "3.1.0"
5852 info:
5853 title: Test
5854 version: "1.0"
5855 paths: {}
5856 components:
5857 schemas:
5858 MissingProp:
5859 type: object
5860 additionalProperties: false
5861 properties:
5862 required:
5863 type: string
5864 optional:
5865 type: string
5866 `
5867 model := buildSchemaFromYAML(t, yml)
5868 schema := getSchema(t, model, "MissingProp")
5869
5870 opts := config.NewValidationOptions(config.WithStrictMode())
5871 v := NewValidator(opts, 3.1)
5872
5873 // Only provide 'required', not 'optional' - line 180 should be hit
5874 data := map[string]any{
5875 "required": "value",
5876 }
5877
5878 result := v.Validate(Input{
5879 Schema: schema,
5880 Data: data,
5881 Direction: DirectionRequest,
5882 Options: opts,
5883 BasePath: "$.body",
5884 Version: 3.1,
5885 })
5886
5887 // No undeclared properties
5888 assert.True(t, result.Valid)
5889 assert.Empty(t, result.UndeclaredValues)
5890 }
5891
5892 func TestStrictValidator_RecurseIntoDeclaredProperties_SkipReadOnly(t *testing.T) {
5893 // Covers schema_walker.go:194-195 - shouldSkipProperty in recurseIntoDeclaredProperties
5894 yml := `openapi: "3.1.0"
5895 info:
5896 title: Test
5897 version: "1.0"
5898 paths: {}
5899 components:
5900 schemas:
5901 ReadOnlyProp:
5902 type: object
5903 additionalProperties: false
5904 properties:
5905 name:
5906 type: string
5907 id:
5908 type: string
5909 readOnly: true
5910 `
5911 model := buildSchemaFromYAML(t, yml)
5912 schema := getSchema(t, model, "ReadOnlyProp")
5913
5914 opts := config.NewValidationOptions(config.WithStrictMode())
5915 v := NewValidator(opts, 3.1)
5916
5917 // Include readOnly property in request - should be skipped (line 195)
5918 data := map[string]any{
5919 "name": "test",
5920 "id": "should-be-skipped",
5921 }
5922
5923 result := v.Validate(Input{
5924 Schema: schema,
5925 Data: data,
5926 Direction: DirectionRequest,
5927 Options: opts,
5928 BasePath: "$.body",
5929 Version: 3.1,
5930 })
5931
5932 // id is readOnly and skipped, no errors
5933 assert.True(t, result.Valid)
5934 assert.Empty(t, result.UndeclaredValues)
5935 }
5936
5937 func TestStrictValidator_RecurseIntoDeclaredProperties_ShouldIgnore(t *testing.T) {
5938 // Covers schema_walker.go:188-189 - shouldIgnore for explicit property
5939 yml := `openapi: "3.1.0"
5940 info:
5941 title: Test
5942 version: "1.0"
5943 paths: {}
5944 components:
5945 schemas:
5946 IgnoreProp:
5947 type: object
5948 additionalProperties: false
5949 properties:
5950 name:
5951 type: string
5952 metadata:
5953 type: object
5954 properties:
5955 nested:
5956 type: string
5957 `
5958 model := buildSchemaFromYAML(t, yml)
5959 schema := getSchema(t, model, "IgnoreProp")
5960
5961 // Ignore metadata property
5962 opts := config.NewValidationOptions(
5963 config.WithStrictMode(),
5964 config.WithStrictIgnorePaths("$.body.metadata"),
5965 )
5966 v := NewValidator(opts, 3.1)
5967
5968 // metadata has undeclared property but is ignored (line 189)
5969 data := map[string]any{
5970 "name": "test",
5971 "metadata": map[string]any{
5972 "nested": "ok",
5973 "undeclared": "should be ignored",
5974 },
5975 }
5976
5977 result := v.Validate(Input{
5978 Schema: schema,
5979 Data: data,
5980 Direction: DirectionRequest,
5981 Options: opts,
5982 BasePath: "$.body",
5983 Version: 3.1,
5984 })
5985
5986 // metadata is ignored, no errors
5987 assert.True(t, result.Valid)
5988 assert.Empty(t, result.UndeclaredValues)
5989 }
5990
5991 func TestStrictValidator_RecurseIntoDeclaredProperties_PatternNoMatch(t *testing.T) {
5992 // Covers schema_walker.go:210-211 - property doesn't match any patternProperty
5993 yml := `openapi: "3.1.0"
5994 info:
5995 title: Test
5996 version: "1.0"
5997 paths: {}
5998 components:
5999 schemas:
6000 PatternSchema:
6001 type: object
6002 additionalProperties: false
6003 properties:
6004 name:
6005 type: string
6006 patternProperties:
6007 "^x-":
6008 type: string
6009 `
6010 model := buildSchemaFromYAML(t, yml)
6011 schema := getSchema(t, model, "PatternSchema")
6012
6013 opts := config.NewValidationOptions(config.WithStrictMode())
6014 v := NewValidator(opts, 3.1)
6015
6016 // "other" doesn't match explicit props or pattern "^x-" - line 211 hit
6017 data := map[string]any{
6018 "name": "test",
6019 "x-custom": "matches pattern",
6020 "other": "doesn't match pattern",
6021 }
6022
6023 result := v.Validate(Input{
6024 Schema: schema,
6025 Data: data,
6026 Direction: DirectionRequest,
6027 Options: opts,
6028 BasePath: "$.body",
6029 Version: 3.1,
6030 })
6031
6032 // "other" doesn't match pattern, but additionalProperties: false handles it
6033 // so strict mode doesn't report it
6034 assert.True(t, result.Valid)
6035 assert.Empty(t, result.UndeclaredValues)
6036 }
6037
6038 func TestStrictValidator_RecurseIntoDeclaredProperties_PatternSkipReadOnly(t *testing.T) {
6039 // Covers schema_walker.go:225-226 - shouldSkipProperty for patternProperty
6040 yml := `openapi: "3.1.0"
6041 info:
6042 title: Test
6043 version: "1.0"
6044 paths: {}
6045 components:
6046 schemas:
6047 PatternReadOnly:
6048 type: object
6049 additionalProperties: false
6050 properties:
6051 name:
6052 type: string
6053 patternProperties:
6054 "^x-":
6055 type: string
6056 readOnly: true
6057 `
6058 model := buildSchemaFromYAML(t, yml)
6059 schema := getSchema(t, model, "PatternReadOnly")
6060
6061 opts := config.NewValidationOptions(config.WithStrictMode())
6062 v := NewValidator(opts, 3.1)
6063
6064 // x-custom matches pattern but schema is readOnly - skip in request (line 226)
6065 data := map[string]any{
6066 "name": "test",
6067 "x-custom": "matches readOnly pattern",
6068 }
6069
6070 result := v.Validate(Input{
6071 Schema: schema,
6072 Data: data,
6073 Direction: DirectionRequest,
6074 Options: opts,
6075 BasePath: "$.body",
6076 Version: 3.1,
6077 })
6078
6079 // x-custom matches pattern but is readOnly, skipped in request
6080 assert.True(t, result.Valid)
6081 assert.Empty(t, result.UndeclaredValues)
6082 }
6083
6084 func TestStrictValidator_RecurseIntoDeclaredProperties_PatternShouldIgnore(t *testing.T) {
6085 // Covers schema_walker.go:219-220 - shouldIgnore for patternProperty path
6086 yml := `openapi: "3.1.0"
6087 info:
6088 title: Test
6089 version: "1.0"
6090 paths: {}
6091 components:
6092 schemas:
6093 PatternIgnore:
6094 type: object
6095 additionalProperties: false
6096 properties:
6097 name:
6098 type: string
6099 patternProperties:
6100 "^x-":
6101 type: object
6102 properties:
6103 nested:
6104 type: string
6105 `
6106 model := buildSchemaFromYAML(t, yml)
6107 schema := getSchema(t, model, "PatternIgnore")
6108
6109 // Ignore the pattern-matched property path
6110 opts := config.NewValidationOptions(
6111 config.WithStrictMode(),
6112 config.WithStrictIgnorePaths("$.body.x-custom"),
6113 )
6114 v := NewValidator(opts, 3.1)
6115
6116 // x-custom matches pattern, path matches ignore pattern - should skip (line 220)
6117 data := map[string]any{
6118 "name": "test",
6119 "x-custom": map[string]any{
6120 "nested": "valid",
6121 "undeclared": "should be ignored because path is ignored",
6122 },
6123 }
6124
6125 result := v.Validate(Input{
6126 Schema: schema,
6127 Data: data,
6128 Direction: DirectionRequest,
6129 Options: opts,
6130 BasePath: "$.body",
6131 Version: 3.1,
6132 })
6133
6134 // x-custom path is ignored, so no undeclared errors
6135 assert.True(t, result.Valid)
6136 assert.Empty(t, result.UndeclaredValues)
6137 }
6138
6139 func TestStrictValidator_ValidateVariantWithParent_VariantNilGoLow(t *testing.T) {
6140 // Covers polymorphic.go:233-234 - fallback to parent when variant.GoLow() is nil
6141 // This tests the defensive code path for programmatically created schemas
6142
6143 // Build a real parent schema from YAML (has GoLow())
6144 yml := `openapi: "3.1.0"
6145 info:
6146 title: Test
6147 version: "1.0"
6148 paths: {}
6149 components:
6150 schemas:
6151 ParentSchema:
6152 type: object
6153 properties:
6154 parentProp:
6155 type: string
6156 `
6157 model := buildSchemaFromYAML(t, yml)
6158 parent := getSchema(t, model, "ParentSchema")
6159 require.NotNil(t, parent.GoLow())
6160
6161 // Create a variant schema programmatically (no GoLow())
6162 variant := &base.Schema{
6163 Type: []string{"object"},
6164 }
6165 require.Nil(t, variant.GoLow())
6166
6167 opts := config.NewValidationOptions(config.WithStrictMode())
6168 v := NewValidator(opts, 3.1)
6169
6170 ctx := newTraversalContext(DirectionRequest, nil, "$.body")
6171
6172 // Data with undeclared property - triggers line 230-237
6173 data := map[string]any{
6174 "parentProp": "value",
6175 "undeclared": "triggers undeclared path",
6176 }
6177
6178 result := v.validateVariantWithParent(ctx, parent, variant, data)
6179
6180 // Should detect undeclared property and use parent's location (since variant has no GoLow)
6181 assert.Len(t, result, 1)
6182 assert.Equal(t, "undeclared", result[0].Name)
6183 // Location should come from parent (not crash due to nil variant.GoLow())
6184 assert.Greater(t, result[0].SpecLine, 0)
6185 }
6186
6187 // ============== readOnly/writeOnly rejection tests ==============
6188
6189 func TestStrictValidator_RejectReadOnly_InRequest(t *testing.T) {
6190 yml := `openapi: "3.1.0"
6191 info:
6192 title: Test
6193 version: "1.0"
6194 paths: {}
6195 components:
6196 schemas:
6197 User:
6198 type: object
6199 properties:
6200 id:
6201 type: string
6202 readOnly: true
6203 name:
6204 type: string
6205 `
6206 model := buildSchemaFromYAML(t, yml)
6207 schema := getSchema(t, model, "User")
6208
6209 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6210 v := NewValidator(opts, 3.1)
6211
6212 // readOnly property "id" sent in a request should be rejected
6213 data := map[string]any{
6214 "id": "user-123",
6215 "name": "John",
6216 }
6217
6218 result := v.Validate(Input{
6219 Schema: schema,
6220 Data: data,
6221 Direction: DirectionRequest,
6222 Options: opts,
6223 BasePath: "$.body",
6224 Version: 3.1,
6225 })
6226
6227 assert.False(t, result.Valid)
6228 require.Len(t, result.UndeclaredValues, 1)
6229 assert.Equal(t, "id", result.UndeclaredValues[0].Name)
6230 assert.Equal(t, "$.body.id", result.UndeclaredValues[0].Path)
6231 assert.Equal(t, TypeReadOnlyProperty, result.UndeclaredValues[0].Type)
6232 assert.Equal(t, DirectionRequest, result.UndeclaredValues[0].Direction)
6233 }
6234
6235 func TestStrictValidator_RejectReadOnly_Disabled(t *testing.T) {
6236 yml := `openapi: "3.1.0"
6237 info:
6238 title: Test
6239 version: "1.0"
6240 paths: {}
6241 components:
6242 schemas:
6243 User:
6244 type: object
6245 properties:
6246 id:
6247 type: string
6248 readOnly: true
6249 name:
6250 type: string
6251 `
6252 model := buildSchemaFromYAML(t, yml)
6253 schema := getSchema(t, model, "User")
6254
6255 // Flag off — backward compat: no violation
6256 opts := config.NewValidationOptions(config.WithStrictMode())
6257 v := NewValidator(opts, 3.1)
6258
6259 data := map[string]any{
6260 "id": "user-123",
6261 "name": "John",
6262 }
6263
6264 result := v.Validate(Input{
6265 Schema: schema,
6266 Data: data,
6267 Direction: DirectionRequest,
6268 Options: opts,
6269 BasePath: "$.body",
6270 Version: 3.1,
6271 })
6272
6273 assert.True(t, result.Valid)
6274 assert.Empty(t, result.UndeclaredValues)
6275 }
6276
6277 func TestStrictValidator_RejectReadOnly_InResponse_NoEffect(t *testing.T) {
6278 yml := `openapi: "3.1.0"
6279 info:
6280 title: Test
6281 version: "1.0"
6282 paths: {}
6283 components:
6284 schemas:
6285 User:
6286 type: object
6287 properties:
6288 id:
6289 type: string
6290 readOnly: true
6291 name:
6292 type: string
6293 `
6294 model := buildSchemaFromYAML(t, yml)
6295 schema := getSchema(t, model, "User")
6296
6297 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6298 v := NewValidator(opts, 3.1)
6299
6300 // readOnly in response is fine — readOnly only applies to requests
6301 data := map[string]any{
6302 "id": "user-123",
6303 "name": "John",
6304 }
6305
6306 result := v.Validate(Input{
6307 Schema: schema,
6308 Data: data,
6309 Direction: DirectionResponse,
6310 Options: opts,
6311 BasePath: "$.body",
6312 Version: 3.1,
6313 })
6314
6315 assert.True(t, result.Valid)
6316 assert.Empty(t, result.UndeclaredValues)
6317 }
6318
6319 func TestStrictValidator_RejectReadOnly_NestedObject(t *testing.T) {
6320 yml := `openapi: "3.1.0"
6321 info:
6322 title: Test
6323 version: "1.0"
6324 paths: {}
6325 components:
6326 schemas:
6327 User:
6328 type: object
6329 properties:
6330 name:
6331 type: string
6332 metadata:
6333 type: object
6334 properties:
6335 createdAt:
6336 type: string
6337 readOnly: true
6338 updatedBy:
6339 type: string
6340 `
6341 model := buildSchemaFromYAML(t, yml)
6342 schema := getSchema(t, model, "User")
6343
6344 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6345 v := NewValidator(opts, 3.1)
6346
6347 data := map[string]any{
6348 "name": "John",
6349 "metadata": map[string]any{
6350 "createdAt": "2024-01-01",
6351 "updatedBy": "admin",
6352 },
6353 }
6354
6355 result := v.Validate(Input{
6356 Schema: schema,
6357 Data: data,
6358 Direction: DirectionRequest,
6359 Options: opts,
6360 BasePath: "$.body",
6361 Version: 3.1,
6362 })
6363
6364 assert.False(t, result.Valid)
6365 require.Len(t, result.UndeclaredValues, 1)
6366 assert.Equal(t, "createdAt", result.UndeclaredValues[0].Name)
6367 assert.Equal(t, "$.body.metadata.createdAt", result.UndeclaredValues[0].Path)
6368 assert.Equal(t, TypeReadOnlyProperty, result.UndeclaredValues[0].Type)
6369 }
6370
6371 func TestStrictValidator_RejectReadOnly_AllOf(t *testing.T) {
6372 yml := `openapi: "3.1.0"
6373 info:
6374 title: Test
6375 version: "1.0"
6376 paths: {}
6377 components:
6378 schemas:
6379 Combined:
6380 allOf:
6381 - type: object
6382 properties:
6383 id:
6384 type: string
6385 readOnly: true
6386 - type: object
6387 properties:
6388 name:
6389 type: string
6390 `
6391 model := buildSchemaFromYAML(t, yml)
6392 schema := getSchema(t, model, "Combined")
6393
6394 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6395 v := NewValidator(opts, 3.1)
6396
6397 data := map[string]any{
6398 "id": "combined-1",
6399 "name": "Test",
6400 }
6401
6402 result := v.Validate(Input{
6403 Schema: schema,
6404 Data: data,
6405 Direction: DirectionRequest,
6406 Options: opts,
6407 BasePath: "$.body",
6408 Version: 3.1,
6409 })
6410
6411 assert.False(t, result.Valid)
6412 require.Len(t, result.UndeclaredValues, 1)
6413 assert.Equal(t, "id", result.UndeclaredValues[0].Name)
6414 assert.Equal(t, TypeReadOnlyProperty, result.UndeclaredValues[0].Type)
6415 }
6416
6417 func TestStrictValidator_RejectWriteOnly_InResponse(t *testing.T) {
6418 yml := `openapi: "3.1.0"
6419 info:
6420 title: Test
6421 version: "1.0"
6422 paths: {}
6423 components:
6424 schemas:
6425 User:
6426 type: object
6427 properties:
6428 name:
6429 type: string
6430 password:
6431 type: string
6432 writeOnly: true
6433 `
6434 model := buildSchemaFromYAML(t, yml)
6435 schema := getSchema(t, model, "User")
6436
6437 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectWriteOnly())
6438 v := NewValidator(opts, 3.1)
6439
6440 // writeOnly property "password" in response should be rejected
6441 data := map[string]any{
6442 "name": "John",
6443 "password": "secret",
6444 }
6445
6446 result := v.Validate(Input{
6447 Schema: schema,
6448 Data: data,
6449 Direction: DirectionResponse,
6450 Options: opts,
6451 BasePath: "$.body",
6452 Version: 3.1,
6453 })
6454
6455 assert.False(t, result.Valid)
6456 require.Len(t, result.UndeclaredValues, 1)
6457 assert.Equal(t, "password", result.UndeclaredValues[0].Name)
6458 assert.Equal(t, "$.body.password", result.UndeclaredValues[0].Path)
6459 assert.Equal(t, TypeWriteOnlyProperty, result.UndeclaredValues[0].Type)
6460 assert.Equal(t, DirectionResponse, result.UndeclaredValues[0].Direction)
6461 }
6462
6463 func TestStrictValidator_RejectWriteOnly_Disabled(t *testing.T) {
6464 yml := `openapi: "3.1.0"
6465 info:
6466 title: Test
6467 version: "1.0"
6468 paths: {}
6469 components:
6470 schemas:
6471 User:
6472 type: object
6473 properties:
6474 name:
6475 type: string
6476 password:
6477 type: string
6478 writeOnly: true
6479 `
6480 model := buildSchemaFromYAML(t, yml)
6481 schema := getSchema(t, model, "User")
6482
6483 // Flag off — backward compat: no violation
6484 opts := config.NewValidationOptions(config.WithStrictMode())
6485 v := NewValidator(opts, 3.1)
6486
6487 data := map[string]any{
6488 "name": "John",
6489 "password": "secret",
6490 }
6491
6492 result := v.Validate(Input{
6493 Schema: schema,
6494 Data: data,
6495 Direction: DirectionResponse,
6496 Options: opts,
6497 BasePath: "$.body",
6498 Version: 3.1,
6499 })
6500
6501 assert.True(t, result.Valid)
6502 assert.Empty(t, result.UndeclaredValues)
6503 }
6504
6505 func TestStrictValidator_RejectWriteOnly_InRequest_NoEffect(t *testing.T) {
6506 yml := `openapi: "3.1.0"
6507 info:
6508 title: Test
6509 version: "1.0"
6510 paths: {}
6511 components:
6512 schemas:
6513 User:
6514 type: object
6515 properties:
6516 name:
6517 type: string
6518 password:
6519 type: string
6520 writeOnly: true
6521 `
6522 model := buildSchemaFromYAML(t, yml)
6523 schema := getSchema(t, model, "User")
6524
6525 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectWriteOnly())
6526 v := NewValidator(opts, 3.1)
6527
6528 // writeOnly in request is fine — writeOnly only applies to responses
6529 data := map[string]any{
6530 "name": "John",
6531 "password": "secret",
6532 }
6533
6534 result := v.Validate(Input{
6535 Schema: schema,
6536 Data: data,
6537 Direction: DirectionRequest,
6538 Options: opts,
6539 BasePath: "$.body",
6540 Version: 3.1,
6541 })
6542
6543 assert.True(t, result.Valid)
6544 assert.Empty(t, result.UndeclaredValues)
6545 }
6546
6547 func TestStrictValidator_RejectWriteOnly_NestedObject(t *testing.T) {
6548 yml := `openapi: "3.1.0"
6549 info:
6550 title: Test
6551 version: "1.0"
6552 paths: {}
6553 components:
6554 schemas:
6555 User:
6556 type: object
6557 properties:
6558 name:
6559 type: string
6560 auth:
6561 type: object
6562 properties:
6563 token:
6564 type: string
6565 writeOnly: true
6566 provider:
6567 type: string
6568 `
6569 model := buildSchemaFromYAML(t, yml)
6570 schema := getSchema(t, model, "User")
6571
6572 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectWriteOnly())
6573 v := NewValidator(opts, 3.1)
6574
6575 data := map[string]any{
6576 "name": "John",
6577 "auth": map[string]any{
6578 "token": "secret-token",
6579 "provider": "google",
6580 },
6581 }
6582
6583 result := v.Validate(Input{
6584 Schema: schema,
6585 Data: data,
6586 Direction: DirectionResponse,
6587 Options: opts,
6588 BasePath: "$.body",
6589 Version: 3.1,
6590 })
6591
6592 assert.False(t, result.Valid)
6593 require.Len(t, result.UndeclaredValues, 1)
6594 assert.Equal(t, "token", result.UndeclaredValues[0].Name)
6595 assert.Equal(t, "$.body.auth.token", result.UndeclaredValues[0].Path)
6596 assert.Equal(t, TypeWriteOnlyProperty, result.UndeclaredValues[0].Type)
6597 }
6598
6599 func TestStrictValidator_RejectBoth_Enabled(t *testing.T) {
6600 yml := `openapi: "3.1.0"
6601 info:
6602 title: Test
6603 version: "1.0"
6604 paths: {}
6605 components:
6606 schemas:
6607 User:
6608 type: object
6609 properties:
6610 id:
6611 type: string
6612 readOnly: true
6613 name:
6614 type: string
6615 password:
6616 type: string
6617 writeOnly: true
6618 `
6619 model := buildSchemaFromYAML(t, yml)
6620 schema := getSchema(t, model, "User")
6621
6622 // Both flags on
6623 opts := config.NewValidationOptions(
6624 config.WithStrictMode(),
6625 config.WithStrictRejectReadOnly(),
6626 config.WithStrictRejectWriteOnly(),
6627 )
6628
6629 // Test request: readOnly "id" should be rejected
6630 v := NewValidator(opts, 3.1)
6631 dataRequest := map[string]any{
6632 "id": "user-123",
6633 "name": "John",
6634 "password": "secret",
6635 }
6636 resultRequest := v.Validate(Input{
6637 Schema: schema,
6638 Data: dataRequest,
6639 Direction: DirectionRequest,
6640 Options: opts,
6641 BasePath: "$.body",
6642 Version: 3.1,
6643 })
6644 assert.False(t, resultRequest.Valid)
6645 require.Len(t, resultRequest.UndeclaredValues, 1)
6646 assert.Equal(t, "id", resultRequest.UndeclaredValues[0].Name)
6647 assert.Equal(t, TypeReadOnlyProperty, resultRequest.UndeclaredValues[0].Type)
6648
6649 // Test response: writeOnly "password" should be rejected
6650 v2 := NewValidator(opts, 3.1)
6651 dataResponse := map[string]any{
6652 "id": "user-123",
6653 "name": "John",
6654 "password": "secret",
6655 }
6656 resultResponse := v2.Validate(Input{
6657 Schema: schema,
6658 Data: dataResponse,
6659 Direction: DirectionResponse,
6660 Options: opts,
6661 BasePath: "$.body",
6662 Version: 3.1,
6663 })
6664 assert.False(t, resultResponse.Valid)
6665 require.Len(t, resultResponse.UndeclaredValues, 1)
6666 assert.Equal(t, "password", resultResponse.UndeclaredValues[0].Name)
6667 assert.Equal(t, TypeWriteOnlyProperty, resultResponse.UndeclaredValues[0].Type)
6668 }
6669
6670 func TestStrictValidator_RejectReadOnly_AdditionalPropertiesFalse(t *testing.T) {
6671 // Covers schema_walker.go recurseIntoDeclaredProperties:
6672 // explicit property path and patternProperties path
6673 yml := `openapi: "3.1.0"
6674 info:
6675 title: Test
6676 version: "1.0"
6677 paths: {}
6678 components:
6679 schemas:
6680 Strict:
6681 type: object
6682 additionalProperties: false
6683 properties:
6684 id:
6685 type: string
6686 readOnly: true
6687 name:
6688 type: string
6689 patternProperties:
6690 "^x-":
6691 type: string
6692 readOnly: true
6693 `
6694 model := buildSchemaFromYAML(t, yml)
6695 schema := getSchema(t, model, "Strict")
6696
6697 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6698 v := NewValidator(opts, 3.1)
6699
6700 data := map[string]any{
6701 "id": "user-1",
6702 "name": "John",
6703 "x-custom": "value",
6704 }
6705
6706 result := v.Validate(Input{
6707 Schema: schema,
6708 Data: data,
6709 Direction: DirectionRequest,
6710 Options: opts,
6711 BasePath: "$.body",
6712 Version: 3.1,
6713 })
6714
6715 assert.False(t, result.Valid)
6716 assert.Len(t, result.UndeclaredValues, 2)
6717
6718 names := []string{result.UndeclaredValues[0].Name, result.UndeclaredValues[1].Name}
6719 assert.Contains(t, names, "id")
6720 assert.Contains(t, names, "x-custom")
6721 for _, uv := range result.UndeclaredValues {
6722 assert.Equal(t, TypeReadOnlyProperty, uv.Type)
6723 }
6724 }
6725
6726 func TestStrictValidator_RejectReadOnly_OneOf(t *testing.T) {
6727 // Covers polymorphic.go validateVariantWithParent path
6728 yml := `openapi: "3.1.0"
6729 info:
6730 title: Test
6731 version: "1.0"
6732 paths: {}
6733 components:
6734 schemas:
6735 OneOfSchema:
6736 type: object
6737 oneOf:
6738 - type: object
6739 properties:
6740 id:
6741 type: string
6742 readOnly: true
6743 email:
6744 type: string
6745 `
6746 model := buildSchemaFromYAML(t, yml)
6747 schema := getSchema(t, model, "OneOfSchema")
6748
6749 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6750 v := NewValidator(opts, 3.1)
6751
6752 data := map[string]any{
6753 "id": "user-1",
6754 "email": "[email protected]",
6755 }
6756
6757 result := v.Validate(Input{
6758 Schema: schema,
6759 Data: data,
6760 Direction: DirectionRequest,
6761 Options: opts,
6762 BasePath: "$.body",
6763 Version: 3.1,
6764 })
6765
6766 assert.False(t, result.Valid)
6767 require.Len(t, result.UndeclaredValues, 1)
6768 assert.Equal(t, "id", result.UndeclaredValues[0].Name)
6769 assert.Equal(t, TypeReadOnlyProperty, result.UndeclaredValues[0].Type)
6770 }
6771
6772 func TestStrictValidator_RejectReadOnly_OneOfAdditionalPropertiesFalse(t *testing.T) {
6773 // Covers polymorphic.go recurseIntoDeclaredPropertiesWithMerged path
6774 yml := `openapi: "3.1.0"
6775 info:
6776 title: Test
6777 version: "1.0"
6778 paths: {}
6779 components:
6780 schemas:
6781 OneOfStrict:
6782 type: object
6783 additionalProperties: false
6784 properties:
6785 name:
6786 type: string
6787 oneOf:
6788 - type: object
6789 additionalProperties: false
6790 properties:
6791 name:
6792 type: string
6793 id:
6794 type: string
6795 readOnly: true
6796 data:
6797 type: string
6798 `
6799 model := buildSchemaFromYAML(t, yml)
6800 schema := getSchema(t, model, "OneOfStrict")
6801
6802 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6803 v := NewValidator(opts, 3.1)
6804
6805 data := map[string]any{
6806 "name": "test",
6807 "id": "should-be-rejected",
6808 "data": "valid",
6809 }
6810
6811 result := v.Validate(Input{
6812 Schema: schema,
6813 Data: data,
6814 Direction: DirectionRequest,
6815 Options: opts,
6816 BasePath: "$.body",
6817 Version: 3.1,
6818 })
6819
6820 assert.False(t, result.Valid)
6821 require.Len(t, result.UndeclaredValues, 1)
6822 assert.Equal(t, "id", result.UndeclaredValues[0].Name)
6823 assert.Equal(t, TypeReadOnlyProperty, result.UndeclaredValues[0].Type)
6824 }
6825
6826 func TestStrictValidator_RejectReadOnly_AllOfAdditionalPropertiesFalse(t *testing.T) {
6827 // Covers polymorphic.go recurseIntoAllOfDeclaredProperties path
6828 yml := `openapi: "3.1.0"
6829 info:
6830 title: Test
6831 version: "1.0"
6832 paths: {}
6833 components:
6834 schemas:
6835 AllOfStrict:
6836 type: object
6837 additionalProperties: false
6838 allOf:
6839 - type: object
6840 properties:
6841 id:
6842 type: string
6843 readOnly: true
6844 name:
6845 type: string
6846 `
6847 model := buildSchemaFromYAML(t, yml)
6848 schema := getSchema(t, model, "AllOfStrict")
6849
6850 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6851 v := NewValidator(opts, 3.1)
6852
6853 data := map[string]any{
6854 "id": "should-be-rejected",
6855 "name": "John",
6856 }
6857
6858 result := v.Validate(Input{
6859 Schema: schema,
6860 Data: data,
6861 Direction: DirectionRequest,
6862 Options: opts,
6863 BasePath: "$.body",
6864 Version: 3.1,
6865 })
6866
6867 assert.False(t, result.Valid)
6868 require.Len(t, result.UndeclaredValues, 1)
6869 assert.Equal(t, "id", result.UndeclaredValues[0].Name)
6870 assert.Equal(t, TypeReadOnlyProperty, result.UndeclaredValues[0].Type)
6871 }
6872
6873 func TestStrictValidator_CheckReadWriteOnlyViolation_NilSchema(t *testing.T) {
6874 opts := config.NewValidationOptions(config.WithStrictMode(), config.WithStrictRejectReadOnly())
6875 v := NewValidator(opts, 3.1)
6876
6877 _, ok := v.checkReadWriteOnlyViolation("$.body.x", "x", "val", nil, DirectionRequest)
6878 assert.False(t, ok)
6879 }