| 1 |
// Copyright 2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"errors" |
| 18 |
"fmt" |
| 19 |
"net" |
| 20 |
"net/url" |
| 21 |
"strings" |
| 22 |
"testing" |
| 23 |
"time" |
| 24 |
) |
| 25 |
|
| 26 |
// Basic HTTP proxy for testing |
| 27 |
type testHTTPProxy struct { |
| 28 |
listener net.Listener |
| 29 |
port int |
| 30 |
username string |
| 31 |
password string |
| 32 |
started bool |
| 33 |
closeDelay time.Duration // Delay before closing connections for robustness |
| 34 |
connections []net.Conn // Track connections for cleanup |
| 35 |
} |
| 36 |
|
| 37 |
func createTestHTTPProxy(username, password string) *testHTTPProxy { |
| 38 |
l, err := net.Listen("tcp", "127.0.0.1:0") |
| 39 |
if err != nil { |
| 40 |
panic(err) |
| 41 |
} |
| 42 |
port := l.Addr().(*net.TCPAddr).Port |
| 43 |
|
| 44 |
proxy := &testHTTPProxy{ |
| 45 |
listener: l, |
| 46 |
port: port, |
| 47 |
username: username, |
| 48 |
password: password, |
| 49 |
closeDelay: 100 * time.Millisecond, // Default delay for test robustness |
| 50 |
connections: make([]net.Conn, 0), |
| 51 |
} |
| 52 |
|
| 53 |
return proxy |
| 54 |
} |
| 55 |
|
| 56 |
func (p *testHTTPProxy) setCloseDelay(delay time.Duration) { |
| 57 |
p.closeDelay = delay |
| 58 |
} |
| 59 |
|
| 60 |
func (p *testHTTPProxy) start() { |
| 61 |
if p.started { |
| 62 |
return |
| 63 |
} |
| 64 |
p.started = true |
| 65 |
|
| 66 |
go func() { |
| 67 |
for { |
| 68 |
conn, err := p.listener.Accept() |
| 69 |
if err != nil { |
| 70 |
return |
| 71 |
} |
| 72 |
p.connections = append(p.connections, conn) |
| 73 |
go p.handleConnection(conn) |
| 74 |
} |
| 75 |
}() |
| 76 |
} |
| 77 |
|
| 78 |
func (p *testHTTPProxy) handleConnection(conn net.Conn) { |
| 79 |
defer func() { |
| 80 |
if p.closeDelay > 0 { |
| 81 |
time.Sleep(p.closeDelay) |
| 82 |
} |
| 83 |
conn.Close() |
| 84 |
}() |
| 85 |
|
| 86 |
// Set read timeout to prevent hanging on malformed requests |
| 87 |
conn.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 88 |
|
| 89 |
// Read the CONNECT request |
| 90 |
buffer := make([]byte, 4096) |
| 91 |
n, err := conn.Read(buffer) |
| 92 |
if err != nil { |
| 93 |
return |
| 94 |
} |
| 95 |
|
| 96 |
request := string(buffer[:n]) |
| 97 |
lines := strings.Split(request, "\r\n") |
| 98 |
|
| 99 |
if len(lines) == 0 || !strings.HasPrefix(lines[0], "CONNECT ") { |
| 100 |
conn.Write([]byte("HTTP/1.1 400 Bad Request\r\n\r\n")) |
| 101 |
return |
| 102 |
} |
| 103 |
|
| 104 |
// Check authentication if required |
| 105 |
if p.username != _EMPTY_ || p.password != _EMPTY_ { |
| 106 |
authFound := false |
| 107 |
for _, line := range lines { |
| 108 |
if strings.HasPrefix(line, "Proxy-Authorization: Basic ") { |
| 109 |
authFound = true |
| 110 |
break |
| 111 |
} |
| 112 |
} |
| 113 |
if !authFound { |
| 114 |
conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n")) |
| 115 |
return |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
// Extract target host from CONNECT line |
| 120 |
parts := strings.Fields(lines[0]) |
| 121 |
if len(parts) < 3 { |
| 122 |
conn.Write([]byte("HTTP/1.1 400 Bad Request\r\n\r\n")) |
| 123 |
return |
| 124 |
} |
| 125 |
|
| 126 |
targetHost := parts[1] |
| 127 |
|
| 128 |
// Connect to target with timeout |
| 129 |
target, err := net.DialTimeout("tcp", targetHost, 5*time.Second) |
| 130 |
if err != nil { |
| 131 |
conn.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n")) |
| 132 |
return |
| 133 |
} |
| 134 |
defer target.Close() |
| 135 |
|
| 136 |
// Send success response |
| 137 |
conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")) |
| 138 |
|
| 139 |
// Clear read deadline for ongoing connection |
| 140 |
conn.SetReadDeadline(time.Time{}) |
| 141 |
|
| 142 |
// Relay data between client and target with proper error handling |
| 143 |
done := make(chan bool, 2) |
| 144 |
|
| 145 |
// Client to target |
| 146 |
go func() { |
| 147 |
defer func() { |
| 148 |
done <- true |
| 149 |
target.Close() |
| 150 |
}() |
| 151 |
buffer := make([]byte, 32*1024) |
| 152 |
for { |
| 153 |
conn.SetReadDeadline(time.Now().Add(30 * time.Second)) |
| 154 |
n, err := conn.Read(buffer) |
| 155 |
if err != nil { |
| 156 |
return |
| 157 |
} |
| 158 |
target.SetWriteDeadline(time.Now().Add(10 * time.Second)) |
| 159 |
_, err = target.Write(buffer[:n]) |
| 160 |
if err != nil { |
| 161 |
return |
| 162 |
} |
| 163 |
} |
| 164 |
}() |
| 165 |
|
| 166 |
// Target to client |
| 167 |
go func() { |
| 168 |
defer func() { |
| 169 |
done <- true |
| 170 |
conn.Close() |
| 171 |
}() |
| 172 |
buffer := make([]byte, 32*1024) |
| 173 |
for { |
| 174 |
target.SetReadDeadline(time.Now().Add(30 * time.Second)) |
| 175 |
n, err := target.Read(buffer) |
| 176 |
if err != nil { |
| 177 |
return |
| 178 |
} |
| 179 |
conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) |
| 180 |
_, err = conn.Write(buffer[:n]) |
| 181 |
if err != nil { |
| 182 |
return |
| 183 |
} |
| 184 |
} |
| 185 |
}() |
| 186 |
|
| 187 |
// Wait for either direction to finish |
| 188 |
<-done |
| 189 |
} |
| 190 |
|
| 191 |
func (p *testHTTPProxy) stop() { |
| 192 |
if p.listener != nil { |
| 193 |
p.listener.Close() |
| 194 |
} |
| 195 |
// Close all tracked connections with delay for robustness |
| 196 |
for _, conn := range p.connections { |
| 197 |
go func(c net.Conn) { |
| 198 |
if p.closeDelay > 0 { |
| 199 |
time.Sleep(p.closeDelay) |
| 200 |
} |
| 201 |
c.Close() |
| 202 |
}(conn) |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
func (p *testHTTPProxy) url() string { |
| 207 |
return fmt.Sprintf("http://127.0.0.1:%d", p.port) |
| 208 |
} |
| 209 |
|
| 210 |
func TestLeafNodeHttpProxyConfigParsing(t *testing.T) { |
| 211 |
// Test valid proxy configuration |
| 212 |
conf := ` |
| 213 |
leafnodes { |
| 214 |
remotes = [ |
| 215 |
{ |
| 216 |
url: "ws://127.0.0.1:7422" |
| 217 |
proxy { |
| 218 |
url: "http://proxy.example.com:8080" |
| 219 |
username: "user" |
| 220 |
password: "pass" |
| 221 |
timeout: "10s" |
| 222 |
} |
| 223 |
} |
| 224 |
] |
| 225 |
} |
| 226 |
` |
| 227 |
|
| 228 |
configFile := createConfFile(t, []byte(conf)) |
| 229 |
|
| 230 |
opts, err := ProcessConfigFile(configFile) |
| 231 |
if err != nil { |
| 232 |
t.Fatalf("Error parsing config: %v", err) |
| 233 |
} |
| 234 |
|
| 235 |
if len(opts.LeafNode.Remotes) != 1 { |
| 236 |
t.Fatalf("Expected 1 remote, got %d", len(opts.LeafNode.Remotes)) |
| 237 |
} |
| 238 |
|
| 239 |
remote := opts.LeafNode.Remotes[0] |
| 240 |
if remote.Proxy.URL != "http://proxy.example.com:8080" { |
| 241 |
t.Errorf("Expected proxy URL 'http://proxy.example.com:8080', got '%s'", remote.Proxy.URL) |
| 242 |
} |
| 243 |
if remote.Proxy.Username != "user" { |
| 244 |
t.Errorf("Expected proxy username 'user', got '%s'", remote.Proxy.Username) |
| 245 |
} |
| 246 |
if remote.Proxy.Password != "pass" { |
| 247 |
t.Errorf("Expected proxy password 'pass', got '%s'", remote.Proxy.Password) |
| 248 |
} |
| 249 |
if remote.Proxy.Timeout != 10*time.Second { |
| 250 |
t.Errorf("Expected proxy timeout 10s, got %v", remote.Proxy.Timeout) |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
func TestLeafNodeHttpProxyConfigWarnings(t *testing.T) { |
| 255 |
testCases := []struct { |
| 256 |
name string |
| 257 |
config string |
| 258 |
expectWarning bool |
| 259 |
warningMatch string |
| 260 |
}{ |
| 261 |
{ |
| 262 |
name: "proxy with only TCP URLs", |
| 263 |
config: ` |
| 264 |
leafnodes { |
| 265 |
remotes = [ |
| 266 |
{ |
| 267 |
url: "nats://127.0.0.1:7422" |
| 268 |
proxy { |
| 269 |
url: "http://proxy.example.com:8080" |
| 270 |
} |
| 271 |
} |
| 272 |
] |
| 273 |
} |
| 274 |
`, |
| 275 |
expectWarning: true, |
| 276 |
warningMatch: "proxy configuration will be ignored", |
| 277 |
}, |
| 278 |
{ |
| 279 |
name: "proxy with mixed TCP and WebSocket URLs", |
| 280 |
config: ` |
| 281 |
leafnodes { |
| 282 |
remotes = [ |
| 283 |
{ |
| 284 |
urls: ["nats://127.0.0.1:7422", "ws://127.0.0.1:8080"] |
| 285 |
proxy { |
| 286 |
url: "http://proxy.example.com:8080" |
| 287 |
} |
| 288 |
} |
| 289 |
] |
| 290 |
} |
| 291 |
`, |
| 292 |
expectWarning: true, |
| 293 |
warningMatch: "proxy configuration will only be used for WebSocket URLs", |
| 294 |
}, |
| 295 |
{ |
| 296 |
name: "proxy with only WebSocket URLs", |
| 297 |
config: ` |
| 298 |
leafnodes { |
| 299 |
remotes = [ |
| 300 |
{ |
| 301 |
url: "ws://127.0.0.1:7422" |
| 302 |
proxy { |
| 303 |
url: "http://proxy.example.com:8080" |
| 304 |
} |
| 305 |
} |
| 306 |
] |
| 307 |
} |
| 308 |
`, |
| 309 |
expectWarning: false, |
| 310 |
}, |
| 311 |
} |
| 312 |
|
| 313 |
for _, tc := range testCases { |
| 314 |
t.Run(tc.name, func(t *testing.T) { |
| 315 |
configFile := createConfFile(t, []byte(tc.config)) |
| 316 |
|
| 317 |
opts, err := ProcessConfigFile(configFile) |
| 318 |
|
| 319 |
if tc.expectWarning { |
| 320 |
// With ProcessConfigFile, warnings don't cause errors |
| 321 |
// The configuration should be valid but might log warnings |
| 322 |
if err != nil { |
| 323 |
t.Fatalf("Expected valid configuration with warnings, but got error: %v", err) |
| 324 |
} |
| 325 |
if opts == nil { |
| 326 |
t.Fatal("Expected valid options but got nil") |
| 327 |
} |
| 328 |
// Note: With ProcessConfigFile, warnings are filtered out and not returned as errors |
| 329 |
// The test verifies that the configuration is valid despite having warning conditions |
| 330 |
} else { |
| 331 |
// No warnings expected - should parse successfully |
| 332 |
if err != nil { |
| 333 |
t.Fatalf("Expected no error but got: %v", err) |
| 334 |
} |
| 335 |
if opts == nil { |
| 336 |
t.Fatal("Expected valid options but got nil") |
| 337 |
} |
| 338 |
} |
| 339 |
}) |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
func TestLeafNodeHttpProxyConnection(t *testing.T) { |
| 344 |
// Create a hub server with WebSocket support using config file |
| 345 |
hubConfig := createConfFile(t, []byte(` |
| 346 |
listen: "127.0.0.1:-1" |
| 347 |
websocket { |
| 348 |
listen: "127.0.0.1:-1" |
| 349 |
no_tls: true |
| 350 |
} |
| 351 |
leafnodes { |
| 352 |
listen: "127.0.0.1:-1" |
| 353 |
} |
| 354 |
`)) |
| 355 |
|
| 356 |
hub, hubOpts := RunServerWithConfig(hubConfig) |
| 357 |
defer hub.Shutdown() |
| 358 |
|
| 359 |
// Create HTTP proxy |
| 360 |
proxy := createTestHTTPProxy(_EMPTY_, _EMPTY_) |
| 361 |
proxy.start() |
| 362 |
defer proxy.stop() |
| 363 |
|
| 364 |
// Create spoke server with proxy configuration via config file |
| 365 |
configContent := fmt.Sprintf(` |
| 366 |
listen: "127.0.0.1:-1" |
| 367 |
leafnodes { |
| 368 |
reconnect_interval: "50ms" |
| 369 |
remotes = [ |
| 370 |
{ |
| 371 |
url: "ws://127.0.0.1:%d" |
| 372 |
proxy { |
| 373 |
url: "%s" |
| 374 |
timeout: 5s |
| 375 |
} |
| 376 |
} |
| 377 |
] |
| 378 |
} |
| 379 |
`, hubOpts.Websocket.Port, proxy.url()) |
| 380 |
|
| 381 |
configFile := createConfFile(t, []byte(configContent)) |
| 382 |
|
| 383 |
spoke, _ := RunServerWithConfig(configFile) |
| 384 |
defer spoke.Shutdown() |
| 385 |
|
| 386 |
// Verify leafnode connections are established |
| 387 |
checkLeafNodeConnected(t, spoke) |
| 388 |
checkLeafNodeConnected(t, hub) |
| 389 |
} |
| 390 |
|
| 391 |
func TestLeafNodeHttpProxyConnectionToTCP(t *testing.T) { |
| 392 |
// Create a hub server using config file |
| 393 |
hubConfig := createConfFile(t, []byte(` |
| 394 |
listen: "127.0.0.1:-1" |
| 395 |
leafnodes { |
| 396 |
listen: "127.0.0.1:-1" |
| 397 |
} |
| 398 |
`)) |
| 399 |
|
| 400 |
hub, hubOpts := RunServerWithConfig(hubConfig) |
| 401 |
defer hub.Shutdown() |
| 402 |
|
| 403 |
// Create HTTP proxy |
| 404 |
proxy := createTestHTTPProxy(_EMPTY_, _EMPTY_) |
| 405 |
proxy.start() |
| 406 |
defer proxy.stop() |
| 407 |
|
| 408 |
// Create spoke server with proxy configuration via config file |
| 409 |
configContent := fmt.Sprintf(` |
| 410 |
listen: "127.0.0.1:-1" |
| 411 |
leafnodes { |
| 412 |
reconnect_interval: "50ms" |
| 413 |
remotes = [ |
| 414 |
{ |
| 415 |
url: "nats://127.0.0.1:%d" |
| 416 |
proxy { |
| 417 |
url: "%s" |
| 418 |
timeout: 5s |
| 419 |
} |
| 420 |
} |
| 421 |
] |
| 422 |
} |
| 423 |
`, hubOpts.LeafNode.Port, proxy.url()) |
| 424 |
|
| 425 |
configFile := createConfFile(t, []byte(configContent)) |
| 426 |
|
| 427 |
spoke, _ := RunServerWithConfig(configFile) |
| 428 |
defer spoke.Shutdown() |
| 429 |
|
| 430 |
// Verify leafnode connections are established |
| 431 |
checkLeafNodeConnected(t, spoke) |
| 432 |
checkLeafNodeConnected(t, hub) |
| 433 |
} |
| 434 |
|
| 435 |
func TestLeafNodeHttpProxyWithAuthentication(t *testing.T) { |
| 436 |
// Create a hub server with WebSocket support using config file |
| 437 |
hubConfig := createConfFile(t, []byte(` |
| 438 |
listen: "127.0.0.1:-1" |
| 439 |
websocket { |
| 440 |
listen: "127.0.0.1:-1" |
| 441 |
no_tls: true |
| 442 |
} |
| 443 |
leafnodes { |
| 444 |
listen: "127.0.0.1:-1" |
| 445 |
} |
| 446 |
`)) |
| 447 |
|
| 448 |
hub, hubOpts := RunServerWithConfig(hubConfig) |
| 449 |
defer hub.Shutdown() |
| 450 |
|
| 451 |
// Create HTTP proxy with authentication |
| 452 |
proxy := createTestHTTPProxy("testuser", "testpass") |
| 453 |
proxy.start() |
| 454 |
defer proxy.stop() |
| 455 |
|
| 456 |
// Create spoke server with proxy configuration including auth via config file |
| 457 |
configContent := fmt.Sprintf(` |
| 458 |
listen: "127.0.0.1:-1" |
| 459 |
leafnodes { |
| 460 |
reconnect_interval: "50ms" |
| 461 |
remotes = [ |
| 462 |
{ |
| 463 |
url: "ws://127.0.0.1:%d" |
| 464 |
proxy { |
| 465 |
url: "%s" |
| 466 |
username: "testuser" |
| 467 |
password: "testpass" |
| 468 |
timeout: 5s |
| 469 |
} |
| 470 |
} |
| 471 |
] |
| 472 |
} |
| 473 |
`, hubOpts.Websocket.Port, proxy.url()) |
| 474 |
|
| 475 |
configFile := createConfFile(t, []byte(configContent)) |
| 476 |
|
| 477 |
spoke, _ := RunServerWithConfig(configFile) |
| 478 |
defer spoke.Shutdown() |
| 479 |
|
| 480 |
// Verify leafnode connections are established |
| 481 |
checkLeafNodeConnected(t, spoke) |
| 482 |
checkLeafNodeConnected(t, hub) |
| 483 |
} |
| 484 |
|
| 485 |
func TestLeafNodeHttpProxyTLSMismatchDetection(t *testing.T) { |
| 486 |
// This test simulates the TLS mismatch scenario described in the feedback: |
| 487 |
// - Leafnode configured with proxy but no TLS |
| 488 |
// - Hub requires TLS |
| 489 |
// - Connection should fail with appropriate error message |
| 490 |
|
| 491 |
// Create hub server with TLS required using config file |
| 492 |
hubConfig := createConfFile(t, []byte(` |
| 493 |
listen: "127.0.0.1:-1" |
| 494 |
leafnodes { |
| 495 |
listen: "127.0.0.1:-1" |
| 496 |
tls: { |
| 497 |
cert_file: "../test/configs/certs/server-cert.pem" |
| 498 |
key_file: "../test/configs/certs/server-key.pem" |
| 499 |
} |
| 500 |
} |
| 501 |
`)) |
| 502 |
|
| 503 |
hub, hubOpts := RunServerWithConfig(hubConfig) |
| 504 |
defer hub.Shutdown() |
| 505 |
|
| 506 |
// Create HTTP proxy |
| 507 |
proxy := createTestHTTPProxy(_EMPTY_, _EMPTY_) |
| 508 |
proxy.start() |
| 509 |
defer proxy.stop() |
| 510 |
|
| 511 |
// Create spoke server with proxy but no TLS configuration (intentional mismatch) |
| 512 |
spokeConfigContent := fmt.Sprintf(` |
| 513 |
listen: "127.0.0.1:-1" |
| 514 |
leafnodes { |
| 515 |
reconnect_interval: "50ms" |
| 516 |
remotes = [ |
| 517 |
{ |
| 518 |
url: "ws://127.0.0.1:%d" |
| 519 |
proxy { |
| 520 |
url: "%s" |
| 521 |
timeout: 5s |
| 522 |
} |
| 523 |
# Intentionally no TLS configuration to create mismatch |
| 524 |
} |
| 525 |
] |
| 526 |
} |
| 527 |
`, hubOpts.LeafNode.Port, proxy.url()) |
| 528 |
|
| 529 |
spokeConfig := createConfFile(t, []byte(spokeConfigContent)) |
| 530 |
spoke, _ := RunServerWithConfig(spokeConfig) |
| 531 |
defer spoke.Shutdown() |
| 532 |
|
| 533 |
// Wait and verify that connection was NOT established due to TLS mismatch |
| 534 |
// First attempt happens during RunServerWithConfig(), then retries every 50ms |
| 535 |
time.Sleep(250 * time.Millisecond) |
| 536 |
|
| 537 |
if spoke.NumLeafNodes() != 0 { |
| 538 |
t.Errorf("Expected 0 leafnode connections due to TLS mismatch, got %d", spoke.NumLeafNodes()) |
| 539 |
} |
| 540 |
} |
| 541 |
|
| 542 |
func TestLeafNodeHttpProxyTunnelBasic(t *testing.T) { |
| 543 |
// Create HTTP proxy with longer delay for robustness |
| 544 |
proxy := createTestHTTPProxy(_EMPTY_, _EMPTY_) |
| 545 |
proxy.setCloseDelay(200 * time.Millisecond) |
| 546 |
proxy.start() |
| 547 |
defer proxy.stop() |
| 548 |
|
| 549 |
// Create a simple TCP server to connect to through proxy |
| 550 |
listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 551 |
if err != nil { |
| 552 |
t.Fatalf("Failed to create test server: %v", err) |
| 553 |
} |
| 554 |
defer listener.Close() |
| 555 |
|
| 556 |
targetPort := listener.Addr().(*net.TCPAddr).Port |
| 557 |
targetHost := fmt.Sprintf("127.0.0.1:%d", targetPort) |
| 558 |
|
| 559 |
errCh := make(chan error, 1) |
| 560 |
|
| 561 |
// Accept one connection with proper timeout handling |
| 562 |
go func() { |
| 563 |
conn, err := listener.Accept() |
| 564 |
if err != nil { |
| 565 |
errCh <- fmt.Errorf("unable to accept: %v", err) |
| 566 |
return |
| 567 |
} |
| 568 |
defer conn.Close() |
| 569 |
|
| 570 |
// Set read deadline to prevent hanging forever |
| 571 |
conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 572 |
|
| 573 |
// Read the incoming data first |
| 574 |
buffer := make([]byte, 1024) |
| 575 |
n, err := conn.Read(buffer) |
| 576 |
if err != nil { |
| 577 |
errCh <- fmt.Errorf("server failed to read: %v", err) |
| 578 |
return |
| 579 |
} |
| 580 |
|
| 581 |
receivedMsg := string(buffer[:n]) |
| 582 |
if receivedMsg != "Hello" { |
| 583 |
errCh <- fmt.Errorf("server expected 'Hello', got '%s'", receivedMsg) |
| 584 |
return |
| 585 |
} |
| 586 |
|
| 587 |
// Send response |
| 588 |
conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) |
| 589 |
_, err = conn.Write([]byte("Hello from target server")) |
| 590 |
if err != nil { |
| 591 |
errCh <- fmt.Errorf("server failed to write: %v", err) |
| 592 |
return |
| 593 |
} |
| 594 |
|
| 595 |
// Wait a bit to ensure the client has time to read before closing |
| 596 |
time.Sleep(50 * time.Millisecond) |
| 597 |
errCh <- nil |
| 598 |
}() |
| 599 |
|
| 600 |
// Test establishing proxy tunnel with timeout |
| 601 |
conn, err := establishHTTPProxyTunnel(proxy.url(), targetHost, 10*time.Second, _EMPTY_, _EMPTY_) |
| 602 |
if err != nil { |
| 603 |
t.Fatalf("Failed to establish proxy tunnel: %v", err) |
| 604 |
} |
| 605 |
defer conn.Close() |
| 606 |
|
| 607 |
// Test that we can communicate through the tunnel with deadlines |
| 608 |
conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) |
| 609 |
_, err = conn.Write([]byte("Hello")) |
| 610 |
if err != nil { |
| 611 |
t.Fatalf("Failed to write to proxy tunnel: %v", err) |
| 612 |
} |
| 613 |
|
| 614 |
conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 615 |
buffer := make([]byte, 1024) |
| 616 |
n, err := conn.Read(buffer) |
| 617 |
if err != nil { |
| 618 |
t.Fatalf("Failed to read from proxy tunnel: %v", err) |
| 619 |
} |
| 620 |
|
| 621 |
response := string(buffer[:n]) |
| 622 |
if response != "Hello from target server" { |
| 623 |
t.Errorf("Unexpected response: '%s', expected 'Hello from target server'", response) |
| 624 |
} |
| 625 |
|
| 626 |
select { |
| 627 |
case err := <-errCh: |
| 628 |
if err != nil { |
| 629 |
t.Fatalf("%v", err) |
| 630 |
} |
| 631 |
case <-time.After(3 * time.Second): |
| 632 |
t.Fatal("Server goroutine didn't complete in time, but test data was exchanged successfully") |
| 633 |
} |
| 634 |
} |
| 635 |
|
| 636 |
func TestLeafNodeHttpProxyTunnelWithAuth(t *testing.T) { |
| 637 |
// Create HTTP proxy with authentication and delay for robustness |
| 638 |
proxy := createTestHTTPProxy("testuser", "testpass") |
| 639 |
proxy.setCloseDelay(200 * time.Millisecond) |
| 640 |
proxy.start() |
| 641 |
defer proxy.stop() |
| 642 |
|
| 643 |
// Create a simple TCP server to connect to through proxy |
| 644 |
listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 645 |
if err != nil { |
| 646 |
t.Fatalf("Failed to create test server: %v", err) |
| 647 |
} |
| 648 |
defer listener.Close() |
| 649 |
|
| 650 |
targetPort := listener.Addr().(*net.TCPAddr).Port |
| 651 |
targetHost := fmt.Sprintf("127.0.0.1:%d", targetPort) |
| 652 |
|
| 653 |
errCh := make(chan error, 1) |
| 654 |
|
| 655 |
// Accept one connection with proper timeout handling |
| 656 |
go func() { |
| 657 |
conn, err := listener.Accept() |
| 658 |
if err != nil { |
| 659 |
errCh <- fmt.Errorf("unable to accept: %v", err) |
| 660 |
return |
| 661 |
} |
| 662 |
defer conn.Close() |
| 663 |
|
| 664 |
// Set read deadline to prevent hanging |
| 665 |
conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 666 |
|
| 667 |
// Read the incoming data first |
| 668 |
buffer := make([]byte, 1024) |
| 669 |
_, err = conn.Read(buffer) |
| 670 |
if err != nil { |
| 671 |
errCh <- fmt.Errorf("unable to read: %v", err) |
| 672 |
return |
| 673 |
} |
| 674 |
|
| 675 |
// Send response |
| 676 |
conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) |
| 677 |
if _, err := conn.Write([]byte("Hello from authenticated server")); err != nil { |
| 678 |
errCh <- fmt.Errorf("unable to write: %v", err) |
| 679 |
return |
| 680 |
} |
| 681 |
|
| 682 |
errCh <- nil |
| 683 |
}() |
| 684 |
|
| 685 |
// Test establishing proxy tunnel with authentication and timeout |
| 686 |
conn, err := establishHTTPProxyTunnel(proxy.url(), targetHost, 10*time.Second, "testuser", "testpass") |
| 687 |
if err != nil { |
| 688 |
t.Fatalf("Failed to establish proxy tunnel with auth: %v", err) |
| 689 |
} |
| 690 |
defer conn.Close() |
| 691 |
|
| 692 |
// Test that we can communicate through the tunnel with deadlines |
| 693 |
conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) |
| 694 |
_, err = conn.Write([]byte("Hello")) |
| 695 |
if err != nil { |
| 696 |
t.Fatalf("Failed to write to proxy tunnel: %v", err) |
| 697 |
} |
| 698 |
|
| 699 |
conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 700 |
buffer := make([]byte, 1024) |
| 701 |
n, err := conn.Read(buffer) |
| 702 |
if err != nil { |
| 703 |
t.Fatalf("Failed to read from proxy tunnel: %v", err) |
| 704 |
} |
| 705 |
|
| 706 |
response := string(buffer[:n]) |
| 707 |
if response != "Hello from authenticated server" { |
| 708 |
t.Errorf("Unexpected response: %s", response) |
| 709 |
} |
| 710 |
|
| 711 |
select { |
| 712 |
case err := <-errCh: |
| 713 |
if err != nil { |
| 714 |
t.Fatalf("%v", err) |
| 715 |
} |
| 716 |
case <-time.After(2 * time.Second): |
| 717 |
t.Fatal("Server goroutine didn't complete in time, but test data was exchanged successfully") |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
func TestLeafNodeHttpProxyTunnelFailsWithoutAuth(t *testing.T) { |
| 722 |
// Create HTTP proxy with authentication required and delay for robustness |
| 723 |
proxy := createTestHTTPProxy("testuser", "testpass") |
| 724 |
proxy.setCloseDelay(200 * time.Millisecond) |
| 725 |
proxy.start() |
| 726 |
defer proxy.stop() |
| 727 |
|
| 728 |
// Try to establish tunnel without providing credentials (should fail quickly) |
| 729 |
_, err := establishHTTPProxyTunnel(proxy.url(), "127.0.0.1:80", 10*time.Second, _EMPTY_, _EMPTY_) |
| 730 |
if err == nil { |
| 731 |
t.Fatal("Expected error when connecting without authentication") |
| 732 |
} |
| 733 |
|
| 734 |
if !strings.Contains(err.Error(), "proxy CONNECT failed") { |
| 735 |
t.Errorf("Expected proxy authentication error, got: %v", err) |
| 736 |
} |
| 737 |
|
| 738 |
// Verify the error contains the expected HTTP response code |
| 739 |
if !strings.Contains(err.Error(), "407") { |
| 740 |
t.Errorf("Expected HTTP 407 error in response, got: %v", err) |
| 741 |
} |
| 742 |
} |
| 743 |
|
| 744 |
// TestLeafNodeProxyValidationProgrammatic tests proxy validation when configuring server programmatically |
| 745 |
func TestLeafNodeHttpProxyValidationProgrammatic(t *testing.T) { |
| 746 |
tests := []struct { |
| 747 |
// name is the name of the test. |
| 748 |
name string |
| 749 |
|
| 750 |
// setupOptions creates the Options configuration for the test. |
| 751 |
setupOptions func() *Options |
| 752 |
|
| 753 |
// err is the expected error. nil means no error expected. |
| 754 |
err error |
| 755 |
}{ |
| 756 |
{ |
| 757 |
name: "invalid proxy scheme", |
| 758 |
setupOptions: func() *Options { |
| 759 |
opts := &Options{} |
| 760 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 761 |
{ |
| 762 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 763 |
}, |
| 764 |
} |
| 765 |
opts.LeafNode.Remotes[0].Proxy.URL = "ftp://proxy.example.com:21" |
| 766 |
return opts |
| 767 |
}, |
| 768 |
err: errors.New("proxy URL scheme must be http or https"), |
| 769 |
}, |
| 770 |
{ |
| 771 |
name: "empty proxy URL - no validation performed", |
| 772 |
setupOptions: func() *Options { |
| 773 |
opts := &Options{} |
| 774 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 775 |
{ |
| 776 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 777 |
}, |
| 778 |
} |
| 779 |
opts.LeafNode.Remotes[0].Proxy.URL = _EMPTY_ |
| 780 |
return opts |
| 781 |
}, |
| 782 |
err: nil, // No error expected for empty URL |
| 783 |
}, |
| 784 |
{ |
| 785 |
name: "invalid proxy URL parse failure", |
| 786 |
setupOptions: func() *Options { |
| 787 |
opts := &Options{} |
| 788 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 789 |
{ |
| 790 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 791 |
}, |
| 792 |
} |
| 793 |
opts.LeafNode.Remotes[0].Proxy.URL = "ht!tp://invalid-url-with-bad-characters" |
| 794 |
return opts |
| 795 |
}, |
| 796 |
err: errors.New("invalid proxy URL"), |
| 797 |
}, |
| 798 |
{ |
| 799 |
name: "missing proxy host", |
| 800 |
setupOptions: func() *Options { |
| 801 |
opts := &Options{} |
| 802 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 803 |
{ |
| 804 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 805 |
}, |
| 806 |
} |
| 807 |
opts.LeafNode.Remotes[0].Proxy.URL = "http://" |
| 808 |
return opts |
| 809 |
}, |
| 810 |
err: errors.New("proxy URL must specify a host"), |
| 811 |
}, |
| 812 |
{ |
| 813 |
name: "username without password", |
| 814 |
setupOptions: func() *Options { |
| 815 |
opts := &Options{} |
| 816 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 817 |
{ |
| 818 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 819 |
}, |
| 820 |
} |
| 821 |
opts.LeafNode.Remotes[0].Proxy.URL = "http://proxy.example.com:8080" |
| 822 |
opts.LeafNode.Remotes[0].Proxy.Username = "user" |
| 823 |
return opts |
| 824 |
}, |
| 825 |
err: errors.New("proxy username and password must both be specified"), |
| 826 |
}, |
| 827 |
{ |
| 828 |
name: "password without username", |
| 829 |
setupOptions: func() *Options { |
| 830 |
opts := &Options{} |
| 831 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 832 |
{ |
| 833 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 834 |
}, |
| 835 |
} |
| 836 |
opts.LeafNode.Remotes[0].Proxy.URL = "http://proxy.example.com:8080" |
| 837 |
opts.LeafNode.Remotes[0].Proxy.Password = "pass" |
| 838 |
return opts |
| 839 |
}, |
| 840 |
err: errors.New("proxy username and password must both be specified"), |
| 841 |
}, |
| 842 |
{ |
| 843 |
name: "negative timeout value", |
| 844 |
setupOptions: func() *Options { |
| 845 |
opts := &Options{} |
| 846 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 847 |
{ |
| 848 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 849 |
}, |
| 850 |
} |
| 851 |
opts.LeafNode.Remotes[0].Proxy.URL = "http://proxy.example.com:8080" |
| 852 |
opts.LeafNode.Remotes[0].Proxy.Timeout = -5 * time.Second |
| 853 |
return opts |
| 854 |
}, |
| 855 |
err: errors.New("proxy timeout must be >= 0"), |
| 856 |
}, |
| 857 |
{ |
| 858 |
name: "zero timeout value - valid", |
| 859 |
setupOptions: func() *Options { |
| 860 |
opts := &Options{} |
| 861 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 862 |
{ |
| 863 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 864 |
}, |
| 865 |
} |
| 866 |
opts.LeafNode.Remotes[0].Proxy.URL = "http://proxy.example.com:8080" |
| 867 |
opts.LeafNode.Remotes[0].Proxy.Timeout = 0 |
| 868 |
return opts |
| 869 |
}, |
| 870 |
err: nil, // No error expected for zero timeout |
| 871 |
}, |
| 872 |
{ |
| 873 |
name: "valid proxy configuration with authentication", |
| 874 |
setupOptions: func() *Options { |
| 875 |
opts := &Options{} |
| 876 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 877 |
{ |
| 878 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 879 |
}, |
| 880 |
} |
| 881 |
opts.LeafNode.Remotes[0].Proxy.URL = "http://proxy.example.com:8080" |
| 882 |
opts.LeafNode.Remotes[0].Proxy.Username = "user" |
| 883 |
opts.LeafNode.Remotes[0].Proxy.Password = "pass" |
| 884 |
opts.LeafNode.Remotes[0].Proxy.Timeout = 10 * time.Second |
| 885 |
return opts |
| 886 |
}, |
| 887 |
err: nil, // No error expected |
| 888 |
}, |
| 889 |
{ |
| 890 |
name: "valid proxy configuration without authentication", |
| 891 |
setupOptions: func() *Options { |
| 892 |
opts := &Options{} |
| 893 |
opts.LeafNode.Remotes = []*RemoteLeafOpts{ |
| 894 |
{ |
| 895 |
URLs: []*url.URL{{Scheme: wsSchemePrefix, Host: "127.0.0.1:7422"}}, |
| 896 |
}, |
| 897 |
} |
| 898 |
opts.LeafNode.Remotes[0].Proxy.URL = "https://proxy.example.com:3128" |
| 899 |
opts.LeafNode.Remotes[0].Proxy.Timeout = 30 * time.Second |
| 900 |
return opts |
| 901 |
}, |
| 902 |
err: nil, // No error expected |
| 903 |
}, |
| 904 |
} |
| 905 |
|
| 906 |
checkErr := func(t *testing.T, err, expectedErr error) { |
| 907 |
t.Helper() |
| 908 |
switch { |
| 909 |
case err == nil && expectedErr == nil: |
| 910 |
// OK |
| 911 |
case err != nil && expectedErr == nil: |
| 912 |
t.Errorf("Unexpected error after validating options: %s", err) |
| 913 |
case err == nil && expectedErr != nil: |
| 914 |
t.Errorf("Expected %q error after validating invalid options but got nothing", expectedErr) |
| 915 |
case err != nil && expectedErr != nil: |
| 916 |
if !strings.Contains(err.Error(), expectedErr.Error()) { |
| 917 |
t.Errorf("Expected error containing %q, got: %q", expectedErr.Error(), err.Error()) |
| 918 |
} |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
for _, test := range tests { |
| 923 |
t.Run(test.name, func(t *testing.T) { |
| 924 |
opts := test.setupOptions() |
| 925 |
err := validateLeafNode(opts) |
| 926 |
checkErr(t, err, test.err) |
| 927 |
}) |
| 928 |
} |
| 929 |
} |