Debian Codegraph @

schema_validation/validate_document_test.go

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package schema_validation
5
6 import (
7 "fmt"
8 "os"
9 "testing"
10
11 "github.com/pb33f/libopenapi"
12 "github.com/stretchr/testify/assert"
13 "go.yaml.in/yaml/v4"
14
15 "github.com/pb33f/libopenapi-validator/config"
16 liberrors "github.com/pb33f/libopenapi-validator/errors"
17 "github.com/pb33f/libopenapi-validator/helpers"
18 )
19
20 func TestValidateDocument(t *testing.T) {
21 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
22
23 doc, _ := libopenapi.NewDocument(petstore)
24
25 // validate!
26 valid, errors := ValidateOpenAPIDocument(doc)
27
28 assert.True(t, valid)
29 assert.Len(t, errors, 0)
30 }
31
32 func TestValidateDocument_31(t *testing.T) {
33 petstore, _ := os.ReadFile("../test_specs/valid_31.yaml")
34
35 doc, _ := libopenapi.NewDocument(petstore)
36
37 // validate!
38 valid, errors := ValidateOpenAPIDocument(doc)
39
40 assert.True(t, valid)
41 assert.Len(t, errors, 0)
42 }
43
44 func TestValidateDocument_Invalid31(t *testing.T) {
45 petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml")
46
47 doc, _ := libopenapi.NewDocument(petstore)
48
49 // validate!
50 valid, errors := ValidateOpenAPIDocument(doc)
51
52 assert.False(t, valid)
53 assert.Len(t, errors, 1)
54 assert.Len(t, errors[0].SchemaValidationErrors, 6)
55 }
56
57 func TestValidateDocument_UnquotedIntegerResponseCodeHelpfulError(t *testing.T) {
58 spec := `openapi: 3.1.0
59 info:
60 title: Test
61 version: 1.0.0
62 paths:
63 /test:
64 get:
65 responses:
66 200:
67 description: OK`
68
69 doc, _ := libopenapi.NewDocument([]byte(spec))
70
71 valid, errors := ValidateOpenAPIDocument(doc)
72
73 assert.False(t, valid)
74 assert.Len(t, errors, 1)
75 assert.Equal(t, "OpenAPI document validation failed", errors[0].Message)
76 assert.Contains(t, errors[0].Reason, "Response status code keys must be strings")
77 assert.Contains(t, errors[0].Reason, `quote 200 as "200"`)
78 assert.Contains(t, errors[0].Reason, "/paths/~1test/get/responses/200")
79 assert.NotContains(t, errors[0].Reason, "got null, want object")
80 assert.Contains(t, errors[0].HowToFix, `"200"`)
81 assert.Equal(t, 9, errors[0].SpecLine)
82 assert.Equal(t, 9, errors[0].SpecCol)
83 assert.Empty(t, errors[0].SchemaValidationErrors)
84 }
85
86 func TestValidateDocument_QuotedResponseCodeValid(t *testing.T) {
87 spec := `openapi: 3.1.0
88 info:
89 title: Test
90 version: 1.0.0
91 paths:
92 /test:
93 get:
94 responses:
95 "200":
96 description: OK`
97
98 doc, _ := libopenapi.NewDocument([]byte(spec))
99
100 valid, errors := ValidateOpenAPIDocument(doc)
101
102 assert.True(t, valid)
103 assert.Empty(t, errors)
104 }
105
106 func TestValidateDocument_YAMLMergeKeyValid(t *testing.T) {
107 spec := `openapi: 3.1.0
108 info:
109 title: Test
110 version: 1.0.0
111 x-base-response: &baseResponse
112 description: OK
113 paths:
114 /test:
115 get:
116 responses:
117 "200":
118 <<: *baseResponse`
119
120 doc, _ := libopenapi.NewDocument([]byte(spec))
121
122 valid, errors := ValidateOpenAPIDocument(doc)
123
124 assert.True(t, valid)
125 assert.Empty(t, errors)
126 }
127
128 func TestValidateDocument_YAMLMergeKeyDoesNotHideInvalidResponseCode(t *testing.T) {
129 spec := `openapi: 3.1.0
130 info:
131 title: Test
132 version: 1.0.0
133 x-base-responses: &baseResponses
134 default:
135 description: Default
136 paths:
137 /test:
138 get:
139 responses:
140 <<: *baseResponses
141 200:
142 description: OK`
143
144 doc, _ := libopenapi.NewDocument([]byte(spec))
145
146 valid, errors := ValidateOpenAPIDocument(doc)
147
148 assert.False(t, valid)
149 assert.Len(t, errors, 1)
150 assert.Contains(t, errors[0].Reason, "Response status code keys must be strings")
151 assert.Contains(t, errors[0].Reason, `quote 200 as "200"`)
152 assert.NotContains(t, errors[0].Reason, `merge key "<<"`)
153 assert.Equal(t, 13, errors[0].SpecLine)
154 assert.Empty(t, errors[0].SchemaValidationErrors)
155 }
156
157 func TestValidateDocument_GenericNonStringMappingKeyHelpfulError(t *testing.T) {
158 spec := `openapi: 3.1.0
159 info:
160 title: Test
161 version: 1.0.0
162 paths: {}
163 x-values:
164 1: one`
165
166 doc, _ := libopenapi.NewDocument([]byte(spec))
167
168 valid, errors := ValidateOpenAPIDocument(doc)
169
170 assert.False(t, valid)
171 assert.Len(t, errors, 1)
172 assert.Equal(t, "OpenAPI document validation failed", errors[0].Message)
173 assert.Contains(t, errors[0].Reason, "OpenAPI documents require string mapping keys")
174 assert.Contains(t, errors[0].Reason, `int key "1"`)
175 assert.Contains(t, errors[0].Reason, "/x-values/1")
176 assert.NotContains(t, errors[0].Reason, "got null, want object")
177 assert.Contains(t, errors[0].HowToFix, "Quote YAML mapping keys")
178 assert.Equal(t, 7, errors[0].SpecLine)
179 assert.Equal(t, 3, errors[0].SpecCol)
180 assert.Empty(t, errors[0].SchemaValidationErrors)
181 }
182
183 func TestNormalizeJSON_ReturnsMarshalError(t *testing.T) {
184 payload := map[string]interface{}{
185 "openapi": "3.1.0",
186 "invalid": map[interface{}]interface{}{
187 1: "one",
188 },
189 }
190
191 normalized, err := normalizeJSON(payload)
192
193 assert.Nil(t, normalized)
194 assert.Error(t, err)
195 assert.Contains(t, err.Error(), "unsupported type: map[interface {}]interface {}")
196 }
197
198 func TestValidateDocument_NormalizationErrorDoesNotValidateNil(t *testing.T) {
199 spec := `openapi: 3.1.0
200 info:
201 title: Test
202 version: 1.0.0
203 paths: {}`
204
205 doc, _ := libopenapi.NewDocument([]byte(spec))
206 badSpecJSON := map[string]interface{}{
207 "openapi": "3.1.0",
208 "invalid": map[interface{}]interface{}{
209 1: "one",
210 },
211 }
212 info := doc.GetSpecInfo()
213 info.GetSpecJSON()
214 info.SpecJSON = &badSpecJSON
215 info.SpecJSONBytes = nil
216
217 valid, errors := ValidateOpenAPIDocument(doc)
218
219 assert.False(t, valid)
220 assert.Len(t, errors, 1)
221 assert.Equal(t, "OpenAPI document validation failed", errors[0].Message)
222 assert.Contains(t, errors[0].Reason, "cannot be converted to JSON")
223 assert.Contains(t, errors[0].Reason, "unsupported type: map[interface {}]interface {}")
224 assert.NotContains(t, errors[0].Reason, "got null, want object")
225 assert.Empty(t, errors[0].SchemaValidationErrors)
226 }
227
228 func TestValidateDocument_CorruptSpecJSONBytesFallbackNormalizationError(t *testing.T) {
229 spec := `openapi: 3.1.0
230 info:
231 title: Test
232 version: 1.0.0
233 paths: {}`
234
235 doc, _ := libopenapi.NewDocument([]byte(spec))
236 badSpecJSON := map[string]interface{}{
237 "openapi": "3.1.0",
238 "invalid": map[interface{}]interface{}{
239 1: "one",
240 },
241 }
242 corrupt := []byte(`{not valid json!!!}`)
243 info := doc.GetSpecInfo()
244 info.GetSpecJSON()
245 info.SpecJSON = &badSpecJSON
246 info.SpecJSONBytes = &corrupt
247
248 valid, errors := ValidateOpenAPIDocument(doc)
249
250 assert.False(t, valid)
251 assert.Len(t, errors, 1)
252 assert.Contains(t, errors[0].Reason, "cannot be converted to JSON")
253 assert.NotContains(t, errors[0].Reason, "got null, want object")
254 assert.Empty(t, errors[0].SchemaValidationErrors)
255 }
256
257 func TestValidateDocumentHelpers_DefensiveBranches(t *testing.T) {
258 assert.Nil(t, findNonStringMappingKey(nil))
259 assert.Nil(t, findNonStringMappingKeyInNode(nil, nil))
260 assert.Nil(t, findNonStringMappingKeyInMergeValue(nil, nil))
261 assert.False(t, isStringMappingKey(nil))
262 assert.False(t, isMergeMappingKey(nil))
263 assert.Equal(t, "", buildJSONPointer(nil))
264 assert.Equal(t, "non-string", yamlKeyType(nil))
265 assert.False(t, isOperationResponseStatusCodeKey([]string{"paths", "/test", "parameters", "responses", "200"}))
266
267 sequenceKey := &nonStringMappingKey{Sequence: true}
268 assert.Equal(t, "sequence", yamlKeyType(sequenceKey))
269
270 mergeKey := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"}
271 assert.True(t, isMergeMappingKey(mergeKey))
272
273 intKey := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: "1", Line: 2, Column: 5}
274 value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "one"}
275 mapping := &yaml.Node{
276 Kind: yaml.MappingNode,
277 Content: []*yaml.Node{intKey, value},
278 }
279 sequence := &yaml.Node{
280 Kind: yaml.SequenceNode,
281 Content: []*yaml.Node{mapping},
282 }
283
284 found := findNonStringMappingKeyInNode(sequence, []string{"items"})
285 assert.NotNil(t, found)
286 assert.Equal(t, []string{"items", "0", "1"}, found.Path)
287 assert.Equal(t, "1", found.Value)
288
289 found = findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.AliasNode, Alias: mapping}, []string{"merged"})
290 assert.NotNil(t, found)
291 assert.Equal(t, []string{"merged", "1"}, found.Path)
292
293 mergeMapping := &yaml.Node{
294 Kind: yaml.MappingNode,
295 Content: []*yaml.Node{mergeKey, mapping},
296 }
297 found = findNonStringMappingKeyInNode(mergeMapping, []string{"mergeTarget"})
298 assert.NotNil(t, found)
299 assert.Equal(t, []string{"mergeTarget", "1"}, found.Path)
300
301 mergeSequence := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{mapping}}
302 found = findNonStringMappingKeyInMergeValue(mergeSequence, []string{"mergedSequence"})
303 assert.NotNil(t, found)
304 assert.Equal(t, []string{"mergedSequence", "1"}, found.Path)
305
306 assert.Nil(t, findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.SequenceNode}, []string{"empty"}))
307 assert.Nil(t, findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.AliasNode}, []string{"merged"}))
308 }
309
310 // Helper function to test the validation logic directly
311 func validateOpenAPIDocumentWithMalformedSchema(loadedSchema string, decodedDocument map[string]interface{}) (bool, []*liberrors.ValidationError) {
312 options := config.NewValidationOptions()
313 var validationErrors []*liberrors.ValidationError
314
315 // This replicates the exact logic from validate_document.go:40-127
316 _, err := helpers.NewCompiledSchema("schema", []byte(loadedSchema), options)
317 if err != nil {
318 // schema compilation failed, return validation error instead of panicking
319 // NO SchemaValidationFailure for pre-validation errors like compilation failures
320 validationErrors = append(validationErrors, &liberrors.ValidationError{
321 ValidationType: helpers.Schema,
322 ValidationSubType: "compilation",
323 Message: "OpenAPI document schema compilation failed",
324 Reason: fmt.Sprintf("The OpenAPI schema failed to compile: %s", err.Error()),
325 SpecLine: 1,
326 SpecCol: 0,
327 HowToFix: "check the OpenAPI schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs",
328 Context: loadedSchema,
329 })
330 return false, validationErrors
331 }
332
333 // If compilation succeeded, continue with normal validation logic
334 // (This would be the rest of the validate_document.go logic)
335 return true, nil
336 }
337
338 func TestValidateDocument_SchemaCompilationFailure(t *testing.T) {
339 // Test the schema compilation error handling by providing invalid JSON schema
340 malformedSchema := `{"type": "object", "properties": {"test": invalid_json_here}}`
341 decodedDocument := map[string]interface{}{
342 "openapi": "3.1.0",
343 "info": map[string]interface{}{
344 "title": "Test API",
345 "version": "1.0.0",
346 },
347 }
348
349 // Call our helper function which replicates the exact logic from validate_document.go
350 valid, errors := validateOpenAPIDocumentWithMalformedSchema(malformedSchema, decodedDocument)
351
352 // Should fail validation due to schema compilation error
353 assert.False(t, valid)
354 assert.NotEmpty(t, errors)
355
356 // Verify we got a schema compilation error with the exact same structure
357 validationError := errors[0]
358 assert.Equal(t, helpers.Schema, validationError.ValidationType)
359 assert.Equal(t, "compilation", validationError.ValidationSubType)
360 assert.Equal(t, "OpenAPI document schema compilation failed", validationError.Message)
361 assert.Contains(t, validationError.Reason, "The OpenAPI schema failed to compile")
362 assert.Contains(t, validationError.HowToFix, "complex regex patterns")
363 assert.Equal(t, malformedSchema, validationError.Context)
364 assert.Equal(t, 1, validationError.SpecLine)
365 assert.Equal(t, 0, validationError.SpecCol)
366
367 // Schema compilation errors don't have SchemaValidationFailure objects
368 assert.Empty(t, validationError.SchemaValidationErrors)
369 }
370
371 // TestValidateDocument_CompilationFailure tests the actual ValidateOpenAPIDocument function
372 // with a corrupted document that causes schema compilation to fail
373 func TestValidateDocument_CompilationFailure(t *testing.T) {
374 doc, _ := libopenapi.NewDocumentWithTypeCheck([]byte(`{}`), true)
375 doc.GetSpecInfo().APISchema = `{"type": "object", "properties": {"test": :bad"": JSON: } here.}}`
376 // validate!
377 valid, errors := ValidateOpenAPIDocument(doc)
378 assert.False(t, valid)
379 assert.Len(t, errors, 1)
380 assert.Contains(t, errors[0].Reason, "The OpenAPI schema failed to compile")
381 assert.Nil(t, errors[0].SchemaValidationErrors, "Compilation errors should not have SchemaValidationErrors")
382 }
383
384 func TestValidateSchema_ValidateLicenseIdentifier(t *testing.T) {
385 spec := `openapi: 3.1.0
386 info:
387 version: 1.0.0
388 title: Test
389 license:
390 name: Apache 2.0
391 url: https://opensource.org/licenses/Apache-2.0
392 identifier: Apache-2.0
393 components:
394 schemas:
395 Pet:
396 type: string`
397
398 doc, _ := libopenapi.NewDocument([]byte(spec))
399
400 // validate!
401 valid, errors := ValidateOpenAPIDocument(doc)
402
403 assert.False(t, valid)
404 assert.Len(t, errors, 1)
405 assert.Len(t, errors[0].SchemaValidationErrors, 1)
406 }
407
408 func TestValidateSchema_GeneratePointlessValidation(t *testing.T) {
409 spec := `openapi: 3.1.0
410 info:
411 version: 1
412 `
413
414 doc, _ := libopenapi.NewDocument([]byte(spec))
415
416 // validate!
417 valid, errors := ValidateOpenAPIDocument(doc)
418
419 assert.False(t, valid)
420 assert.Len(t, errors, 1)
421 assert.Len(t, errors[0].SchemaValidationErrors, 6)
422 }
423
424 func TestValidateDocument_NilSpecJSON(t *testing.T) {
425 // Create a document with minimal valid OpenAPI content
426 spec := `openapi: 3.1.0
427 info:
428 version: 1.0.0
429 title: Test
430 `
431
432 doc, _ := libopenapi.NewDocument([]byte(spec))
433
434 // Simulate the nil SpecJSON scenario by setting both to nil
435 info := doc.GetSpecInfo()
436 info.GetSpecJSON()
437 info.SpecJSON = nil
438 info.SpecJSONBytes = nil
439
440 // validate!
441 valid, errors := ValidateOpenAPIDocument(doc)
442
443 // Should fail validation due to nil SpecJSON
444 assert.False(t, valid)
445 assert.Len(t, errors, 1)
446
447 // Verify error structure
448 validationError := errors[0]
449 assert.Equal(t, helpers.Schema, validationError.ValidationType)
450 assert.Equal(t, "document", validationError.ValidationSubType)
451 assert.Equal(t, "OpenAPI document validation failed", validationError.Message)
452 assert.Contains(t, validationError.Reason, "SpecJSON is nil")
453 assert.Contains(t, validationError.HowToFix, "ensure the OpenAPI document is valid")
454 assert.Equal(t, 1, validationError.SpecLine)
455 assert.Equal(t, 0, validationError.SpecCol)
456
457 // Pre-validation errors should not have SchemaValidationErrors
458 assert.Empty(t, validationError.SchemaValidationErrors)
459 }
460
461 func TestValidateDocument_WithPrecompiledSchema(t *testing.T) {
462 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
463 doc, _ := libopenapi.NewDocument(petstore)
464
465 info := doc.GetSpecInfo()
466 info.GetSpecJSON()
467
468 // Pre-compile the schema
469 options := config.NewValidationOptions()
470 compiledSchema, err := helpers.NewCompiledSchema("schema", []byte(info.APISchema), options)
471 assert.NoError(t, err)
472
473 // Validate with precompiled schema
474 valid, errs := ValidateOpenAPIDocumentWithPrecompiled(doc, compiledSchema)
475 assert.True(t, valid)
476 assert.Len(t, errs, 0)
477
478 // Validate without precompiled schema (should produce identical results)
479 valid2, errs2 := ValidateOpenAPIDocument(doc)
480 assert.True(t, valid2)
481 assert.Len(t, errs2, 0)
482 }
483
484 func TestValidateDocument_WithPrecompiledSchema_Invalid(t *testing.T) {
485 petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml")
486 doc, _ := libopenapi.NewDocument(petstore)
487
488 info := doc.GetSpecInfo()
489 info.GetSpecJSON()
490
491 // Pre-compile the schema
492 options := config.NewValidationOptions()
493 compiledSchema, err := helpers.NewCompiledSchema("schema", []byte(info.APISchema), options)
494 assert.NoError(t, err)
495
496 // Validate with precompiled schema
497 valid, errs := ValidateOpenAPIDocumentWithPrecompiled(doc, compiledSchema)
498 assert.False(t, valid)
499 assert.Len(t, errs, 1)
500 assert.Len(t, errs[0].SchemaValidationErrors, 6)
501
502 // Validate without precompiled schema (should produce identical error count)
503 valid2, errs2 := ValidateOpenAPIDocument(doc)
504 assert.False(t, valid2)
505 assert.Len(t, errs2, 1)
506 assert.Len(t, errs2[0].SchemaValidationErrors, 6)
507 }
508
509 func TestValidateDocument_SpecJSONBytesPath(t *testing.T) {
510 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
511 doc, _ := libopenapi.NewDocument(petstore)
512
513 info := doc.GetSpecInfo()
514 info.GetSpecJSON()
515
516 // Nil out SpecJSON but leave SpecJSONBytes intact — forces the SpecJSONBytes path
517 assert.NotNil(t, info.SpecJSONBytes, "SpecJSONBytes should be populated by libopenapi")
518 info.SpecJSON = nil
519
520 valid, errs := ValidateOpenAPIDocument(doc)
521 assert.True(t, valid)
522 assert.Len(t, errs, 0)
523 }
524
525 func TestValidateDocument_SpecJSONBytesCorrupt_NilSpecJSON(t *testing.T) {
526 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
527 doc, _ := libopenapi.NewDocument(petstore)
528
529 info := doc.GetSpecInfo()
530 info.GetSpecJSON()
531
532 // Put corrupt bytes in SpecJSONBytes so UnmarshalJSON fails,
533 // and nil out SpecJSON so the fallback normalizeJSON path is skipped.
534 // This exercises the nil guard on SpecJSON inside the error branch.
535 corrupt := []byte(`{not valid json!!!}`)
536 info.SpecJSONBytes = &corrupt
537 info.SpecJSON = nil
538
539 // Validation should fail before JSON Schema validation instead of validating nil.
540 valid, errs := ValidateOpenAPIDocument(doc)
541 assert.False(t, valid)
542 assert.Len(t, errs, 1)
543 assert.Contains(t, errs[0].Reason, "SpecJSONBytes cannot be decoded as JSON")
544 assert.Empty(t, errs[0].SchemaValidationErrors)
545 }
546
547 func TestValidateDocument_SpecJSONBytesCorrupt_FallbackToSpecJSON(t *testing.T) {
548 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
549 doc, _ := libopenapi.NewDocument(petstore)
550
551 info := doc.GetSpecInfo()
552 info.GetSpecJSON()
553
554 // Put corrupt bytes in SpecJSONBytes so UnmarshalJSON fails,
555 // but leave SpecJSON intact so the fallback to normalizeJSON executes.
556 corrupt := []byte(`{not valid json!!!}`)
557 info.SpecJSONBytes = &corrupt
558
559 // Should still validate successfully via the SpecJSON fallback
560 valid, errs := ValidateOpenAPIDocument(doc)
561 assert.True(t, valid)
562 assert.Len(t, errs, 0)
563 }
564
565 func TestValidateDocument_SpecJSONBytesPath_Invalid(t *testing.T) {
566 petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml")
567 doc, _ := libopenapi.NewDocument(petstore)
568
569 info := doc.GetSpecInfo()
570 info.GetSpecJSON()
571
572 // Nil out SpecJSON but leave SpecJSONBytes intact
573 assert.NotNil(t, info.SpecJSONBytes, "SpecJSONBytes should be populated by libopenapi")
574 info.SpecJSON = nil
575
576 valid, errs := ValidateOpenAPIDocument(doc)
577 assert.False(t, valid)
578 assert.Len(t, errs, 1)
579 assert.NotEmpty(t, errs[0].SchemaValidationErrors)
580 }