Skip to content

[TT-19131]: Stop request values choosing the URL rewrite host - #8991

Open
kofoworola wants to merge 5 commits into
masterfrom
TT-19131-url-rewrite-request-host
Open

kofoworola wants to merge 5 commits into
masterfrom
TT-19131-url-rewrite-request-host

Conversation

@kofoworola

@kofoworola kofoworola commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

A URL rewrite can no longer send a request to a server that the API client chose.

  • On load. The Gateway skips an API whose URL rewrite rewrite_to, or a trigger's rewrite_to, starts with a numbered capture ($0, $1, …) or a $tyk_context variable. It logs the API ID and the rule, and loads the other APIs. The same rule is in apidef.DefaultValidationRuleSet, so the Gateway API and the Dashboard reject these definitions on save.
  • At request time. When the rewritten URL has a host and rewrite_to has a variable, the middleware rebuilds the URL with every request value left empty. If the scheme, user info, host or port differ, it returns 400 Bad Request and sends nothing upstream. Each secret is resolved once and reused, so the check doesn't call the secret store twice.
  • Empty leading capture. With rewrite_to: "/$1/$2" and an empty $1, the upstream now receives /$2 instead of the base path.

These keep working as before:

  • Hosts that the API manager wrote literally, or through $tyk_meta or a secret reference.
  • Absolute http, https, ws, wss and h2c rewrites.
  • tyk:// loop targets.
  • rewrite_to values 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_to of $1, with ?u=http://other-host/x, sends the request, including headers that the API adds such as upstream credentials, to other-host. That is server-side request forgery. A value after a literal host, such as http://api.internal$1 with $1=@other-host/x, does the same through the URL's user-info syntax.

Behavior change. An API whose rewrite_to starts with $1 or $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_context values 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:

AC What Test
1 Skip on load, log, other APIs load (classic, OAS, triggers); the error names the rule TestURLRewrite_RequestValueAtStartOfRewriteToIsNotLoaded, TestRuleURLRewriteTarget_Validate
4 /$1, /api/$1 load and stay on target_url TestURLRewrite_LiteralPrefixKeepsRequestOnTarget
5 400 at request time for http, https, HTTP, ftp, //host, user info, port, triggers, OAS TestURLRewriteMiddleware_RequestValueCannotSetHost, TestURLRewrite_RequestValueCannotCompleteTheHost
6 $tyk_meta and secret references still choose the server TestURLRewrite_APIManagerValuesCanStillChooseHost, TestReplaceTykVariables_ReusesResolvedSecrets
7 Upstream headers never reach a host the API client chose Rogue upstream in the tests above receives no request
8 Absolute http, https, ws, wss, h2c rewrites and tyk:// unchanged API manager subtests of TestURLRewriteMiddleware_RequestValueCannotSetHost
9 /$1/$2 with an empty $1 TestURLRewrite_EmptyLeadingCaptureKeepsRemainingSegments
10 Classic and OAS OAS subtests in the tests above
11 Tests fail on unfixed code All the request and load tests above fail on master e66db61f4

Local run with Redis: apidef/... passes, and the URL rewrite, trigger, ReplaceTykVariables, looping and TestReverseProxyRetainHost tests pass. TestCheckActivePollerLoop, TestLooping/VirtualEndpoint_or_plugins and TestSyncAPISpecsRPCFailure_CheckGlobals also fail locally on clean master e66db61f4, 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 both master and 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 loaded now expects the API not to load. The request-time escaping that TT-18122 added is still covered at the middleware level.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring or add test (improvements in base code or adds test coverage to functionality)

Checklist

  • I ensured that the documentation is up to date. The URL rewrite docs and the security advisory are tracked outside this PR.
  • I explained why this PR updates go.mod in detail with reasoning why it's required. go.mod is unchanged.
  • I would like a code coverage CI quality gate exception and have explained why

Ticket Details

TT-19131
Status In Code Review
Summary [Security] URL Rewrite Numbered Capture Group Can Override Upstream Host (SSRF)

Generated at: 2026-11-26 14:30:34

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.
@probelabs

probelabs Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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 rewrite_to directive.

