Debian Codegraph @

schema_validation/validate_document.go

raw ◀ ▶
1 Debian patch 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 "bytes"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "strconv"
12 "strings"
13
14 "github.com/pb33f/libopenapi"
15 "github.com/santhosh-tekuri/jsonschema/v6"
16 "go.yaml.in/yaml/v4"
17 "golang.org/x/text/language"
18 "golang.org/x/text/message"
19
20 "github.com/pb33f/libopenapi-validator/config"
21 liberrors "github.com/pb33f/libopenapi-validator/errors"
22 "github.com/pb33f/libopenapi-validator/helpers"
23 )
24
25 type nonStringMappingKey struct {
26 Value string
27 Tag string
28 Path []string
29 Line int
30 Column int
31 Sequence bool
32 }
33
34 func normalizeJSON(data any) (any, error) {
35 d, err := json.Marshal(data)
36 if err != nil {
37 return nil, err
38 }
39
40 var normalized any
41 _ = json.Unmarshal(d, &normalized)
42 return normalized, nil
43 }
44
45 func findNonStringMappingKey(rootNode *yaml.Node) *nonStringMappingKey {
46 if rootNode == nil {
47 return nil
48 }
49 return findNonStringMappingKeyInNode(rootNode, nil)
50 }
51
52 func findNonStringMappingKeyInNode(node *yaml.Node, path []string) *nonStringMappingKey {
53 if node == nil {
54 return nil
55 }
56
57 switch node.Kind {
58 case yaml.DocumentNode:
59 for _, child := range node.Content {
60 if found := findNonStringMappingKeyInNode(child, path); found != nil {
61 return found
62 }
63 }
64 case yaml.MappingNode:
65 for i := 0; i+1 < len(node.Content); i += 2 {
66 keyNode := node.Content[i]
67 valueNode := node.Content[i+1]
68 if isMergeMappingKey(keyNode) {
69 if found := findNonStringMappingKeyInMergeValue(valueNode, path); found != nil {
70 return found
71 }
72 continue
73 }
74 nextPath := appendPathSegment(path, keyNode.Value)
75 if !isStringMappingKey(keyNode) {
76 return &nonStringMappingKey{
77 Value: keyNode.Value,
78 Tag: keyNode.ShortTag(),
79 Path: nextPath,
80 Line: keyNode.Line,
81 Column: keyNode.Column,
82 Sequence: keyNode.Kind == yaml.SequenceNode,
83 }
84 }
85 if found := findNonStringMappingKeyInNode(valueNode, nextPath); found != nil {
86 return found
87 }
88 }
89 case yaml.SequenceNode:
90 for i, child := range node.Content {
91 if found := findNonStringMappingKeyInNode(child, appendPathSegment(path, strconv.Itoa(i))); found != nil {
92 return found
93 }
94 }
95 }
96
97 return nil
98 }
99
100 func findNonStringMappingKeyInMergeValue(node *yaml.Node, path []string) *nonStringMappingKey {
101 if node == nil {
102 return nil
103 }
104
105 switch node.Kind {
106 case yaml.AliasNode:
107 return findNonStringMappingKeyInMergeValue(node.Alias, path)
108 case yaml.SequenceNode:
109 for _, child := range node.Content {
110 if found := findNonStringMappingKeyInMergeValue(child, path); found != nil {
111 return found
112 }
113 }
114 return nil
115 default:
116 return findNonStringMappingKeyInNode(node, path)
117 }
118 }
119
120 func isStringMappingKey(keyNode *yaml.Node) bool {
121 if keyNode == nil || keyNode.Kind != yaml.ScalarNode {
122 return false
123 }
124 return keyNode.ShortTag() == "!!str"
125 }
126
127 func isMergeMappingKey(keyNode *yaml.Node) bool {
128 if keyNode == nil || keyNode.Kind != yaml.ScalarNode {
129 return false
130 }
131 return keyNode.ShortTag() == "!!merge" && keyNode.Value == "<<"
132 }
133
134 func appendPathSegment(path []string, segment string) []string {
135 next := make([]string, 0, len(path)+1)
136 next = append(next, path...)
137 return append(next, segment)
138 }
139
140 func buildJSONPointer(path []string) string {
141 if len(path) == 0 {
142 return ""
143 }
144 var builder strings.Builder
145 for _, segment := range path {
146 builder.WriteByte('/')
147 builder.WriteString(helpers.EscapeJSONPointerSegment(segment))
148 }
149 return builder.String()
150 }
151
152 func buildNonStringMappingKeyError(key *nonStringMappingKey) *liberrors.ValidationError {
153 pointer := buildJSONPointer(key.Path)
154 reason := fmt.Sprintf("OpenAPI documents require string mapping keys, but found %s key %q at %s",
155 yamlKeyType(key), key.Value, pointer)
156 howToFix := "Quote YAML mapping keys that should be strings, because OpenAPI documents must be representable as JSON objects"
157
158 if isOperationResponseStatusCodeKey(key.Path) {
159 reason = fmt.Sprintf("Response status code keys must be strings, quote %s as %q at %s",
160 key.Value, key.Value, pointer)
161 howToFix = fmt.Sprintf("Quote the response status code key, for example use %q instead of %s",
162 key.Value, key.Value)
163 }
164
165 return &liberrors.ValidationError{
166 ValidationType: helpers.Schema,
167 ValidationSubType: "document",
168 Message: "OpenAPI document validation failed",
169 Reason: reason,
170 SpecLine: key.Line,
171 SpecCol: key.Column,
172 HowToFix: howToFix,
173 Context: pointer,
174 }
175 }
176
177 func yamlKeyType(key *nonStringMappingKey) string {
178 if key == nil {
179 return "non-string"
180 }
181 if key.Sequence {
182 return "sequence"
183 }
184 return strings.TrimPrefix(key.Tag, "!!")
185 }
186
187 func isOperationResponseStatusCodeKey(path []string) bool {
188 if len(path) < 5 || path[0] != "paths" || path[len(path)-2] != "responses" {
189 return false
190 }
191 for _, segment := range path[2 : len(path)-2] {
192 if isHTTPMethod(segment) {
193 return true
194 }
195 }
196 return false
197 }
198
199 func isHTTPMethod(segment string) bool {
200 switch strings.ToLower(segment) {
201 case "get", "put", "post", "delete", "options", "head", "patch", "trace":
202 return true
203 default:
204 return false
205 }
206 }
207
208 func buildDocumentDecodeError(reason, context string) *liberrors.ValidationError {
209 return &liberrors.ValidationError{
210 ValidationType: helpers.Schema,
211 ValidationSubType: "document",
212 Message: "OpenAPI document validation failed",
213 Reason: reason,
214 SpecLine: 1,
215 SpecCol: 0,
216 HowToFix: "ensure the OpenAPI document is valid YAML/JSON and can be represented as JSON",
217 Context: context,
218 }
219 }
220
221 // ValidateOpenAPIDocument will validate an OpenAPI document against the OpenAPI 2, 3.0 and 3.1 schemas (depending on version)
222 // It will return true if the document is valid, false if it is not and a slice of ValidationError pointers.
223 func ValidateOpenAPIDocument(doc libopenapi.Document, opts ...config.Option) (bool, []*liberrors.ValidationError) {
224 return ValidateOpenAPIDocumentWithPrecompiled(doc, nil, opts...)
225 }
226
227 // ValidateOpenAPIDocumentWithPrecompiled validates an OpenAPI document against the OAS JSON Schema.
228 // When compiledSchema is non-nil it is used directly, skipping schema compilation.
229 // When SpecJSONBytes is available on the document's SpecInfo, the normalizeJSON round-trip is
230 // bypassed in favour of a single jsonschema.UnmarshalJSON call.
231 func ValidateOpenAPIDocumentWithPrecompiled(doc libopenapi.Document, compiledSchema *jsonschema.Schema, opts ...config.Option) (bool, []*liberrors.ValidationError) {
232 options := config.NewValidationOptions(opts...)
233
234 info := doc.GetSpecInfo()
235 loadedSchema := info.APISchema
236 var validationErrors []*liberrors.ValidationError
237
238 // Check if both JSON representations are nil before proceeding
•239 if info.GetSpecJSON() == nil && info.GetSpecJSONBytes() == nil {
240 validationErrors = append(validationErrors, &liberrors.ValidationError{
241 ValidationType: helpers.Schema,
242 ValidationSubType: "document",
243 Message: "OpenAPI document validation failed",
244 Reason: "The document's SpecJSON is nil, indicating the document was not properly parsed or is empty",
245 SpecLine: 1,
246 SpecCol: 0,
247 HowToFix: "ensure the OpenAPI document is valid YAML/JSON and can be properly parsed by libopenapi",
248 Context: "document root",
249 })
250 return false, validationErrors
251 }
252
253 if info.RootNode != nil {
254 if invalidKey := findNonStringMappingKey(info.RootNode); invalidKey != nil {
255 return false, []*liberrors.ValidationError{buildNonStringMappingKeyError(invalidKey)}
256 }
257 }
258
259 // Use the precompiled schema if provided, otherwise compile it
260 jsch := compiledSchema
261 if jsch == nil {
262 var err error
263 jsch, err = helpers.NewCompiledSchema("schema", []byte(loadedSchema), options)
264 if err != nil {
265 validationErrors = append(validationErrors, &liberrors.ValidationError{
266 ValidationType: helpers.Schema,
267 ValidationSubType: "compilation",
268 Message: "OpenAPI document schema compilation failed",
269 Reason: fmt.Sprintf("The OpenAPI schema failed to compile: %s", err.Error()),
270 SpecLine: 1,
271 SpecCol: 0,
272 HowToFix: "check the OpenAPI schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs",
273 Context: loadedSchema,
274 })
275 return false, validationErrors
276 }
277 }
278
279 // Build the normalized document value for validation.
280 // Prefer SpecJSONBytes (single unmarshal) over SpecJSON (marshal+unmarshal round-trip).
281 var normalized any
•282 if info.GetSpecJSONBytes() != nil && len(*info.GetSpecJSONBytes()) > 0 {
283 var err error
•284 normalized, err = jsonschema.UnmarshalJSON(bytes.NewReader(*info.GetSpecJSONBytes()))
285 if err != nil {
286 // Fall back to normalizeJSON if UnmarshalJSON fails
•287 if info.GetSpecJSON() != nil {
288 normalized, err = normalizeJSON(*info.GetSpecJSON())
289 if err != nil {
290 return false, []*liberrors.ValidationError{buildDocumentDecodeError(
291 fmt.Sprintf("The OpenAPI document cannot be converted to JSON: %s", err.Error()),
292 "SpecJSON",
293 )}
294 }
295 } else {
296 return false, []*liberrors.ValidationError{buildDocumentDecodeError(
297 fmt.Sprintf("The document's SpecJSONBytes cannot be decoded as JSON: %s", err.Error()),
298 "SpecJSONBytes",
299 )}
300 }
301 }
•302 } else if info.GetSpecJSON() != nil {
303 var err error
•304 normalized, err = normalizeJSON(*info.GetSpecJSON())
305 if err != nil {
306 return false, []*liberrors.ValidationError{buildDocumentDecodeError(
307 fmt.Sprintf("The OpenAPI document cannot be converted to JSON: %s", err.Error()),
308 "SpecJSON",
309 )}
310 }
311 }
312
313 // Validate the document
314 scErrs := jsch.Validate(normalized)
315
316 var schemaValidationErrors []*liberrors.SchemaValidationFailure
317
318 if scErrs != nil {
319
320 var jk *jsonschema.ValidationError
321 if errors.As(scErrs, &jk) {
322
323 // flatten the validationErrors
324 schFlatErrs := jk.BasicOutput().Errors
325
326 // Extract property name info once before processing errors (performance optimization)
327 propertyInfo := extractPropertyNameFromError(jk)
328
329 for q := range schFlatErrs {
330 er := schFlatErrs[q]
331
332 errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{}))
333 if er.KeywordLocation == "" || helpers.IgnorePolyRegex.MatchString(errMsg) {
334 continue // ignore this error, it's useless tbh, utter noise.
335 }
336 if errMsg != "" {
337
338 // locate the violated property in the schema
339 located := LocateSchemaPropertyNodeByJSONPath(info.RootNode.Content[0], er.InstanceLocation)
340 violation := &liberrors.SchemaValidationFailure{
341 Reason: errMsg,
342 FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation),
343 FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation),
344 InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation),
345 KeywordLocation: er.KeywordLocation,
346 OriginalJsonSchemaError: jk,
347 }
348
349 // if we have a location within the schema, add it to the error
350 if located != nil {
351 line := located.Line
352 // if the located node is a map or an array, then the actual human interpretable
353 // line on which the violation occurred is the line of the key, not the value.
354 if located.Kind == yaml.MappingNode || located.Kind == yaml.SequenceNode {
355 if line > 0 {
356 line--
357 }
358 }
359
360 // location of the violation within the rendered schema.
361 violation.Line = line
362 violation.Column = located.Column
363 } else {
364 // handles property name validation errors that don't provide useful InstanceLocation
365 applyPropertyNameFallback(propertyInfo, info.RootNode.Content[0], violation)
366 }
367 schemaValidationErrors = append(schemaValidationErrors, violation)
368 }
369 }
370 }
371
372 // add the error to the list
373 validationErrors = append(validationErrors, &liberrors.ValidationError{
374 ValidationType: helpers.Schema,
375 Message: "Document does not pass validation",
376 Reason: fmt.Sprintf("OpenAPI document is not valid according "+
377 "to the %s specification", info.Version),
378 SchemaValidationErrors: schemaValidationErrors,
379 HowToFix: liberrors.HowToFixInvalidSchema,
380 })
381 }
382 if len(validationErrors) > 0 {
383 return false, validationErrors
384 }
385 return true, nil
386 }