-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat: Add dynamic variable support for upstream URLs #7290
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
This commit introduces the ability to use dynamic variables in upstream URLs, enabling powerful routing capabilities based on session metadata and request context. Key changes: - Modified reverse_proxy.go to process variables in upstream URLs - Added comprehensive integration tests - Created documentation for the feature 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com>
PR Reviewer Guide 🔍Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Explore these optional code suggestions:
|
|
API Changes no api changes detected |
📦 Impact Review Snapshot
## Impact AssessmentThis PR adds dynamic variable support for upstream URLs by leveraging the existing Since this change doesn't alter any schemas, protocols, or interfaces, it has minimal impact on downstream repositories. The feature is opt-in via the existing ## Required UpdatesNo schema or interface changes are required in downstream repositories. The feature leverages existing API definition fields and functionality. However, documentation updates would be beneficial in:
## Compatibility ConcernsThe implementation has excellent backward compatibility:
The only potential concern is ensuring that error handling is robust when invalid variables are used in upstream URLs, but the PR includes comprehensive tests for error cases. ## Summary & Recommendations
Tip: Mention me again using |
🚀 Performance Snapshot
## Performance Impact AnalysisThe PR adds dynamic variable substitution in the reverse proxy director function, which is in the critical request path. The implementation processes variables in two places: load-balanced hosts and target URLs. Variable substitution involves regex matching, string operations, and map lookups, adding a small overhead (likely <1ms per request) when enabled. The feature is opt-in via ## Critical AreasThe most performance-sensitive change is in the director function of ## Optimization Recommendations
## Summary
Tip: Mention me again using |
🚦 Connectivity Review Snapshot
## Connectivity Assessment
## Test Coverage Validation
## Security & Performance Impact
## Summary & Recommendations
Tip: Mention me again using |
🛡️ Security Snapshot
## Security Impact AnalysisThis PR introduces dynamic variable substitution in upstream URLs, allowing routing decisions based on session metadata, request context, and external configuration sources. The implementation modifies the reverse proxy director function to process variables in both load-balanced hosts and target URLs. The feature is opt-in via The implementation includes proper URL validation after variable substitution and has error handling for invalid URLs, which mitigates some risks. The code also maintains connection pooling efficiency by using Go's standard HTTP transport mechanisms. ## Identified VulnerabilitiesMedium: Potential SSRF via User-Controlled Metadata
Low: Header-Based Routing Manipulation
Low: Error Handling Information Disclosure
## Security Recommendations
## OWASP ComplianceA1:2021 - Broken Access Control: The feature could potentially bypass network segmentation if not properly configured. Ensure proper access controls on metadata sources. A10:2021 - Server-Side Request Forgery: The primary risk of this feature is SSRF if user-controlled data influences routing. Implement proper validation and allowlists. The implementation follows best practices for URL parsing and validation, which helps mitigate injection risks. The opt-in nature of the feature also reduces the attack surface. ## Summary
Tip: Mention me again using |
Transform CLAUDE.md from a PR-specific document into a general-purpose development guide for AI assistants and developers working with Tyk Gateway. Key improvements: - Add project overview and architecture patterns - Expand testing best practices with complete examples - Include debugging tips and common pitfalls - Add comprehensive file reference for navigation - Include build commands and environment setup - Add security and performance considerations - Make it feature-agnostic for broader applicability This guide now serves as a central reference for understanding the Tyk codebase structure, development workflows, testing patterns, and debugging techniques - useful for any future development work, not just dynamic URLs.
🚀 Performance Snapshot
## Performance Impact AnalysisThis PR adds dynamic variable substitution in the reverse proxy director function, which is in the critical request path. The implementation processes variables in two places: load-balanced hosts and target URLs. Variable substitution involves regex matching, string operations, and map lookups, adding a small overhead (likely <1ms per request) when enabled. The feature is opt-in via ## Critical AreasThe most performance-sensitive change is in the director function of ## Optimization Recommendations
## Summary
Tip: Mention me again using |
🛡️ Security Snapshot
## Security Impact AnalysisThis PR introduces dynamic variable substitution in upstream URLs, allowing the gateway to route requests to different backends based on session metadata, request context, and other variables. The implementation modifies the reverse proxy director function to process variables in both load-balanced hosts and target URLs. The feature is opt-in via the ## Identified VulnerabilitiesMedium: Potential SSRF via User-Controlled Metadata
Low: Header-Based Routing Manipulation
Low: Error Handling Information Disclosure
## Security Recommendations
## OWASP ComplianceA1:2021 - Broken Access Control: The feature could potentially bypass network segmentation if not properly configured. Ensure proper access controls on metadata sources. A10:2021 - Server-Side Request Forgery: The primary risk of this feature is SSRF if user-controlled data influences routing. Implement proper validation and allowlists. The implementation follows best practices for URL parsing and validation, which helps mitigate injection risks. The opt-in nature of the feature also reduces the attack surface. ## Summary
Tip: Mention me again using |
📦 Impact Review Snapshot
## Impact AssessmentThis PR adds dynamic variable support for upstream URLs by leveraging the existing Since this change doesn't alter any schemas, protocols, or interfaces, it has minimal impact on downstream repositories. The feature is opt-in via the existing ## Required UpdatesNo schema or interface changes are required in downstream repositories. The feature leverages existing API definition fields and functionality. However, documentation updates would be beneficial in:
## Compatibility ConcernsThe implementation has excellent backward compatibility:
The only potential concern is ensuring that error handling is robust when invalid variables are used in upstream URLs, but the PR includes comprehensive tests for error cases. ## Summary & Recommendations
Tip: Mention me again using |
🚦 Connectivity Review Snapshot
## Connectivity Assessment
## Test Coverage Validation
## Security & Performance Impact
## Summary & Recommendations
Tip: Mention me again using |
User description
Summary
This PR introduces dynamic variable support for upstream URLs in Tyk Gateway, enabling powerful routing capabilities based on session metadata, request context, and external configuration sources. This feature allows users to route requests to different upstream servers dynamically without needing multiple API definitions.
Motivation
Currently, Tyk requires static upstream URLs in API definitions. This limitation means:
This PR solves these issues by allowing variables like
$tyk_meta.upstream_hostand$tyk_context.headers_X_Target_Hostin upstream URLs.Implementation Details
Core Changes
The implementation modifies the reverse proxy director function in
gateway/reverse_proxy.go:Static URL Processing (lines 293-312):
EnableContextVarsis trueLoad Balancing Integration (lines 260-267):
URL Construction Fix (line 319):
variablesProcessedflagSupported Variable Types
$tyk_meta.*- Session metadata variables (user-specific routing)$tyk_context.*- Request context variables (header-based routing)$secret_env.*- Environment variables (with TYK_SECRET_ prefix)$secret_vault.*- HashiCorp Vault integration$secret_consul.*- Consul KV store values$secret_conf.*- Configuration secretsTesting Strategy
Comprehensive Integration Tests
Created
gateway/reverse_proxy_dynamic_url_test.gowith real-world scenarios:1. Regional Routing Test (
TestDynamicUpstreamURL_Integration)2. Load Balancing with Variables (
TestDynamicUpstreamURL_LoadBalancing)$tyk_meta.api_versionvariable3. Context Variables (
TestDynamicUpstreamURL_ContextVariables)$tyk_context.headers_X_Target_Versionvariable4. Policy Metadata (
TestDynamicUpstreamURL_PolicyMetadata)5. Connection Pooling (
TestDynamicUpstreamURL_ConnectionPooling)6. Error Handling (
TestDynamicUpstreamURL_ErrorHandling)Test Execution
All tests use Tyk's integration test framework:
Performance Considerations
Connection Pooling
http.Transportautomatically maintains separate connection pools per unique hostVariable Processing
EnableContextVars: trueUse Cases Enabled
1. Multi-Tenant SaaS
{ "target_url": "http://$tyk_meta.tenant_id.backend.internal/" }2. Regional Routing
{ "target_url": "http://$tyk_meta.region.api.example.com/" }3. Blue-Green Deployments
{ "target_url": "http://$tyk_meta.deployment_color.service.internal/" }4. A/B Testing
{ "target_url": "http://backend-$tyk_meta.experiment_group.internal/" }5. Header-Based Routing
{ "target_url": "http://$tyk_context.headers_X_Backend_Override/" }Backward Compatibility
EnableContextVarsflagConfiguration Example
{ "name": "Dynamic Routing API", "api_id": "dynamic-api", "proxy": { "listen_path": "/api/", "target_url": "http://$tyk_meta.upstream_host:$tyk_meta.port/", "strip_listen_path": true, "enable_load_balancing": true, "target_list": [ "http://$tyk_meta.primary_host/", "http://$tyk_meta.secondary_host/" ] }, "enable_context_vars": true }Documentation
Added comprehensive documentation in
CLAUDE.md:TYK_LOGLEVEL)Security Considerations
Checklist
reverse_proxy.goCLAUDE.mdTest Results
Future Enhancements
Potential future improvements (not in this PR):
Breaking Changes
None. This is a backward-compatible enhancement.
Migration Guide
No migration required. To use the feature:
enable_context_vars: truein your API definitiontarget_urlortarget_listRelated Issues
This PR addresses common feature requests for:
🤖 Generated with Claude Code
PR Type
Enhancement, Tests, Documentation
Description
Add dynamic variable processing for upstream URLs
Support variables in load-balanced targets
Add comprehensive integration and error tests
Add developer guide documenting feature usage
Diagram Walkthrough
File Walkthrough
reverse_proxy.go
Variable substitution in targets and final URLgateway/reverse_proxy.go
variablesProcessedand update scheme/host/path/query.reverse_proxy_dynamic_url_test.go
Tests for dynamic upstream URL behaviorgateway/reverse_proxy_dynamic_url_test.go
CLAUDE.md
Developer guide for dynamic URL featureCLAUDE.md