-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhostname_forwarding_test.go
More file actions
327 lines (266 loc) · 10.7 KB
/
hostname_forwarding_test.go
File metadata and controls
327 lines (266 loc) · 10.7 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
package reverseproxy
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"testing"
"github.com/GoCodeAlone/modular"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestHostnameNotForwarded tests that the reverseproxy module does not forward
// the hostname to the backend service, keeping the original request's Host header.
func TestHostnameNotForwarded(t *testing.T) {
// Track what Host header the backend receives
var receivedHost string
// Create a mock backend server that captures the Host header
backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHost = r.Host
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"backend response","host":"` + r.Host + `"}`))
}))
defer backendServer.Close()
// Create a reverse proxy module
module := NewModule()
// Set up the module configuration
backendURL, err := url.Parse(backendServer.URL)
require.NoError(t, err)
module.config = &ReverseProxyConfig{
BackendServices: map[string]string{
"test-backend": backendServer.URL,
},
DefaultBackend: "test-backend",
TenantIDHeader: "X-Tenant-ID",
}
// Create the reverse proxy directly
proxy := module.createReverseProxyForBackend(context.Background(), backendURL, "", "")
require.NotNil(t, proxy)
// Test Case 1: Request with custom Host header should preserve it
t.Run("CustomHostHeaderPreserved", func(t *testing.T) {
// Reset captured values
receivedHost = ""
// Create a request with a custom Host header
req := httptest.NewRequest("GET", "http://original-host.com/api/test", nil)
req.Host = "original-host.com"
// Process the request through the proxy
w := httptest.NewRecorder()
proxy.ServeHTTP(w, req)
// Verify the response
resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Verify the Host header received by backend
// The backend should receive the original Host header, not the backend's host
assert.Equal(t, "original-host.com", receivedHost,
"Backend should receive original Host header, not be overridden with backend host")
// Verify response body
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Contains(t, string(body), `"host":"original-host.com"`)
})
// Test Case 2: Request without Host header should get it from URL
t.Run("NoHostHeaderUsesURLHost", func(t *testing.T) {
// Reset captured values
receivedHost = ""
// Create a request without explicit Host header
req := httptest.NewRequest("GET", "http://example.com/api/test", nil)
// Don't set req.Host - let it use the URL host
// Process the request through the proxy
w := httptest.NewRecorder()
proxy.ServeHTTP(w, req)
// Verify the response
resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
// The backend should receive the Host header from the original request URL
assert.Equal(t, "example.com", receivedHost,
"Backend should receive Host header from request URL when no explicit Host is set")
})
// Test Case 3: Request with different Host header and URL should preserve Host header
t.Run("HostHeaderOverridesURLHost", func(t *testing.T) {
// Reset captured values
receivedHost = ""
// Create a request with Host header different from URL host
req := httptest.NewRequest("GET", "http://url-host.com/api/test", nil)
req.Host = "header-host.com"
// Process the request through the proxy
w := httptest.NewRecorder()
proxy.ServeHTTP(w, req)
// Verify the response
resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
// The backend should receive the Host header value, not the URL host
assert.Equal(t, "header-host.com", receivedHost,
"Backend should receive Host header value when it differs from URL host")
})
}
// TestHostnameForwardingWithTenants tests that tenant-specific configurations
// also correctly handle hostname forwarding (i.e., don't forward it)
func TestHostnameForwardingWithTenants(t *testing.T) {
// Track what Host header the backend receives
var receivedHost string
var receivedTenantHeader string
// Create mock backend servers for different tenants
globalBackendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHost = r.Host
receivedTenantHeader = r.Header.Get("X-Tenant-ID")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"global backend","host":"` + r.Host + `"}`))
}))
defer globalBackendServer.Close()
tenantBackendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHost = r.Host
receivedTenantHeader = r.Header.Get("X-Tenant-ID")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"tenant backend","host":"` + r.Host + `"}`))
}))
defer tenantBackendServer.Close()
// Create a reverse proxy module
module := NewModule()
// Set up the module with global configuration
module.config = &ReverseProxyConfig{
BackendServices: map[string]string{
"api": globalBackendServer.URL,
},
DefaultBackend: "api",
TenantIDHeader: "X-Tenant-ID",
}
// Set up tenant-specific configuration that overrides the backend URL
tenantID := modular.TenantID("tenant-123")
module.tenants = make(map[modular.TenantID]*ReverseProxyConfig)
module.tenants[tenantID] = &ReverseProxyConfig{
BackendServices: map[string]string{
"api": tenantBackendServer.URL,
},
DefaultBackend: "api",
TenantIDHeader: "X-Tenant-ID",
}
// Test Case 1: Request without tenant header should use global backend
t.Run("GlobalBackendHostnameNotForwarded", func(t *testing.T) {
// Reset captured values
receivedHost = ""
receivedTenantHeader = ""
// Create the reverse proxy for global backend
globalURL, err := url.Parse(globalBackendServer.URL)
require.NoError(t, err)
proxy := module.createReverseProxyForBackend(context.Background(), globalURL, "", "")
// Create a request without tenant header
req := httptest.NewRequest("GET", "http://client.example.com/api/test", nil)
req.Host = "client.example.com"
// Process the request through the proxy
w := httptest.NewRecorder()
proxy.ServeHTTP(w, req)
// Verify the response
resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Verify the Host header received by global backend
assert.Equal(t, "client.example.com", receivedHost,
"Global backend should receive original Host header")
assert.Empty(t, receivedTenantHeader,
"Global backend should not receive tenant header")
})
// Test Case 2: Request with tenant header should use tenant backend
t.Run("TenantBackendHostnameNotForwarded", func(t *testing.T) {
// Reset captured values
receivedHost = ""
receivedTenantHeader = ""
// Create the reverse proxy for tenant backend
tenantURL, err := url.Parse(tenantBackendServer.URL)
require.NoError(t, err)
proxy := module.createReverseProxyForBackend(context.Background(), tenantURL, "", "")
// Create a request with tenant header
req := httptest.NewRequest("GET", "http://tenant-client.example.com/api/test", nil)
req.Host = "tenant-client.example.com"
req.Header.Set("X-Tenant-ID", string(tenantID))
// Process the request through the proxy
w := httptest.NewRecorder()
proxy.ServeHTTP(w, req)
// Verify the response
resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Verify the Host header received by tenant backend
assert.Equal(t, "tenant-client.example.com", receivedHost,
"Tenant backend should receive original Host header")
assert.Equal(t, string(tenantID), receivedTenantHeader,
"Tenant backend should receive the tenant header")
})
}
// TestHostnameForwardingComparisonWithDefault tests that our fix actually changes
// behavior from the default Go reverse proxy behavior
func TestHostnameForwardingComparisonWithDefault(t *testing.T) {
// Track what Host header the backend receives
var receivedHostCustom string
var receivedHostDefault string
// Create a mock backend server
backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This will be called by both proxies, we'll track both
if r.Header.Get("X-Proxy-Type") == "custom" {
receivedHostCustom = r.Host
} else {
receivedHostDefault = r.Host
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"backend response","host":"` + r.Host + `"}`))
}))
defer backendServer.Close()
backendURL, err := url.Parse(backendServer.URL)
require.NoError(t, err)
// Create our custom reverse proxy module
module := NewModule()
module.config = &ReverseProxyConfig{
BackendServices: map[string]string{
"test-backend": backendServer.URL,
},
DefaultBackend: "test-backend",
TenantIDHeader: "X-Tenant-ID",
}
customProxy := module.createReverseProxyForBackend(context.Background(), backendURL, "", "")
// Create a default Go reverse proxy for comparison
defaultProxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = backendURL.Scheme
req.URL.Host = backendURL.Host
req.URL.Path = backendURL.Path + req.URL.Path
// This is the default Go behavior - sets Host header to backend host
req.Host = backendURL.Host
},
}
// Test with the same request to both proxies
originalHost := "original-client.example.com"
// Test our custom proxy
t.Run("CustomProxyPreservesHost", func(t *testing.T) {
receivedHostCustom = ""
req := httptest.NewRequest("GET", "http://"+originalHost+"/api/test", nil)
req.Host = originalHost
req.Header.Set("X-Proxy-Type", "custom")
w := httptest.NewRecorder()
customProxy.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, originalHost, receivedHostCustom,
"Custom proxy should preserve original Host header")
})
// Test default proxy behavior
t.Run("DefaultProxyOverridesHost", func(t *testing.T) {
receivedHostDefault = ""
req := httptest.NewRequest("GET", "http://"+originalHost+"/api/test", nil)
req.Host = originalHost
req.Header.Set("X-Proxy-Type", "default")
w := httptest.NewRecorder()
defaultProxy.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, backendURL.Host, receivedHostDefault,
"Default proxy should override Host header with backend host")
})
// Verify that the behaviors are actually different
assert.NotEqual(t, receivedHostCustom, receivedHostDefault,
"Custom and default proxy should have different Host header behaviors")
assert.Equal(t, originalHost, receivedHostCustom,
"Custom proxy should preserve original host")
assert.Equal(t, backendURL.Host, receivedHostDefault,
"Default proxy should use backend host")
}