-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmodel_apispec.go
More file actions
382 lines (320 loc) · 11.9 KB
/
model_apispec.go
File metadata and controls
382 lines (320 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package gateway
import (
"context"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers"
"github.com/TykTechnologies/tyk-pump/analytics"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/apidef/oas"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/internal/agentprotocol"
"github.com/TykTechnologies/tyk/internal/certcheck"
"github.com/TykTechnologies/tyk/internal/errors"
"github.com/TykTechnologies/tyk/internal/graphengine"
"github.com/TykTechnologies/tyk/internal/httpctx"
"github.com/TykTechnologies/tyk/internal/httputil"
"github.com/TykTechnologies/tyk/internal/jsonrpc"
"github.com/TykTechnologies/tyk/user"
_ "github.com/TykTechnologies/tyk/internal/mcp" // registers MCP VEM prefixes
)
// APISpec represents a path specification for an API, to avoid enumerating multiple nested lists, a single
// flattened URL list is checked for matching paths and then it's status evaluated if found.
type APISpec struct {
*apidef.APIDefinition
OAS oas.OAS
sync.RWMutex
Checksum string
RxPaths map[string][]URLSpec
WhiteListEnabled map[string]bool
target *url.URL
AuthManager SessionHandler
OAuthManager OAuthManagerInterface
OrgSessionManager SessionHandler
EventPaths map[apidef.TykEvent][]config.TykEventHandler
Health HealthChecker
JSVM JSVM
ResponseChain []TykResponseHandler
RoundRobin RoundRobin
URLRewriteEnabled bool
CircuitBreakerEnabled bool
EnforcedTimeoutEnabled bool
LastGoodHostList *apidef.HostList
HasRun bool
ServiceRefreshInProgress bool
HTTPTransport *TykRoundTripper
HTTPTransportCreated time.Time
WSTransport http.RoundTripper
WSTransportCreated time.Time
GlobalConfig config.Config
OrgHasNoSession bool
AnalyticsPluginConfig *GoAnalyticsPlugin
unloadHooks []func()
network analytics.NetworkStats
GraphEngine graphengine.Engine
oasRouter routers.Router
// UpstreamCertExpiryBatcher handles upstream certificate expiry checking
UpstreamCertExpiryBatcher certcheck.BackgroundBatcher
upstreamCertExpiryCheckContext context.Context
upstreamCertExpiryCancelFunc context.CancelFunc
upstreamCertExpiryInitOnce sync.Once
// MCPPrimitives maps primitive identifiers to their VEM paths for JSON-RPC routing.
// Key format: "tool:{name}", "resource:{pattern}", "prompt:{name}"
// Value: VEM path (e.g., "/mcp-tool:get-weather")
MCPPrimitives map[string]string
JSONRPCRouter jsonrpc.Router
// OperationsAllowListEnabled is true if any JSON-RPC operation (method-level) has
// an allow rule enabled. Pre-calculated during API loading.
OperationsAllowListEnabled bool
// ToolsAllowListEnabled is true if any MCP tool has an allow rule enabled.
// Pre-calculated during API loading.
ToolsAllowListEnabled bool
// ResourcesAllowListEnabled is true if any MCP resource has an allow rule enabled.
// Pre-calculated during API loading.
ResourcesAllowListEnabled bool
// PromptsAllowListEnabled is true if any MCP prompt has an allow rule enabled.
// Pre-calculated during API loading.
PromptsAllowListEnabled bool
// MCPAllowListEnabled is true if any MCP primitive (tool, resource, prompt) has an
// allow rule enabled. Pre-calculated during API loading to avoid iterating through
// all primitives on every JSON-RPC request that doesn't match a VEM.
// This is a convenience flag that combines ToolsAllowListEnabled, ResourcesAllowListEnabled, and PromptsAllowListEnabled.
MCPAllowListEnabled bool
}
// CheckSpecMatchesStatus checks if a URL spec has a specific status.
// Deprecated: The function doesn't follow go return conventions (T, ok); use FindSpecMatchesStatus;
func (a *APISpec) CheckSpecMatchesStatus(r *http.Request, rxPaths []URLSpec, mode URLStatus) (bool, interface{}) {
matchPath, method := a.getMatchPathAndMethod(r, mode)
for i := range rxPaths {
if rxPaths[i].Status != mode {
continue
}
if !rxPaths[i].matchesMethod(method) {
continue
}
if !rxPaths[i].matchesPath(matchPath, a) {
continue
}
if spec, ok := rxPaths[i].modeSpecificSpec(mode); ok {
return true, spec
}
}
return false, nil
}
func (a *APISpec) GetTykExtension() *oas.XTykAPIGateway {
if !a.IsOAS {
return nil
}
res := a.OAS.GetTykExtension()
if res == nil {
log.Warn("APISpec is an invalid OAS API")
}
return res
}
// GetPRMConfig returns the Protected Resource Metadata configuration
// if the API is an OAS API Definition (OAS API, MCP Proxy, Stream API) with PRM enabled.
// Returns nil otherwise.
func (a *APISpec) GetPRMConfig() *oas.ProtectedResourceMetadata {
ext := a.GetTykExtension()
if ext == nil || ext.Server.Authentication == nil {
return nil
}
prm := ext.Server.Authentication.ProtectedResourceMetadata
if prm == nil || !prm.Enabled {
return nil
}
return prm
}
// FindSpecMatchesStatus checks if a URL spec has a specific status and returns the URLSpec for it.
func (a *APISpec) FindSpecMatchesStatus(r *http.Request, rxPaths []URLSpec, mode URLStatus) (*URLSpec, bool) {
matchPath, method := a.getMatchPathAndMethod(r, mode)
for i := range rxPaths {
if rxPaths[i].Status != mode {
continue
}
if !rxPaths[i].matchesMethod(method) {
continue
}
if !rxPaths[i].matchesPath(matchPath, a) {
continue
}
return &rxPaths[i], true
}
return nil, false
}
// isJSONRPCVEMPath returns true if the request is a JSON-RPC routed request
// targeting a protocol VEM path. In this case, the listen path should not be
// stripped as the VEM path is already in its final form.
func isJSONRPCVEMPath(r *http.Request, path string) bool {
return httpctx.IsJsonRPCRouting(r) && agentprotocol.IsProtocolVEMPath(path)
}
// getMatchPathAndMethod retrieves the match path and method from the request based on the mode.
func (a *APISpec) getMatchPathAndMethod(r *http.Request, mode URLStatus) (string, string) {
var (
matchPath = r.URL.Path
method = r.Method
)
if mode == TransformedJQResponse || mode == HeaderInjectedResponse || mode == TransformedResponse {
matchPath = ctxGetUrlRewritePath(r)
method = ctxGetRequestMethod(r)
if matchPath == "" {
matchPath = r.URL.Path
}
}
if a.Proxy.ListenPath != "/" && !isJSONRPCVEMPath(r, matchPath) {
matchPath = a.StripListenPath(matchPath)
}
if !strings.HasPrefix(matchPath, "/") {
matchPath = "/" + matchPath
}
return matchPath, method
}
func (a *APISpec) injectIntoReqContext(req *http.Request) {
if a.IsOAS {
ctx.SetOASDefinition(req, &a.OAS)
} else {
ctx.SetDefinition(req, a.APIDefinition)
}
}
func (a *APISpec) findOperation(r *http.Request) *Operation {
middleware := a.OAS.GetTykMiddleware()
if middleware == nil {
return nil
}
if a.oasRouter == nil {
log.Warningf("OAS router not initialized properly. Unable to find route for %s %v", r.Method, r.URL)
return nil
}
rClone := *r
rClone.URL = ctxGetInternalRedirectTarget(r)
route, pathParams, err := a.oasRouter.FindRoute(&rClone)
if errors.Is(err, routers.ErrPathNotFound) {
log.Tracef("Unable to find route for %s %v at spec %v", r.Method, r.URL, a.Id)
return nil
}
if err != nil {
log.Errorf("Error finding route: %v", err)
return nil
}
operation, ok := middleware.Operations[route.Operation.OperationID]
if !ok {
log.Warningf("No operation found for ID: %s", route.Operation.OperationID)
return nil
}
return &Operation{
Operation: operation,
route: route,
pathParams: pathParams,
}
}
// findRouteForOASPath finds the OAS route using the OAS path pattern (e.g., "/users/{id}")
// and method, rather than the actual request path. This is used when gateway path matching
// (prefix/suffix) matches a broader pattern than the exact OAS path.
// The actualPath parameter is the request path stripped of the listen path.
// The fullRequestPath is the original request path (used for regexp listen paths).
func (a *APISpec) findRouteForOASPath(oasPath, method, actualPath, fullRequestPath string) (*routers.Route, map[string]string, error) {
if a.oasRouter == nil {
return nil, nil, errors.New("OAS router not initialized")
}
// For listen paths with mux-style variables (regexp), we need to use the actual
// request path because the OAS router's server URL contains the variable pattern.
// For regular listen paths, we build a synthetic path.
var routePath string
if httputil.IsMuxTemplate(a.Proxy.ListenPath) {
// For regexp listen paths like /product-regexp1/{name:.*}
// Use the full request path as the OAS router expects actual values
routePath = fullRequestPath
} else {
// For regular listen paths, combine listen path + OAS path
routePath = strings.TrimSuffix(a.Proxy.ListenPath, "/") + oasPath
}
syntheticURL, err := url.Parse(routePath)
if err != nil {
return nil, nil, err
}
syntheticReq := &http.Request{
Method: method,
URL: syntheticURL,
}
route, _, err := a.oasRouter.FindRoute(syntheticReq)
if err != nil {
return nil, nil, err
}
// Extract path parameters from the actual request path by matching against
// the OAS path pattern. This handles cases where the OAS path has parameters
// like /users/{id} and we need to extract the actual id value from the request.
pathParams := extractPathParams(oasPath, actualPath)
return route, pathParams, nil
}
// matchCandidatePath looks up the path item and operation from the OAS spec for a
// candidate path+method, extracts path parameters from the actual request path, and
// validates them against the operation's path parameter schemas. Returns the operation,
// path params, and true if the candidate matches; false otherwise.
// This is the shared disambiguation logic used by both validate request and mock response.
func (a *APISpec) matchCandidatePath(oasPath, oasMethod, strippedPath string) (*openapi3.PathItem, *openapi3.Operation, map[string]string, bool) {
pathItem := a.OAS.Paths.Value(oasPath)
if pathItem == nil {
return nil, nil, nil, false
}
operation := pathItem.GetOperation(oasMethod)
if operation == nil {
return nil, nil, nil, false
}
pathParams := extractPathParams(oasPath, strippedPath)
if !pathParamsMatchOperation(pathParams, operation) {
return nil, nil, nil, false
}
return pathItem, operation, pathParams, true
}
// extractPathParams extracts path parameter values from actualPath based on the
// OAS path pattern. For example, if oasPath is "/users/{id}" and actualPath is
// "/users/123", it returns map[string]string{"id": "123"}.
func extractPathParams(oasPath, actualPath string) map[string]string {
params := make(map[string]string)
oasParts := strings.Split(strings.Trim(oasPath, "/"), "/")
actualParts := strings.Split(strings.Trim(actualPath, "/"), "/")
for i, oasPart := range oasParts {
if i >= len(actualParts) {
break
}
// Check if this is a path parameter (wrapped in {})
if strings.HasPrefix(oasPart, "{") && strings.HasSuffix(oasPart, "}") {
paramName := oasPart[1 : len(oasPart)-1]
params[paramName] = actualParts[i]
}
}
return params
}
// APIType returns the api_type string for the given API spec.
// Precedence: mcp > graphql > oas > classic.
func (a *APISpec) APIType() string {
switch {
case a.IsMCP():
return "mcp"
case a.GraphQL.Enabled:
return "graphql"
case a.IsOAS:
return "oas"
default:
return "classic"
}
}
func (a *APISpec) sendRateLimitHeaders(session *user.SessionState, dest *http.Response) {
quotaMax, quotaRemaining, quotaRenews := int64(0), int64(0), int64(0)
if session != nil {
quotaMax, quotaRemaining, _, quotaRenews = session.GetQuotaLimitByAPIID(a.APIID)
}
if dest.Header == nil {
dest.Header = http.Header{}
}
dest.Header.Set(header.XRateLimitLimit, strconv.Itoa(int(quotaMax)))
dest.Header.Set(header.XRateLimitRemaining, strconv.Itoa(int(quotaRemaining)))
dest.Header.Set(header.XRateLimitReset, strconv.Itoa(int(quotaRenews)))
}