Debian Codegraph @

schema_validation/property_locator.go

raw
1 // Copyright 2025 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package schema_validation
5
6 import (
7 "regexp"
8 "strings"
9
10 "github.com/santhosh-tekuri/jsonschema/v6"
11 "go.yaml.in/yaml/v4"
12
13 liberrors "github.com/pb33f/libopenapi-validator/errors"
14 "github.com/pb33f/libopenapi-validator/helpers"
15 )
16
17 // PropertyNameInfo contains extracted information about a property name validation error
18 type PropertyNameInfo struct {
19 PropertyName string // The property name that violated validation (e.g., "$defs-atmVolatility_type")
20 ParentLocation []string // The path to the parent containing the property (e.g., ["components", "schemas"])
21 EnhancedReason string // A more detailed error message with context
22 Pattern string // The pattern that was violated, if applicable
23 }
24
25 var (
26 // invalidPropertyNameRegex matches errors like: "invalid propertyName 'X'"
27 invalidPropertyNameRegex = regexp.MustCompile(`invalid propertyName '([^']+)'`)
28
29 // patternMismatchRegex matches errors like: "'X' does not match pattern 'Y'"
30 patternMismatchRegex = regexp.MustCompile(`'([^']+)' does not match pattern '([^']+)'`)
31 )
32
33 // extractPropertyNameFromError extracts property name information from a jsonschema.ValidationError
34 // when BasicOutput doesn't provide useful InstanceLocation.
35 // This handles Priority 1 (invalid propertyName) and Priority 2 (pattern mismatch) cases.
36 //
37 // Returns PropertyNameInfo with extracted details, or nil if no relevant information found.
38 // Note: ValidationError.Error() includes all cause information in the formatted string,
39 // so we only need to check the root error message.
40 func extractPropertyNameFromError(ve *jsonschema.ValidationError) *PropertyNameInfo {
41 if ve == nil {
42 return nil
43 }
44
45 // Check error message for patterns (Error() includes all cause information)
46 return checkErrorForPropertyInfo(ve)
47 }
48
49 // checkErrorForPropertyInfo examines a single ValidationError for property name patterns.
50 // This is extracted as a separate function to avoid duplication and improve testability.
51 func checkErrorForPropertyInfo(ve *jsonschema.ValidationError) *PropertyNameInfo {
52 errMsg := ve.Error()
53 return checkErrorMessageForPropertyInfo(errMsg, ve.InstanceLocation, ve)
54 }
55
56 // checkErrorMessageForPropertyInfo extracts property name info from an error message string.
57 // This is separated to improve testability while keeping validation error traversal logic intact.
58 func checkErrorMessageForPropertyInfo(errMsg string, instanceLocation []string, ve *jsonschema.ValidationError) *PropertyNameInfo {
59 // Check for "invalid propertyName 'X'" first (most specific error message)
60 if matches := invalidPropertyNameRegex.FindStringSubmatch(errMsg); len(matches) > 1 {
61 propertyName := matches[1]
62 info := &PropertyNameInfo{
63 PropertyName: propertyName,
64 ParentLocation: instanceLocation,
65 }
66
67 // try to extract pattern information from deeper causes if available
68 var pattern string
69 if ve != nil {
70 pattern = extractPatternFromCauses(ve)
71 }
72
73 if pattern != "" {
74 info.Pattern = pattern
75 info.EnhancedReason = buildEnhancedReason(propertyName, pattern)
76 } else {
77 info.EnhancedReason = "invalid propertyName '" + propertyName + "'"
78 }
79
80 return info
81 }
82
83 // Check for "'X' does not match pattern 'Y'" as fallback (pattern violation)
84 if matches := patternMismatchRegex.FindStringSubmatch(errMsg); len(matches) > 2 {
85 return &PropertyNameInfo{
86 PropertyName: matches[1],
87 ParentLocation: instanceLocation,
88 Pattern: matches[2],
89 EnhancedReason: buildEnhancedReason(matches[1], matches[2]),
90 }
91 }
92
93 return nil
94 }
95
96 // extractPatternFromCauses looks through error causes to find pattern violation details.
97 // Since ValidationError.Error() includes all cause information, we check the formatted error string.
98 func extractPatternFromCauses(ve *jsonschema.ValidationError) string {
99 if ve == nil {
100 return ""
101 }
102
103 // Check the error message which includes all cause information
104 errMsg := ve.Error()
105 if matches := patternMismatchRegex.FindStringSubmatch(errMsg); len(matches) > 2 {
106 return matches[2]
107 }
108
109 return ""
110 }
111
112 // buildEnhancedReason constructs a detailed error message with property name and pattern
113 func buildEnhancedReason(propertyName, pattern string) string {
114 var buf strings.Builder
115 buf.Grow(len(propertyName) + len(pattern) + 50) // pre-allocate to avoid reallocation
116 buf.WriteString("invalid propertyName '")
117 buf.WriteString(propertyName)
118 buf.WriteString("': does not match pattern '")
119 buf.WriteString(pattern)
120 buf.WriteString("'")
121 return buf.String()
122 }
123
124 // findPropertyKeyNodeInYAML searches the YAML tree for a property key node at a specific location.
125 // It first navigates to the parent location, then searches for the property name as a map key.
126 //
127 // Parameters:
128 // - rootNode: The root YAML node to search from
129 // - propertyName: The property key to find (e.g., "$defs-atmVolatility_type")
130 // - parentPath: Path segments to the parent (e.g., ["components", "schemas"])
131 //
132 // Returns the YAML node for the property key, or nil if not found.
133 func findPropertyKeyNodeInYAML(rootNode *yaml.Node, propertyName string, parentPath []string) *yaml.Node {
134 if rootNode == nil || propertyName == "" {
135 return nil
136 }
137
138 // Navigate to parent location first
139 currentNode := rootNode
140 for _, segment := range parentPath {
141 currentNode = navigateToYAMLChild(currentNode, segment)
142 if currentNode == nil {
143 return nil
144 }
145 }
146
147 // Search for the property name as a map key
148 return findMapKeyNode(currentNode, propertyName)
149 }
150
151 // navigateToYAMLChild navigates from a parent node to a child by name.
152 // Handles both document root navigation and map content navigation.
153 func navigateToYAMLChild(parent *yaml.Node, childName string) *yaml.Node {
154 if parent == nil {
155 return nil
156 }
157
158 // If parent is a document node, navigate to its content
159 if parent.Kind == yaml.DocumentNode && len(parent.Content) > 0 {
160 parent = parent.Content[0]
161 }
162
163 // Navigate through mapping node
164 if parent.Kind == yaml.MappingNode {
165 return findMapKeyValue(parent, childName)
166 }
167
168 return nil
169 }
170
171 // findMapKeyValue searches a mapping node for a key and returns its value node
172 func findMapKeyValue(mappingNode *yaml.Node, keyName string) *yaml.Node {
173 if mappingNode.Kind != yaml.MappingNode {
174 return nil
175 }
176
177 // mapping nodes have key-value pairs: [key1, value1, key2, value2, ...]
178 for i := 0; i < len(mappingNode.Content); i += 2 {
179 keyNode := mappingNode.Content[i]
180 if keyNode.Value == keyName {
181 // return the value node (i+1)
182 if i+1 < len(mappingNode.Content) {
183 return mappingNode.Content[i+1]
184 }
185 }
186 }
187
188 return nil
189 }
190
191 // findMapKeyNode searches a mapping node for a key and returns the key node itself (not the value)
192 func findMapKeyNode(mappingNode *yaml.Node, keyName string) *yaml.Node {
193 if mappingNode == nil {
194 return nil
195 }
196
197 // if it's a document node, unwrap to content
198 if mappingNode.Kind == yaml.DocumentNode && len(mappingNode.Content) > 0 {
199 mappingNode = mappingNode.Content[0]
200 }
201
202 if mappingNode.Kind != yaml.MappingNode {
203 return nil
204 }
205
206 // mapping nodes have key-value pairs: [key1, value1, key2, value2, ...]
207 for i := 0; i < len(mappingNode.Content); i += 2 {
208 keyNode := mappingNode.Content[i]
209 if keyNode.Value == keyName {
210 return keyNode // contains line/column metadata for error reporting
211 }
212 }
213
214 return nil
215 }
216
217 // applyPropertyNameFallback attempts to enrich a violation with property name information
218 // when the primary location method fails. Returns true if enrichment was applied.
219 func applyPropertyNameFallback(
220 propertyInfo *PropertyNameInfo,
221 rootNode *yaml.Node,
222 violation *liberrors.SchemaValidationFailure,
223 ) bool {
224 if propertyInfo == nil {
225 return false
226 }
227
228 return enrichSchemaValidationFailure(
229 propertyInfo,
230 rootNode,
231 &violation.Line,
232 &violation.Column,
233 &violation.Reason,
234 &violation.FieldName,
235 &violation.FieldPath,
236 &violation.InstancePath,
237 )
238 }
239
240 // enrichSchemaValidationFailure attempts to enhance a SchemaValidationFailure with better
241 // location information by searching the YAML tree when the standard location is empty.
242 //
243 // This function:
244 // 1. searches YAML tree for the property key in various locations
245 // 2. updates Line, Column, Reason, and other fields if found
246 //
247 // Returns true if enrichment was performed, false otherwise.
248 func enrichSchemaValidationFailure(
249 failure *PropertyNameInfo,
250 rootNode *yaml.Node,
251 line *int,
252 column *int,
253 reason *string,
254 fieldName *string,
255 fieldPath *string,
256 instancePath *[]string,
257 ) bool {
258 if failure == nil {
259 return false
260 }
261
262 // search for the property key in the YAML tree with multiple fallback locations
263 // since InstanceLocation may be empty for property name errors
264 var foundNode *yaml.Node
265
266 // try with the provided parent location first
267 if len(failure.ParentLocation) > 0 {
268 foundNode = findPropertyKeyNodeInYAML(rootNode, failure.PropertyName, failure.ParentLocation)
269 }
270
271 // common fallback locations for OpenAPI property name errors
272 if foundNode == nil {
273 foundNode = findPropertyKeyNodeInYAML(rootNode, failure.PropertyName, []string{"components", "schemas"})
274 }
275 if foundNode == nil {
276 foundNode = findPropertyKeyNodeInYAML(rootNode, failure.PropertyName, []string{"components"})
277 }
278 if foundNode == nil {
279 foundNode = findPropertyKeyNodeInYAML(rootNode, failure.PropertyName, []string{})
280 }
281
282 if foundNode == nil {
283 return false
284 }
285
286 // populate location metadata from YAML node
287 *line = foundNode.Line
288 *column = foundNode.Column
289
290 if failure.EnhancedReason != "" {
291 *reason = failure.EnhancedReason
292 }
293
294 *fieldName = failure.PropertyName
295
296 // construct JSONPath from parent location segments
297 if len(failure.ParentLocation) > 0 {
298 *fieldPath = helpers.ExtractJSONPathFromStringLocation("/" + strings.Join(failure.ParentLocation, "/") + "/" + failure.PropertyName)
299 *instancePath = failure.ParentLocation
300 } else {
301 *fieldPath = helpers.ExtractJSONPathFromStringLocation("/" + failure.PropertyName)
302 *instancePath = []string{}
303 }
304
305 return true
306 }