Debian Codegraph @

paths/paths.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package paths
5
6 import (
7 "fmt"
8 "net/http"
9 "net/url"
10 "path/filepath"
11 "regexp"
12 "strings"
13
14 "github.com/pb33f/libopenapi/orderedmap"
15
16 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
17
18 "github.com/pb33f/libopenapi-validator/config"
19 "github.com/pb33f/libopenapi-validator/errors"
20 "github.com/pb33f/libopenapi-validator/helpers"
21 )
22
23 // FindPath will find the path in the document that matches the request path. If a successful match was found, then
24 // the first return value will be a pointer to the PathItem. The second return value will contain any validation errors
25 // that were picked up when locating the path.
26 // The third return value will be the path that was found in the document, as it pertains to the contract, so all path
27 // parameters will not have been replaced with their values from the request - allowing model lookups.
28 //
29 // This function first tries a fast O(k) radix tree lookup (where k is path depth). If the radix tree
30 // doesn't find a match, it falls back to regex-based matching which handles complex path patterns
31 // like matrix-style ({;param}), label-style ({.param}), and OData-style (entities('{Entity}')).
32 //
33 // Path matching follows the OpenAPI specification: literal (concrete) paths take precedence over
34 // parameterized paths, regardless of definition order in the specification.
35 func FindPath(request *http.Request, document *v3.Document, options *config.ValidationOptions) (*v3.PathItem, []*errors.ValidationError, string) {
36 stripped := StripRequestPath(request, document)
37
38 // Fast path: try radix tree first (O(k) where k = path depth)
39 // If no path lookup is provided, we will fall back to regex-based matching.
40 if options != nil && options.PathTree != nil {
41 if pathItem, matchedPath, found := options.PathTree.Lookup(stripped); found {
42 if pathHasMethod(pathItem, request.Method) {
43 return pathItem, nil, matchedPath
44 }
45 return pathItem, missingOperationError(request, matchedPath), matchedPath
46 }
47 }
48
49 // Slow path: fall back to regex matching for complex paths (matrix, label, OData, etc.)
50 basePaths := getBasePaths(document)
51
52 reqPathSegments := strings.Split(stripped, "/")
53 if reqPathSegments[0] == "" {
54 reqPathSegments = reqPathSegments[1:]
55 }
56
57 var regexCache config.RegexCache
58 if options != nil {
59 regexCache = options.RegexCache
60 }
61
62 candidates := make([]pathCandidate, 0, document.Paths.PathItems.Len())
63
64 for pair := orderedmap.First(document.Paths.PathItems); pair != nil; pair = pair.Next() {
65 path := pair.Key()
66 pathItem := pair.Value()
67
68 pathForMatching := normalizePathForMatching(path, stripped)
69
70 segs := strings.Split(pathForMatching, "/")
71 if segs[0] == "" {
72 segs = segs[1:]
73 }
74
75 ok := comparePaths(segs, reqPathSegments, basePaths, regexCache)
76 if !ok {
77 continue
78 }
79
80 // Compute specificity score and check if method exists
81 score := computeSpecificityScore(path)
82 hasMethod := pathHasMethod(pathItem, request.Method)
83
84 candidates = append(candidates, pathCandidate{
85 pathItem: pathItem,
86 path: path,
87 score: score,
88 hasMethod: hasMethod,
89 })
90 }
91
92 if len(candidates) == 0 {
93 validationErrors := []*errors.ValidationError{
94 {
95 ValidationType: helpers.PathValidation,
96 ValidationSubType: helpers.ValidationMissing,
97 Message: fmt.Sprintf("%s Path '%s' not found", request.Method, request.URL.Path),
98 Reason: fmt.Sprintf("The %s request contains a path of '%s' "+
99 "however that path, or the %s method for that path does not exist in the specification",
100 request.Method, request.URL.Path, request.Method),
101 SpecLine: -1,
102 SpecCol: -1,
103 HowToFix: errors.HowToFixPath,
104 },
105 }
106 errors.PopulateValidationErrors(validationErrors, request, "")
107 return nil, validationErrors, ""
108 }
109
110 bestWithMethod, bestOverall := selectMatches(candidates)
111
112 if bestWithMethod != nil {
113 return bestWithMethod.pathItem, nil, bestWithMethod.path
114 }
115
116 // path matches exist but none have the required method
117 return bestOverall.pathItem, missingOperationError(request, bestOverall.path), bestOverall.path
118 }
119
120 // normalizePathForMatching removes the fragment from a path template unless
121 // the request path itself contains a fragment.
122 func normalizePathForMatching(path, requestPath string) string {
123 if strings.Contains(requestPath, "#") {
124 return path
125 }
126 if idx := strings.IndexByte(path, '#'); idx >= 0 {
127 return path[:idx]
128 }
129 return path
130 }
131
132 func getBasePaths(document *v3.Document) []string {
133 // extract base path from document to check against paths.
134 var basePaths []string
135 for _, s := range document.Servers {
136 u, err := url.Parse(s.URL)
137 // if the host contains special characters, we should attempt to split and parse only the relative path
138 if err != nil {
139 // split at first occurrence
140 _, serverPath, _ := strings.Cut(strings.Replace(s.URL, "//", "", 1), "/")
141
142 if !strings.HasPrefix(serverPath, "/") {
143 serverPath = "/" + serverPath
144 }
145
146 u, _ = url.Parse(serverPath)
147 }
148
149 if u != nil && u.Path != "" {
150 basePaths = append(basePaths, u.Path)
151 }
152 }
153
154 return basePaths
155 }
156
157 // StripRequestPath strips the base path from the request path, based on the server paths provided in the specification
158 func StripRequestPath(request *http.Request, document *v3.Document) string {
159 basePaths := getBasePaths(document)
160
161 // strip any base path
162 stripped := stripBaseFromPath(request.URL.EscapedPath(), basePaths)
163 if request.URL.Fragment != "" {
164 stripped = fmt.Sprintf("%s#%s", stripped, request.URL.Fragment)
165 }
166 if !strings.HasPrefix(stripped, "/") {
167 stripped = "/" + stripped
168 }
169 return stripped
170 }
171
172 func checkPathAgainstBase(docPath, urlPath string, basePaths []string) bool {
173 if docPath == urlPath {
174 return true
175 }
176 for _, basePath := range basePaths {
177 if len(basePath) > 1 && basePath[len(basePath)-1] == '/' {
178 basePath = basePath[:len(basePath)-1]
179 }
180 merged := fmt.Sprintf("%s%s", basePath, urlPath)
181 if docPath == merged {
182 return true
183 }
184 }
185 return false
186 }
187
188 func stripBaseFromPath(path string, basePaths []string) string {
189 for i := range basePaths {
190 if strings.HasPrefix(path, basePaths[i]) {
191 return path[len(basePaths[i]):]
192 }
193 }
194 return path
195 }
196
197 func comparePaths(mapped, requested, basePaths []string, regexCache config.RegexCache) bool {
198 if len(mapped) != len(requested) {
199 return false // short circuit out
200 }
201 var imploded []string
202 for i, seg := range mapped {
203 s := seg
204 var rgx *regexp.Regexp
205
206 if regexCache != nil {
207 if cachedRegex, found := regexCache.Load(s); found {
208 rgx = cachedRegex.(*regexp.Regexp)
209 }
210 }
211
212 if rgx == nil {
213 r, err := helpers.GetRegexForPath(seg)
214 if err != nil {
215 return false
216 }
217
218 rgx = r
219
220 if regexCache != nil {
221 regexCache.Store(seg, r)
222 }
223 }
224
225 if rgx.MatchString(requested[i]) {
226 s = requested[i]
227 }
228 imploded = append(imploded, s)
229 }
230 l := filepath.Join(imploded...)
231 r := filepath.Join(requested...)
232 return checkPathAgainstBase(l, r, basePaths)
233 }
234
235 // missingOperationError returns a validation error for when a path was found but the HTTP method doesn't exist.
236 func missingOperationError(request *http.Request, matchedPath string) []*errors.ValidationError {
237 validationErrors := []*errors.ValidationError{{
238 ValidationType: helpers.PathValidation,
239 ValidationSubType: helpers.ValidationMissingOperation,
240 Message: fmt.Sprintf("%s Path '%s' not found", request.Method, request.URL.Path),
241 Reason: fmt.Sprintf("The %s method for that path does not exist in the specification",
242 request.Method),
243 SpecLine: -1,
244 SpecCol: -1,
245 HowToFix: errors.HowToFixPath,
246 }}
247 errors.PopulateValidationErrors(validationErrors, request, matchedPath)
248 return validationErrors
249 }