Repository navigation
[TT-19131]: Stop request values choosing the URL rewrite host - #8991
kofoworola wants to merge 5 commits into
Conversation
The Gateway no longer loads an API when an enabled URL rewrite, or one of its triggers, has a rewrite_to that starts with a numbered capture ($0, $1, ...) or a $tyk_context variable, and it logs the API ID and the rule. Other APIs still load, and rewrite_to values with a literal prefix, $tyk_meta values, secret references and absolute URLs that the API manager wrote load as before. Code: - apidef/validator_url_rewrite.go:1-60: RewriteToStartsWithRequestValue and RuleURLRewriteTarget, also added to DefaultValidationRuleSet (apidef/validator.go:67) so the Gateway API rejects these definitions. - gateway/api_definition.go:254-260: APISpec.Validate runs the rule on load. - gateway/server.go:786: the skip log names the API ID. Acceptance criteria: - AC1 (skip on load, log, others load): TestURLRewrite_RequestValueAtStartOfRewriteToIsNotLoaded, TestRuleURLRewriteTarget_Validate. - AC4 (literal prefix loads, stays on target_url): TestURLRewrite_LiteralPrefixKeepsRequestOnTarget. - AC6 ($tyk_meta and secret references can choose the server): TestURLRewrite_APIManagerValuesCanStillChooseHost. - AC10 (classic and OAS): OAS subtests in both tests above. - AC11 (fails on unfixed code): the load-time tests above fail on master e66db61.
When rewrite_to starts with a single "/" and an empty value makes the rewritten path start with "//", the Gateway now collapses the leading slashes so the remaining segments stay in the path. Before, "/$1/$2" with an empty $1 read $2 as a host and the upstream received only the base path; rewrites whose result does not start with "//", and rewrite_to values that start with "//", are unchanged. Code: - gateway/mw_url_rewrite.go:114-129: keepSingleLeadingSlash, applied after substitution when the rule matched. Acceptance criteria: - AC9 (/$1/$2 with an empty $1 keeps the remaining segments): TestURLRewrite_EmptyLeadingCaptureKeepsRemainingSegments, which fails on the previous commit (upstream path "/" instead of "/segment").
When the rewritten URL has a host and rewrite_to has a variable, the URL rewrite middleware rebuilds it with every request value (numbered captures and $tyk_context variables) left empty and returns 400 Bad Request, sending nothing upstream, if the scheme, user info, host or port differ. Hosts that the API manager wrote literally or through $tyk_meta or secret references, absolute ws, wss and h2c rewrites, and tyk:// loop targets behave as before. Each secret is resolved once per rewrite and reused by the comparison, so the secret store is not called twice and both passes see the same value. Path-only rewrites skip the check (BenchmarkZZRewrite, 200000x: 13 allocs, 577 B on master and on this branch); a host rewrite with variables adds 7 allocs and ~700 ns. Code: - gateway/mw_url_rewrite.go:113-129: secrets reused within the rewrite, and the check after substitution. - gateway/mw_url_rewrite.go:153-188: requestValueSetsHost. - gateway/mw_url_rewrite.go:281-300: replaceVariables reuses resolved secrets. - gateway/mw_url_rewrite.go:510-513: ProcessRequest returns 400 and logs it. Acceptance criteria: - AC5 (runtime 400 for every scheme and form): TestURLRewriteMiddleware_RequestValueCannotSetHost (http, https, HTTP, ftp, //host) and TestURLRewrite_RequestValueCannotCompleteTheHost (user info after a literal host or a secret reference, port from the request, trigger rewrite_to, OAS). A value that is still percent-encoded parses as a path, not a host, so it stays on target_url with 200. - AC6 (secret references still choose the server): TestURLRewrite_RequestValueCannotCompleteTheHost "path after a secret reference", TestReplaceTykVariables_ReusesResolvedSecrets. - AC7 (upstream headers never reach a client-chosen host): the rogue upstream in TestURLRewrite_RequestValueCannotCompleteTheHost receives no request. - AC8 (absolute rewrites the API manager wrote, tyk:// loops): API manager subtests of TestURLRewriteMiddleware_RequestValueCannotSetHost. - AC2 runtime regression for TT-18122: "context value with a full URL is escaped into a path" subtest. - AC11: these tests fail on master e66db61.
|
This PR introduces a critical security fix to prevent a Server-Side Request Forgery (SSRF) vulnerability within the URL rewrite middleware. The core issue allowed an API client to control the upstream host by providing specially crafted request values, which could be used in a The fix implements a two-layered defense strategy:
Additionally, the PR addresses an edge case where an empty leading capture group (e.g., Files Changed AnalysisThe changes are primarily focused on the
Architecture & Impact Assessment
Visualization of Security ChecksThis diagram illustrates the two layers of protection introduced by the PR: sequenceDiagram
participant Client
participant Gateway
participant Upstream
alt API Loading Time
Gateway->>Gateway: Validate API Definition with RuleURLRewriteTarget
alt `rewrite_to` starts with `$1` or `$tyk_context.*`
Gateway-->>Gateway: Validation Fails, API is NOT loaded
Note over Gateway: Error logged with API ID
else `rewrite_to` has a safe prefix (e.g., `/$1`)
Gateway-->>Gateway: Validation Succeeds, API loads
end
end
alt Request Processing Time (for loaded APIs)
Client->>Gateway: GET /path?u=@evil.com
Gateway->>Gateway: URLRewriteMiddleware processes request
Note over Gateway: Checks if request value changed the host/scheme/port
alt Host was altered by request value
Gateway-->>Client: 400 Bad Request
Note over Gateway: Request is blocked
else Rewrite is safe
Gateway->>Upstream: Proxies safely rewritten request
Upstream-->>Gateway: 200 OK
Gateway-->>Client: 200 OK
end
end
Scope Discovery & Context ExpansionThe scope of this change is broader than just the Gateway's runtime behavior. By adding the new validation rule to
This PR enforces a security-first policy, intentionally introducing a breaking change to eliminate a class of vulnerability rather than maintaining backward compatibility for insecure configurations. Metadata
Powered by Visor from Probelabs Last updated: 2026-11-26T13:39:19.356Z | Triggered by: pr_updated | Commit: 1ae7897 💡 TIP: You can chat with Visor using |
✅ Security Check PassedNo security issues found – changes LGTM. Performance Issues (1)
✅ Security Check PassedNo security issues found – changes LGTM. \n\n \n\nPerformance Issues (1)
No quality issues found – changes LGTM. Powered by Visor from Probelabs Last updated: 2026-11-26T13:39:01.586Z | Triggered by: pr_updated | Commit: 1ae7897 💡 TIP: You can chat with Visor using |
OAS APIs extract to a single unnamed version, so the rule's message read `url rewrite GET /q in version "": ...`. It now reads `url rewrite GET /q: ...` for an unnamed version; named versions keep the version in the message. Code: - apidef/validator_url_rewrite.go:40-63: urlRewriteRuleName. Acceptance criteria: - AC1/AC2 (error names the rule): TestRuleURLRewriteTarget_Validate "an unnamed version is left out of the message".
Adds a regression case for the request-time host check: with match_pattern "/" (no capture groups) and rewrite_to "http://$tyk_context.headers_X_Host/x", a header value that names a host returns 400 and sets no rewrite target. The check runs whenever the pattern matches, because the whole match counts as a match group; no production code changes. Acceptance criteria: - AC5 (runtime 400 when a request value sets the host): TestURLRewriteMiddleware_RequestValueCannotSetHost "context value as the host, pattern without capture groups".
|
SentinelOne CNS Hardcoded Secret Detector SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes. |
|




Description
A URL rewrite can no longer send a request to a server that the API client chose.
rewrite_to, or a trigger'srewrite_to, starts with a numbered capture ($0,$1, …) or a$tyk_contextvariable. It logs the API ID and the rule, and loads the other APIs. The same rule is inapidef.DefaultValidationRuleSet, so the Gateway API and the Dashboard reject these definitions on save.rewrite_tohas a variable, the middleware rebuilds the URL with every request value left empty. If the scheme, user info, host or port differ, it returns400 Bad Requestand sends nothing upstream. Each secret is resolved once and reused, so the check doesn't call the secret store twice.rewrite_to: "/$1/$2"and an empty$1, the upstream now receives/$2instead of the base path.These keep working as before:
$tyk_metaor a secret reference.http,https,ws,wssandh2crewrites.tyk://loop targets.rewrite_tovalues with a literal prefix, such as/$1.Related Issue
TT-19131. It builds on TT-18122 (#8958), which escapes request context values.
The Dashboard part is TykTechnologies/tyk-analytics#6580. Merge this PR first. The Dashboard PR pins this branch's head commit (
dbab8682239f), and its pin moves to the merged commit afterwards.Motivation and Context
A
rewrite_toof$1, with?u=http://other-host/x, sends the request, including headers that the API adds such as upstream credentials, toother-host. That is server-side request forgery. A value after a literal host, such ashttp://api.internal$1with$1=@other-host/x, does the same through the URL's user-info syntax.Behavior change. An API whose
rewrite_tostarts with$1or$tyk_context.*no longer loads, even if it only ever received safe values. The fix is to add a literal prefix ($1→/$1). This also applies to$tyk_contextvalues that come from session metadata through triggers, or from plugins.How This Has Been Tested
The acceptance criteria are on the Jira story. Each criterion maps to these tests:
TestURLRewrite_RequestValueAtStartOfRewriteToIsNotLoaded,TestRuleURLRewriteTarget_Validate/$1,/api/$1load and stay ontarget_urlTestURLRewrite_LiteralPrefixKeepsRequestOnTargethttp,https,HTTP,ftp,//host, user info, port, triggers, OASTestURLRewriteMiddleware_RequestValueCannotSetHost,TestURLRewrite_RequestValueCannotCompleteTheHost$tyk_metaand secret references still choose the serverTestURLRewrite_APIManagerValuesCanStillChooseHost,TestReplaceTykVariables_ReusesResolvedSecretshttp,https,ws,wss,h2crewrites andtyk://unchangedTestURLRewriteMiddleware_RequestValueCannotSetHost/$1/$2with an empty$1TestURLRewrite_EmptyLeadingCaptureKeepsRemainingSegmentsmastere66db61f4Local run with Redis:
apidef/...passes, and the URL rewrite, trigger,ReplaceTykVariables, looping andTestReverseProxyRetainHosttests pass.TestCheckActivePollerLoop,TestLooping/VirtualEndpoint_or_pluginsandTestSyncAPISpecsRPCFailure_CheckGlobalsalso fail locally on cleanmastere66db61f4, so they are not caused by this change.Benchmark of
urlRewrite(200000 iterations,-benchmem): a path-only rewrite costs 13 allocs and 577 B on bothmasterand this branch. A host rewrite that contains a variable adds 7 allocs and about 700 ns for the comparison.Existing test updated:
TestURLRewrite_EscapeBySource/trigger capture at the start of rewrite_to is not loadednow expects the API not to load. The request-time escaping that TT-18122 added is still covered at the middleware level.Types of changes
Checklist
Ticket Details
TT-19131
Generated at: 2026-11-26 14:30:34