Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cli/linter/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,10 @@
"type": "boolean",
"default": false
},
"allow_unsafe_listen_path_matching": {
"type": "boolean",
"default": false
},
"close_idle_connections": {
"type": "boolean"
},
Expand Down
8 changes: 8 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,14 @@ type Config struct {
// Enable it only if your APIs rely on the legacy behavior.
ApplyStripListenPathToURLRewrite bool `json:"apply_strip_listen_path_to_url_rewrite"`

// AllowUnsafeListenPathMatching restores the previous behavior, where endpoint
// matching for Tyk OAS APIs also accepted the full request URL including the
// listen path. With strip_listen_path enabled this could approve a request for
// one endpoint and proxy a different, undeclared path upstream.
// Defaults to false, which matches OAS endpoints only against the path that
// is proxied upstream. Tyk Classic APIs are not affected by this setting.
AllowUnsafeListenPathMatching bool `json:"allow_unsafe_listen_path_matching"`

// Tyk nodes can provide uptime awareness, uptime testing and analytics for your underlying APIs uptime and availability.
// Tyk can also notify you when a service goes down.
UptimeTests UptimeTestsConfig `json:"uptime_tests"`
Expand Down
9 changes: 9 additions & 0 deletions gateway/api_definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ func (a APIDefinitionLoader) MakeSpec(def *model.MergedAPI, logger *logrus.Entry
}

spec.GlobalConfig = a.Gw.GetConfig()
spec.endpointMatcher = newEndpointMatcher(spec)

if err = a.Gw.loadBundle(spec); err != nil {
logger.WithError(err).Error("Couldn't load bundle")
Expand Down Expand Up @@ -985,6 +986,10 @@ func (a APIDefinitionLoader) generateRegex(stringSpec string, newSpec *URLSpec,

newSpec.Status = specType
newSpec.spec = asRegex

if specType == WhiteList || specType == Ignored {
newSpec.oasExact = newOASExactPath(stringSpec, isIgnoreCase)
}
}

func (a APIDefinitionLoader) compilePathSpec(paths []string, specType URLStatus, conf config.Config) []URLSpec {
Expand Down Expand Up @@ -2244,6 +2249,10 @@ func (a *APISpec) URLAllowedAndIgnored(r *http.Request, rxPaths []URLSpec, white
continue
}

if !a.endpointMatcher.grants(r, &rxPaths[i], a) {
continue
}

if rxPaths[i].MethodActions == nil {
switch rxPaths[i].Status {
case WhiteList:
Expand Down
1 change: 1 addition & 0 deletions gateway/api_definition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3144,6 +3144,7 @@ func TestURLAllowedAndIgnored_CORSPreflight(t *testing.T) {
OptionsPassthrough: false,
},
},
endpointMatcher: legacyEndpointMatcher{},
}

testPath := "/test"
Expand Down
1 change: 1 addition & 0 deletions gateway/mcp_cache_safety_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func TestRedisCacheMiddleware_BypassesCredentialSpecificMCPFiltering(t *testing.
spec.CacheOptions.EnableCache = true
})[0]
spec.CacheOptions.CacheTimeout = 60
spec.endpointMatcher = newEndpointMatcher(spec)
spec.RxPaths = map[string][]URLSpec{"v1": (APIDefinitionLoader{}).compileCachedPathSpec(nil, []apidef.CacheMeta{{Path: "/mcp", Method: http.MethodPost}}, config.Config{})}
store := &cacheReadCountingStore{DummyStorage: storage.NewDummyStorage(), written: make(chan struct{}, 1)}
middleware := &RedisCacheMiddleware{BaseMiddleware: &BaseMiddleware{Spec: spec}, store: store}
Expand Down
3 changes: 2 additions & 1 deletion gateway/mcp_pairing.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,8 @@ func buildMCPAdapterSpec(rest *APISpec, proxies []*APISpec, existing *APISpec) (
orgID: rest.OrgID,
Gw: gw,
},
GlobalConfig: rest.GlobalConfig,
GlobalConfig: rest.GlobalConfig,
endpointMatcher: rest.endpointMatcher,
MCPAdapter: MCPAdapterRuntime{
Synthetic: true,
SourceRESTAPIID: rest.APIID,
Expand Down
188 changes: 185 additions & 3 deletions gateway/model_apispec.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@
OrgHasNoSession bool
AnalyticsPluginConfig *GoAnalyticsPlugin

// Chosen once in MakeSpec from the API type and the Gateway config.
endpointMatcher endpointMatcher

// Swapped by a reload while requests read it, so the reads stay lock-free.
dnsDiscovery atomic.Pointer[dnsDiscoveryPlan]

Expand Down Expand Up @@ -166,7 +169,7 @@
if rxPaths[i].Status != mode {
continue
}
if !rxPaths[i].matchesMethod(method) {

Check warning on line 172 in gateway/model_apispec.go

View check run for this annotation

probelabs / Visor: performance

performance Issue

The `pathParameters` function is called on the request path within `oasOperationMatches`. This function performs a parameter merge operation involving a slice allocation and a nested loop on every applicable request. This introduces unnecessary CPU and memory overhead in a performance-sensitive code path.
Raw output
The merged parameters for each OAS operation are static for a given API definition. Pre-compute the merged parameters for all operations when the API definition is loaded (e.g., in `MakeSpec`) and store them in a cache within the `APISpec`. The `oasOperationMatches` function should then retrieve the pre-computed parameter list from the cache instead of recalculating it.
continue
}
if !rxPaths[i].matchesPath(matchPath, a) {
Expand Down Expand Up @@ -319,9 +322,7 @@
}
}

if a.Proxy.ListenPath != "/" && !isJSONRPCVEMPath(r, matchPath) {
matchPath = a.StripListenPath(matchPath)
}
matchPath = a.endpointMatcher.matchPath(r, matchPath, a)

if !strings.HasPrefix(matchPath, "/") {
matchPath = "/" + matchPath
Expand Down Expand Up @@ -434,6 +435,187 @@
return route, pathParams, nil
}

// endpointMatcher decides how a request path is matched against the endpoint
// specs of an API. One implementation per matching mode, chosen once per API
// in MakeSpec, so no per-request code consults the mode.
type endpointMatcher interface {
// matchPath returns the request path CheckSpecMatchesStatus and
// FindSpecMatchesStatus hand to matchesPath.
matchPath(r *http.Request, path string, api *APISpec) string
// matchesPath reports whether the request path matches the spec regex.
matchesPath(spec *URLSpec, reqPath string, api *APISpec) bool
// grants reports whether a matched allow or ignoreAuthentication entry
// applies to the request.
grants(r *http.Request, spec *URLSpec, api *APISpec) bool
}

// newEndpointMatcher picks the matcher for the API. Tyk OAS APIs match the
// path proxied upstream unless allow_unsafe_listen_path_matching is set;
// Tyk Classic APIs keep legacyEndpointMatcher.
func newEndpointMatcher(spec *APISpec) endpointMatcher {
if spec.IsOAS && !spec.GlobalConfig.AllowUnsafeListenPathMatching {
return oasEndpointMatcher{}
}
return legacyEndpointMatcher{}
}

// legacyEndpointMatcher is the matching every API used before TT-18034: the
// listen path is stripped before matching, and the regex is tried against the
// path with listen path and version stripped, with the listen path stripped,
// and against the full URL including the listen path. Customers declare
// Classic endpoint paths that include the listen path, so the last step stays.
type legacyEndpointMatcher struct{}

func (legacyEndpointMatcher) matchPath(r *http.Request, path string, api *APISpec) string {
if api.Proxy.ListenPath != "/" && !isJSONRPCVEMPath(r, path) {
return api.StripListenPath(path)
}
return path
}

func (legacyEndpointMatcher) matchesPath(spec *URLSpec, reqPath string, api *APISpec) bool {
clean := api.StripListenPath(reqPath)
noVersion := api.StripVersionPath(clean)
// match /users
if noVersion != clean && spec.spec.MatchString(noVersion) {
return true
}
// match /v3/users
if spec.spec.MatchString(clean) {
return true
}
// match /listenpath/v3/users
if spec.spec.MatchString(reqPath) {
return true
}
return false
}

func (legacyEndpointMatcher) grants(*http.Request, *URLSpec, *APISpec) bool {
return true
}

// oasEndpointMatcher matches Tyk OAS endpoints against the path proxied
// upstream only: the listen path is stripped once, in matchesPath, and the
// full URL is never tried, so what the allow list approves is what the
// upstream receives. Allow and ignoreAuthentication entries additionally
// require the exact declared operation.
type oasEndpointMatcher struct{}

func (oasEndpointMatcher) matchPath(_ *http.Request, path string, _ *APISpec) string {
return path

Check warning on line 506 in gateway/model_apispec.go

View check run for this annotation

probelabs / Visor: architecture

architecture Issue

The `matchesPath` methods for `legacyEndpointMatcher` and `oasEndpointMatcher` contain duplicated logic. The initial path stripping and the first two `if` blocks that match against the version-stripped and listen-path-stripped paths are identical in both implementations.
Raw output
To reduce duplication and improve maintainability, the common path matching logic could be extracted into a shared helper function. This function could be called at the beginning of both `matchesPath` implementations. While the amount of duplication is small and the current implementation is clear, a helper function could centralize the common matching steps.
}

func (oasEndpointMatcher) matchesPath(spec *URLSpec, reqPath string, api *APISpec) bool {
clean := api.StripListenPath(reqPath)
noVersion := api.StripVersionPath(clean)
// match /users
if noVersion != clean && spec.spec.MatchString(noVersion) {
return true
}
// match /v3/users
if spec.spec.MatchString(clean) {
return true
}
// Block entries keep the full URL step: narrowing a denial is not safe.
// VEM paths are internal looping targets without a listen path, so the
// full URL is the only form they can be matched against.
if spec.Status == BlackList || agentprotocol.IsProtocolVEMPath(reqPath) {
return spec.spec.MatchString(reqPath)
}
return false
}

func (oasEndpointMatcher) grants(r *http.Request, spec *URLSpec, api *APISpec) bool {
return api.oasOperationMatches(r, spec)
}

// oasOperationMatches reports whether the request targets exactly the OAS
// operation an allow or ignoreAuthentication entry was declared for, path
// parameter schemas included. Other entries, and entries not declared in the
// OAS document, keep the regex verdict.
func (a *APISpec) oasOperationMatches(r *http.Request, spec *URLSpec) bool {
if !spec.oasExact.enabled {
return true
}

meta := spec.Whitelist
if spec.Status == Ignored {
meta = spec.Ignored
}

pathItem := a.OAS.Paths.Value(meta.Path)
if pathItem == nil {
return true
}

method := meta.Method
if method == "" {
method = r.Method
}

operation := pathItem.GetOperation(strings.ToUpper(method))
if operation == nil {
return true
}

// The escaped path keeps an encoded slash inside one parameter value.
clean := a.StripListenPath(r.URL.EscapedPath())
for _, candidate := range []string{a.StripVersionPath(clean), clean} {
params, ok := spec.oasExact.matches(candidate)
if !ok {
continue
}
// validateRequest on the operation keeps answering invalid parameter
// values with its configured status code.
if a.validateRequestEnabled(operation.OperationID) {
return true
}
return pathParamsMatchParameters(params, pathParameters(pathItem, operation))
}

return false

Check warning on line 577 in gateway/model_apispec.go

View check run for this annotation

probelabs / Visor: quality

style Issue

The function `pathParameters` uses a nested loop to find overridden parameters shared between a path and an operation. This O(N*M) complexity can be made more readable and efficient by using a map for lookups, reducing complexity to O(N+M).
Raw output
Refactor the function to use a map to store operation-level parameters for O(1) lookup when iterating through path-level parameters. This avoids the nested loop and makes the logic for checking overrides clearer.
}

// pathParameters returns the operation parameters plus the path item
// parameters the operation does not override (same name and location).
func pathParameters(pathItem *openapi3.PathItem, operation *openapi3.Operation) openapi3.Parameters {
if len(pathItem.Parameters) == 0 {
return operation.Parameters
}

merged := make(openapi3.Parameters, 0, len(operation.Parameters)+len(pathItem.Parameters))
merged = append(merged, operation.Parameters...)
for _, ref := range pathItem.Parameters {
if ref == nil || ref.Value == nil {
continue
}
overridden := false
for _, opRef := range operation.Parameters {
if opRef != nil && opRef.Value != nil && opRef.Value.Name == ref.Value.Name && opRef.Value.In == ref.Value.In {
overridden = true
break
}
}
if !overridden {
merged = append(merged, ref)
}
}

return merged
}

// validateRequestEnabled reports whether the Tyk validateRequest middleware
// is enabled on the OAS operation.
func (a *APISpec) validateRequestEnabled(operationID string) bool {
middleware := a.OAS.GetTykMiddleware()
if middleware == nil {
return false
}
operation := middleware.Operations[operationID]
return operation != nil && operation.ValidateRequest != nil && operation.ValidateRequest.Enabled
}

// 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,
Expand Down
Loading
Loading