Debian Codegraph @

schema_validation/validate_document_test.go

raw ◀ ▶
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": make(chan int),
187 }
188
189 normalized, err := normalizeJSON(payload)
190
191 assert.Nil(t, normalized)
•192 if assert.Error(t, err) {
193 assert.Contains(t, err.Error(), "unsupported type: chan int")
194 }
195 }
196
197 func TestValidateDocument_NormalizationErrorDoesNotValidateNil(t *testing.T) {
198 spec := `openapi: 3.1.0
199 info:
200 title: Test
201 version: 1.0.0
202 paths: {}`
203
204 doc, _ := libopenapi.NewDocument([]byte(spec))
205 badSpecJSON := map[string]interface{}{
206 "openapi": "3.1.0",
•207 "invalid": make(chan int),
208 }
209 info := doc.GetSpecInfo()
210 info.GetSpecJSON()
211 info.SpecJSON = &badSpecJSON
•212 info.SpecJSONBytes = nil
213
214 valid, errors := ValidateOpenAPIDocument(doc)
215
216 assert.False(t, valid)
217 assert.Len(t, errors, 1)
218 assert.Equal(t, "OpenAPI document validation failed", errors[0].Message)
219 assert.Contains(t, errors[0].Reason, "cannot be converted to JSON")
•220 assert.Contains(t, errors[0].Reason, "unsupported type: chan int")
221 assert.NotContains(t, errors[0].Reason, "got null, want object")
222 assert.Empty(t, errors[0].SchemaValidationErrors)
223 }
224
225 func TestValidateDocument_CorruptSpecJSONBytesFallbackNormalizationError(t *testing.T) {
226 spec := `openapi: 3.1.0
227 info:
228 title: Test
229 version: 1.0.0
230 paths: {}`
231
232 doc, _ := libopenapi.NewDocument([]byte(spec))
233 badSpecJSON := map[string]interface{}{
234 "openapi": "3.1.0",
•235 "invalid": make(chan int),
236 }
237 corrupt := []byte(`{not valid json!!!}`)
238 info := doc.GetSpecInfo()
•239 info.GetSpecJSON()
240 info.SpecJSON = &badSpecJSON
241 info.SpecJSONBytes = &corrupt
242
243 valid, errors := ValidateOpenAPIDocument(doc)
244
245 assert.False(t, valid)
246 assert.Len(t, errors, 1)
247 assert.Contains(t, errors[0].Reason, "cannot be converted to JSON")
248 assert.NotContains(t, errors[0].Reason, "got null, want object")
249 assert.Empty(t, errors[0].SchemaValidationErrors)
250 }
251
252 func TestValidateDocumentHelpers_DefensiveBranches(t *testing.T) {
253 assert.Nil(t, findNonStringMappingKey(nil))
254 assert.Nil(t, findNonStringMappingKeyInNode(nil, nil))
255 assert.Nil(t, findNonStringMappingKeyInMergeValue(nil, nil))
256 assert.False(t, isStringMappingKey(nil))
257 assert.False(t, isMergeMappingKey(nil))
258 assert.Equal(t, "", buildJSONPointer(nil))
259 assert.Equal(t, "non-string", yamlKeyType(nil))
260 assert.False(t, isOperationResponseStatusCodeKey([]string{"paths", "/test", "parameters", "responses", "200"}))
261
262 sequenceKey := &nonStringMappingKey{Sequence: true}
263 assert.Equal(t, "sequence", yamlKeyType(sequenceKey))
264
265 mergeKey := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"}
266 assert.True(t, isMergeMappingKey(mergeKey))
267
268 intKey := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: "1", Line: 2, Column: 5}
269 value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "one"}
270 mapping := &yaml.Node{
271 Kind: yaml.MappingNode,
272 Content: []*yaml.Node{intKey, value},
273 }
274 sequence := &yaml.Node{
275 Kind: yaml.SequenceNode,
276 Content: []*yaml.Node{mapping},
277 }
278
279 found := findNonStringMappingKeyInNode(sequence, []string{"items"})
280 assert.NotNil(t, found)
281 assert.Equal(t, []string{"items", "0", "1"}, found.Path)
282 assert.Equal(t, "1", found.Value)
283
284 found = findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.AliasNode, Alias: mapping}, []string{"merged"})
285 assert.NotNil(t, found)
286 assert.Equal(t, []string{"merged", "1"}, found.Path)
287
288 mergeMapping := &yaml.Node{
289 Kind: yaml.MappingNode,
290 Content: []*yaml.Node{mergeKey, mapping},
291 }
292 found = findNonStringMappingKeyInNode(mergeMapping, []string{"mergeTarget"})
293 assert.NotNil(t, found)
294 assert.Equal(t, []string{"mergeTarget", "1"}, found.Path)
295
296 mergeSequence := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{mapping}}
297 found = findNonStringMappingKeyInMergeValue(mergeSequence, []string{"mergedSequence"})
298 assert.NotNil(t, found)
299 assert.Equal(t, []string{"mergedSequence", "1"}, found.Path)
300
301 assert.Nil(t, findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.SequenceNode}, []string{"empty"}))
302 assert.Nil(t, findNonStringMappingKeyInMergeValue(&yaml.Node{Kind: yaml.AliasNode}, []string{"merged"}))
303 }
304
305 // Helper function to test the validation logic directly
306 func validateOpenAPIDocumentWithMalformedSchema(loadedSchema string, decodedDocument map[string]interface{}) (bool, []*liberrors.ValidationError) {
307 options := config.NewValidationOptions()
308 var validationErrors []*liberrors.ValidationError
309
310 // This replicates the exact logic from validate_document.go:40-127
311 _, err := helpers.NewCompiledSchema("schema", []byte(loadedSchema), options)
312 if err != nil {
313 // schema compilation failed, return validation error instead of panicking
314 // NO SchemaValidationFailure for pre-validation errors like compilation failures
315 validationErrors = append(validationErrors, &liberrors.ValidationError{
316 ValidationType: helpers.Schema,
317 ValidationSubType: "compilation",
318 Message: "OpenAPI document schema compilation failed",
319 Reason: fmt.Sprintf("The OpenAPI schema failed to compile: %s", err.Error()),
320 SpecLine: 1,
321 SpecCol: 0,
322 HowToFix: "check the OpenAPI schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs",
323 Context: loadedSchema,
324 })
325 return false, validationErrors
326 }
327
328 // If compilation succeeded, continue with normal validation logic
329 // (This would be the rest of the validate_document.go logic)
330 return true, nil
331 }
332
333 func TestValidateDocument_SchemaCompilationFailure(t *testing.T) {
334 // Test the schema compilation error handling by providing invalid JSON schema
335 malformedSchema := `{"type": "object", "properties": {"test": invalid_json_here}}`
336 decodedDocument := map[string]interface{}{
337 "openapi": "3.1.0",
338 "info": map[string]interface{}{
339 "title": "Test API",
340 "version": "1.0.0",
341 },
342 }
343
344 // Call our helper function which replicates the exact logic from validate_document.go
345 valid, errors := validateOpenAPIDocumentWithMalformedSchema(malformedSchema, decodedDocument)
346
347 // Should fail validation due to schema compilation error
348 assert.False(t, valid)
349 assert.NotEmpty(t, errors)
350
351 // Verify we got a schema compilation error with the exact same structure
352 validationError := errors[0]
353 assert.Equal(t, helpers.Schema, validationError.ValidationType)
354 assert.Equal(t, "compilation", validationError.ValidationSubType)
355 assert.Equal(t, "OpenAPI document schema compilation failed", validationError.Message)
356 assert.Contains(t, validationError.Reason, "The OpenAPI schema failed to compile")
357 assert.Contains(t, validationError.HowToFix, "complex regex patterns")
358 assert.Equal(t, malformedSchema, validationError.Context)
359 assert.Equal(t, 1, validationError.SpecLine)
360 assert.Equal(t, 0, validationError.SpecCol)
361
362 // Schema compilation errors don't have SchemaValidationFailure objects
363 assert.Empty(t, validationError.SchemaValidationErrors)
364 }
365
366 // TestValidateDocument_CompilationFailure tests the actual ValidateOpenAPIDocument function
367 // with a corrupted document that causes schema compilation to fail
368 func TestValidateDocument_CompilationFailure(t *testing.T) {
369 doc, _ := libopenapi.NewDocumentWithTypeCheck([]byte(`{}`), true)
370 doc.GetSpecInfo().APISchema = `{"type": "object", "properties": {"test": :bad"": JSON: } here.}}`
371 // validate!
372 valid, errors := ValidateOpenAPIDocument(doc)
373 assert.False(t, valid)
374 assert.Len(t, errors, 1)
375 assert.Contains(t, errors[0].Reason, "The OpenAPI schema failed to compile")
376 assert.Nil(t, errors[0].SchemaValidationErrors, "Compilation errors should not have SchemaValidationErrors")
377 }
378
379 func TestValidateSchema_ValidateLicenseIdentifier(t *testing.T) {
380 spec := `openapi: 3.1.0
381 info:
382 version: 1.0.0
383 title: Test
384 license:
385 name: Apache 2.0
386 url: https://opensource.org/licenses/Apache-2.0
387 identifier: Apache-2.0
388 components:
389 schemas:
390 Pet:
391 type: string`
392
393 doc, _ := libopenapi.NewDocument([]byte(spec))
394
395 // validate!
396 valid, errors := ValidateOpenAPIDocument(doc)
397
398 assert.False(t, valid)
399 assert.Len(t, errors, 1)
400 assert.Len(t, errors[0].SchemaValidationErrors, 1)
401 }
402
403 func TestValidateSchema_GeneratePointlessValidation(t *testing.T) {
404 spec := `openapi: 3.1.0
405 info:
406 version: 1
407 `
408
409 doc, _ := libopenapi.NewDocument([]byte(spec))
410
411 // validate!
412 valid, errors := ValidateOpenAPIDocument(doc)
413
414 assert.False(t, valid)
415 assert.Len(t, errors, 1)
416 assert.Len(t, errors[0].SchemaValidationErrors, 6)
417 }
418
419 func TestValidateDocument_NilSpecJSON(t *testing.T) {
420 // Create a document with minimal valid OpenAPI content
421 spec := `openapi: 3.1.0
422 info:
423 version: 1.0.0
424 title: Test
425 `
426
427 doc, _ := libopenapi.NewDocument([]byte(spec))
428
429 // Simulate the nil SpecJSON scenario by setting both to nil
430 info := doc.GetSpecInfo()
•431 info.GetSpecJSON()
432 info.SpecJSON = nil
433 info.SpecJSONBytes = nil
434
435 // validate!
436 valid, errors := ValidateOpenAPIDocument(doc)
437
438 // Should fail validation due to nil SpecJSON
439 assert.False(t, valid)
440 assert.Len(t, errors, 1)
441
442 // Verify error structure
443 validationError := errors[0]
444 assert.Equal(t, helpers.Schema, validationError.ValidationType)
445 assert.Equal(t, "document", validationError.ValidationSubType)
446 assert.Equal(t, "OpenAPI document validation failed", validationError.Message)
447 assert.Contains(t, validationError.Reason, "SpecJSON is nil")
448 assert.Contains(t, validationError.HowToFix, "ensure the OpenAPI document is valid")
449 assert.Equal(t, 1, validationError.SpecLine)
450 assert.Equal(t, 0, validationError.SpecCol)
451
452 // Pre-validation errors should not have SchemaValidationErrors
453 assert.Empty(t, validationError.SchemaValidationErrors)
454 }
455
456 func TestValidateDocument_WithPrecompiledSchema(t *testing.T) {
457 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
458 doc, _ := libopenapi.NewDocument(petstore)
459
460 info := doc.GetSpecInfo()
•461 info.GetSpecJSON()
462
463 // Pre-compile the schema
464 options := config.NewValidationOptions()
465 compiledSchema, err := helpers.NewCompiledSchema("schema", []byte(info.APISchema), options)
466 assert.NoError(t, err)
467
468 // Validate with precompiled schema
469 valid, errs := ValidateOpenAPIDocumentWithPrecompiled(doc, compiledSchema)
470 assert.True(t, valid)
471 assert.Len(t, errs, 0)
472
473 // Validate without precompiled schema (should produce identical results)
474 valid2, errs2 := ValidateOpenAPIDocument(doc)
475 assert.True(t, valid2)
476 assert.Len(t, errs2, 0)
477 }
478
479 func TestValidateDocument_WithPrecompiledSchema_Invalid(t *testing.T) {
480 petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml")
481 doc, _ := libopenapi.NewDocument(petstore)
482
483 info := doc.GetSpecInfo()
•484 info.GetSpecJSON()
485
486 // Pre-compile the schema
487 options := config.NewValidationOptions()
488 compiledSchema, err := helpers.NewCompiledSchema("schema", []byte(info.APISchema), options)
489 assert.NoError(t, err)
490
491 // Validate with precompiled schema
492 valid, errs := ValidateOpenAPIDocumentWithPrecompiled(doc, compiledSchema)
493 assert.False(t, valid)
494 assert.Len(t, errs, 1)
495 assert.Len(t, errs[0].SchemaValidationErrors, 6)
496
497 // Validate without precompiled schema (should produce identical error count)
498 valid2, errs2 := ValidateOpenAPIDocument(doc)
499 assert.False(t, valid2)
500 assert.Len(t, errs2, 1)
501 assert.Len(t, errs2[0].SchemaValidationErrors, 6)
502 }
503
504 func TestValidateDocument_SpecJSONBytesPath(t *testing.T) {
505 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
506 doc, _ := libopenapi.NewDocument(petstore)
507
508 info := doc.GetSpecInfo()
•509 info.GetSpecJSON()
510
511 // Nil out SpecJSON but leave SpecJSONBytes intact — forces the SpecJSONBytes path
512 assert.NotNil(t, info.SpecJSONBytes, "SpecJSONBytes should be populated by libopenapi")
513 info.SpecJSON = nil
514
515 valid, errs := ValidateOpenAPIDocument(doc)
516 assert.True(t, valid)
517 assert.Len(t, errs, 0)
518 }
519
520 func TestValidateDocument_SpecJSONBytesCorrupt_NilSpecJSON(t *testing.T) {
521 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
522 doc, _ := libopenapi.NewDocument(petstore)
523
524 info := doc.GetSpecInfo()
•525 info.GetSpecJSON()
526
527 // Put corrupt bytes in SpecJSONBytes so UnmarshalJSON fails,
528 // and nil out SpecJSON so the fallback normalizeJSON path is skipped.
529 // This exercises the nil guard on SpecJSON inside the error branch.
530 corrupt := []byte(`{not valid json!!!}`)
531 info.SpecJSONBytes = &corrupt
532 info.SpecJSON = nil
533
534 // Validation should fail before JSON Schema validation instead of validating nil.
535 valid, errs := ValidateOpenAPIDocument(doc)
536 assert.False(t, valid)
537 assert.Len(t, errs, 1)
538 assert.Contains(t, errs[0].Reason, "SpecJSONBytes cannot be decoded as JSON")
539 assert.Empty(t, errs[0].SchemaValidationErrors)
540 }
541
542 func TestValidateDocument_SpecJSONBytesCorrupt_FallbackToSpecJSON(t *testing.T) {
543 petstore, _ := os.ReadFile("../test_specs/petstorev3.json")
544 doc, _ := libopenapi.NewDocument(petstore)
545
546 info := doc.GetSpecInfo()
•547 info.GetSpecJSON()
548
549 // Put corrupt bytes in SpecJSONBytes so UnmarshalJSON fails,
550 // but leave SpecJSON intact so the fallback to normalizeJSON executes.
551 corrupt := []byte(`{not valid json!!!}`)
552 info.SpecJSONBytes = &corrupt
553
554 // Should still validate successfully via the SpecJSON fallback
555 valid, errs := ValidateOpenAPIDocument(doc)
556 assert.True(t, valid)
557 assert.Len(t, errs, 0)
558 }
559
560 func TestValidateDocument_SpecJSONBytesPath_Invalid(t *testing.T) {
561 petstore, _ := os.ReadFile("../test_specs/invalid_31.yaml")
562 doc, _ := libopenapi.NewDocument(petstore)
563
564 info := doc.GetSpecInfo()
•565 info.GetSpecJSON()
566
567 // Nil out SpecJSON but leave SpecJSONBytes intact
568 assert.NotNil(t, info.SpecJSONBytes, "SpecJSONBytes should be populated by libopenapi")
569 info.SpecJSON = nil
570
571 valid, errs := ValidateOpenAPIDocument(doc)
572 assert.False(t, valid)
573 assert.Len(t, errs, 1)
574 assert.NotEmpty(t, errs[0].SchemaValidationErrors)
575 }