The fix implements a two-layered defense strategy:

  1. Load-Time Validation (Breaking Change): A new validation rule, RuleURLRewriteTarget, is added to the default validation set. This rule prevents any API Definition from being loaded if its rewrite_to value (in a URL rewrite or its triggers) starts with a request-controlled variable like a numbered capture group ($1, $2, etc.) or a $tyk_context variable. APIs with such configurations will now fail to load, and an error will be logged.

  2. Request-Time Check: For URL rewrites that pass the load-time validation but still use variables after a literal host (e.g., http://api.internal/$1), a new runtime check is performed. The middleware compares the rewritten URL against a version generated without any request-controlled values. If the scheme, host, port, or user-info differs, it indicates that a request value attempted to modify the upstream target. In such cases, the request is immediately rejected with a 400 Bad Request, and no request is sent upstream.

Additionally, the PR addresses an edge case where an empty leading capture group (e.g., $1 in /$1/$2) could cause an incorrect path rewrite. It also includes a performance optimization to cache resolved secrets within a single request, avoiding redundant lookups during the host-check comparison.

Files Changed Analysis

The changes are primarily focused on the apidef and gateway packages, with extensive new tests to cover the security fixes:

  • apidef/validator_url_rewrite.go (new): Introduces the new load-time validation logic (RuleURLRewriteTarget) that rejects API definitions with rewrite_to values starting with request-controlled variables.
  • apidef/validator.go: Registers the new RuleURLRewriteTarget into the DefaultValidationRuleSet, ensuring it is applied by default in the Gateway, Dashboard, and CLI.
  • gateway/api_definition.go: Integrates the new validation rule into the API specification loading process, preventing insecure APIs from being loaded by the Gateway.
  • gateway/mw_url_rewrite.go: Implements the core request-time check (requestValueSetsHost) to detect and block attempts to change the upstream host using request values. It also includes logic for caching resolved secrets during this process.
  • gateway/server.go: Enhances logging to include the api_id when an API specification fails validation, improving debuggability.
  • New Test Files: apidef/validator_url_rewrite_test.go, gateway/mw_url_rewrite_empty_capture_test.go, gateway/mw_url_rewrite_host_from_request_test.go, and gateway/mw_url_rewrite_request_host_test.go provide comprehensive test coverage for the new validation rules, runtime checks, edge cases, and attack vectors.

Architecture & Impact Assessment

  • What this PR accomplishes: It patches a critical SSRF vulnerability by preventing API clients from controlling the upstream host via the URL rewrite middleware.
  • Key technical changes introduced: The PR introduces a defense-in-depth approach with a strict load-time validation rule and a dynamic request-time security check. This is a breaking change for any existing APIs that rely on insecure rewrite patterns.
  • Affected system components: The changes primarily affect the Gateway's API loading process and the URL Rewrite middleware. Due to the modification of the DefaultValidationRuleSet, the impact extends to any component that validates API definitions, including the Tyk Dashboard and the Tyk Gateway CLI (check command).

Visualization of Security Checks

This 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
Loading

Scope Discovery & Context Expansion

The scope of this change is broader than just the Gateway's runtime behavior. By adding the new validation rule to apidef.DefaultValidationRuleSet, this security measure is automatically inherited by other tools in the Tyk ecosystem:

  • Tyk Dashboard: Will prevent users from creating or saving API definitions that contain this insecure URL rewrite pattern.
  • Tyk Gateway CLI: The tyk check command will now fail when validating an API definition that violates this new rule.

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
  • Review Effort: 4 / 5
  • Primary Label: bug

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 /visor ask <your question>

@probelabs

probelabs Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

✅ Security Check Passed

No security issues found – changes LGTM.

Performance Issues (1)

Severity Location Issue
🟠 Error contract:0
Output schema validation failed: must have required property 'issues'

✅ Security Check Passed

No security issues found – changes LGTM.

\n\n \n\n

Performance Issues (1)

Severity Location Issue
🟠 Error contract:0
Output schema validation failed: must have required property 'issues'
\n\n ### ✅ Quality Check Passed

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 /visor ask <your question>

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-cnapp-eu1

Copy link
Copy Markdown

SentinelOne CNS Hardcoded Secret Detector
✅ Congratulations, your code is safe

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.

@kofoworola
kofoworola marked this pull request as ready for review November 26, 2026 13:37
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@kofoworola kofoworola changed the title TT-19131: Stop request values choosing the URL rewrite host [TT-19131]: Stop request values choosing the URL rewrite host Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant