| 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 |
"bufio" |
| 18 |
"bytes" |
| 19 |
"crypto/tls" |
| 20 |
"crypto/x509" |
| 21 |
"encoding/binary" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"net" |
| 25 |
"os" |
| 26 |
"strings" |
| 27 |
"testing" |
| 28 |
"time" |
| 29 |
) |
| 30 |
|
| 31 |
// mockConn is a mock net.Conn for testing |
| 32 |
type mockConn struct { |
| 33 |
net.Conn |
| 34 |
readBuf *bytes.Buffer |
| 35 |
writeBuf *bytes.Buffer |
| 36 |
closed bool |
| 37 |
deadline time.Time |
| 38 |
} |
| 39 |
|
| 40 |
func newMockConn(data []byte) *mockConn { |
| 41 |
return &mockConn{ |
| 42 |
readBuf: bytes.NewBuffer(data), |
| 43 |
writeBuf: &bytes.Buffer{}, |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
func (m *mockConn) Read(b []byte) (int, error) { |
| 48 |
if m.closed { |
| 49 |
return 0, fmt.Errorf("connection closed") |
| 50 |
} |
| 51 |
if !m.deadline.IsZero() && time.Now().After(m.deadline) { |
| 52 |
return 0, &net.OpError{Op: "read", Err: fmt.Errorf("timeout")} |
| 53 |
} |
| 54 |
return m.readBuf.Read(b) |
| 55 |
} |
| 56 |
|
| 57 |
func (m *mockConn) Write(b []byte) (int, error) { |
| 58 |
if m.closed { |
| 59 |
return 0, fmt.Errorf("connection closed") |
| 60 |
} |
| 61 |
return m.writeBuf.Write(b) |
| 62 |
} |
| 63 |
|
| 64 |
func (m *mockConn) Close() error { |
| 65 |
m.closed = true |
| 66 |
return nil |
| 67 |
} |
| 68 |
|
| 69 |
func (m *mockConn) LocalAddr() net.Addr { |
| 70 |
return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 4222} |
| 71 |
} |
| 72 |
|
| 73 |
func (m *mockConn) RemoteAddr() net.Addr { |
| 74 |
return &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 54321} |
| 75 |
} |
| 76 |
|
| 77 |
func (m *mockConn) SetDeadline(t time.Time) error { |
| 78 |
m.deadline = t |
| 79 |
return nil |
| 80 |
} |
| 81 |
|
| 82 |
func (m *mockConn) SetReadDeadline(t time.Time) error { |
| 83 |
m.deadline = t |
| 84 |
return nil |
| 85 |
} |
| 86 |
|
| 87 |
func (m *mockConn) SetWriteDeadline(t time.Time) error { |
| 88 |
return nil |
| 89 |
} |
| 90 |
|
| 91 |
// buildProxyV2Header builds a valid PROXY protocol v2 header |
| 92 |
func buildProxyV2Header(t *testing.T, srcIP, dstIP string, srcPort, dstPort uint16, family byte) []byte { |
| 93 |
t.Helper() |
| 94 |
|
| 95 |
buf := &bytes.Buffer{} |
| 96 |
buf.WriteString(proxyProtoV2Sig) // Write signature |
| 97 |
buf.WriteByte(proxyProtoV2Ver | proxyProtoCmdProxy) // Write version and command (version 2, PROXY command) |
| 98 |
buf.WriteByte(family | proxyProtoProtoStream) // Write family and protocol |
| 99 |
|
| 100 |
src := net.ParseIP(srcIP) |
| 101 |
dst := net.ParseIP(dstIP) |
| 102 |
var addrData []byte |
| 103 |
switch family { |
| 104 |
case proxyProtoFamilyInet: |
| 105 |
// IPv4: 12 bytes |
| 106 |
addrData = make([]byte, proxyProtoAddrSizeIPv4) |
| 107 |
copy(addrData[0:4], src.To4()) |
| 108 |
copy(addrData[4:8], dst.To4()) |
| 109 |
binary.BigEndian.PutUint16(addrData[8:10], srcPort) |
| 110 |
binary.BigEndian.PutUint16(addrData[10:12], dstPort) |
| 111 |
case proxyProtoFamilyInet6: |
| 112 |
// IPv6: 36 bytes |
| 113 |
addrData = make([]byte, proxyProtoAddrSizeIPv6) |
| 114 |
copy(addrData[0:16], src.To16()) |
| 115 |
copy(addrData[16:32], dst.To16()) |
| 116 |
binary.BigEndian.PutUint16(addrData[32:34], srcPort) |
| 117 |
binary.BigEndian.PutUint16(addrData[34:36], dstPort) |
| 118 |
default: |
| 119 |
t.Fatalf("unsupported address family: %d", family) |
| 120 |
} |
| 121 |
|
| 122 |
addrLen := make([]byte, 2) |
| 123 |
binary.BigEndian.PutUint16(addrLen, uint16(len(addrData))) |
| 124 |
buf.Write(addrLen) |
| 125 |
buf.Write(addrData) |
| 126 |
|
| 127 |
return buf.Bytes() |
| 128 |
} |
| 129 |
|
| 130 |
// buildProxyV2LocalHeader builds a PROXY protocol v2 LOCAL command header |
| 131 |
func buildProxyV2LocalHeader() []byte { |
| 132 |
buf := &bytes.Buffer{} |
| 133 |
buf.WriteString(proxyProtoV2Sig) // // Write signature |
| 134 |
buf.WriteByte(proxyProtoV2Ver | proxyProtoCmdLocal) // // Write version and command (version 2, LOCAL command) |
| 135 |
buf.WriteByte(proxyProtoFamilyUnspec | proxyProtoProtoUnspec) // // Write family and protocol (UNSPEC) |
| 136 |
buf.WriteByte(0) |
| 137 |
buf.WriteByte(0) |
| 138 |
return buf.Bytes() |
| 139 |
} |
| 140 |
|
| 141 |
// buildProxyV1Header builds a valid PROXY protocol v1 header (text format) |
| 142 |
func buildProxyV1Header(t *testing.T, protocol, srcIP, dstIP string, srcPort, dstPort uint16) []byte { |
| 143 |
t.Helper() |
| 144 |
|
| 145 |
if protocol != "TCP4" && protocol != "TCP6" && protocol != "UNKNOWN" { |
| 146 |
t.Fatalf("invalid protocol: %s", protocol) |
| 147 |
} |
| 148 |
|
| 149 |
var line string |
| 150 |
if protocol == "UNKNOWN" { |
| 151 |
line = "PROXY UNKNOWN\r\n" |
| 152 |
} else { |
| 153 |
line = fmt.Sprintf("PROXY %s %s %s %d %d\r\n", protocol, srcIP, dstIP, srcPort, dstPort) |
| 154 |
} |
| 155 |
|
| 156 |
return []byte(line) |
| 157 |
} |
| 158 |
|
| 159 |
func TestClientProxyProtoV2ParseIPv4(t *testing.T) { |
| 160 |
header := buildProxyV2Header(t, "192.168.1.50", "10.0.0.1", 12345, 4222, proxyProtoFamilyInet) |
| 161 |
conn := newMockConn(header) |
| 162 |
|
| 163 |
addr, err := readProxyProtoV2Header(conn) |
| 164 |
require_NoError(t, err) |
| 165 |
require_NotNil(t, addr) |
| 166 |
|
| 167 |
require_Equal(t, addr.srcIP.String(), "192.168.1.50") |
| 168 |
require_Equal(t, addr.srcPort, 12345) |
| 169 |
|
| 170 |
require_Equal(t, addr.dstIP.String(), "10.0.0.1") |
| 171 |
require_Equal(t, addr.dstPort, 4222) |
| 172 |
|
| 173 |
// Test String() and Network() methods |
| 174 |
require_Equal(t, addr.String(), "192.168.1.50:12345") |
| 175 |
require_Equal(t, addr.Network(), "tcp4") |
| 176 |
} |
| 177 |
|
| 178 |
func TestClientProxyProtoV2ParseIPv6(t *testing.T) { |
| 179 |
header := buildProxyV2Header(t, "2001:db8::1", "2001:db8::2", 54321, 4222, proxyProtoFamilyInet6) |
| 180 |
conn := newMockConn(header) |
| 181 |
|
| 182 |
addr, err := readProxyProtoV2Header(conn) |
| 183 |
require_NoError(t, err) |
| 184 |
require_NotNil(t, addr) |
| 185 |
|
| 186 |
require_Equal(t, addr.srcIP.String(), "2001:db8::1") |
| 187 |
require_Equal(t, addr.srcPort, 54321) |
| 188 |
|
| 189 |
require_Equal(t, addr.dstIP.String(), "2001:db8::2") |
| 190 |
require_Equal(t, addr.dstPort, 4222) |
| 191 |
|
| 192 |
// Test Network() method for IPv6 |
| 193 |
require_Equal(t, addr.String(), "[2001:db8::1]:54321") |
| 194 |
require_Equal(t, addr.Network(), "tcp6") |
| 195 |
} |
| 196 |
|
| 197 |
func TestClientProxyProtoV2ParseLocalCommand(t *testing.T) { |
| 198 |
header := buildProxyV2LocalHeader() |
| 199 |
conn := newMockConn(header) |
| 200 |
|
| 201 |
addr, err := readProxyProtoV2Header(conn) |
| 202 |
require_NoError(t, err) |
| 203 |
require_True(t, addr == nil) |
| 204 |
} |
| 205 |
|
| 206 |
func TestClientProxyProtoV2InvalidSignature(t *testing.T) { |
| 207 |
// Create invalid signature |
| 208 |
header := []byte("INVALID_SIG_") |
| 209 |
header = append(header, []byte{0x20, 0x11, 0x00, 0x0C}...) |
| 210 |
conn := newMockConn(header) |
| 211 |
|
| 212 |
_, err := readProxyProtoV2Header(conn) |
| 213 |
require_Error(t, err, errProxyProtoInvalid) |
| 214 |
} |
| 215 |
|
| 216 |
func TestClientProxyProtoV2InvalidVersion(t *testing.T) { |
| 217 |
buf := &bytes.Buffer{} |
| 218 |
buf.WriteString(proxyProtoV2Sig) |
| 219 |
buf.WriteByte(0x10 | proxyProtoCmdProxy) // Version 1 instead of 2 |
| 220 |
buf.WriteByte(proxyProtoFamilyInet | proxyProtoProtoStream) |
| 221 |
buf.WriteByte(0) |
| 222 |
buf.WriteByte(0) |
| 223 |
|
| 224 |
conn := newMockConn(buf.Bytes()) |
| 225 |
|
| 226 |
_, err := readProxyProtoV2Header(conn) |
| 227 |
require_Error(t, err, errProxyProtoInvalid) |
| 228 |
} |
| 229 |
|
| 230 |
func TestClientProxyProtoV2UnsupportedFamily(t *testing.T) { |
| 231 |
buf := &bytes.Buffer{} |
| 232 |
buf.WriteString(proxyProtoV2Sig) |
| 233 |
buf.WriteByte(proxyProtoV2Ver | proxyProtoCmdProxy) |
| 234 |
buf.WriteByte(proxyProtoFamilyUnix | proxyProtoProtoStream) // Unix socket family |
| 235 |
buf.WriteByte(0) |
| 236 |
buf.WriteByte(0) |
| 237 |
|
| 238 |
conn := newMockConn(buf.Bytes()) |
| 239 |
|
| 240 |
_, err := readProxyProtoV2Header(conn) |
| 241 |
require_Error(t, err, errProxyProtoUnsupported) |
| 242 |
} |
| 243 |
|
| 244 |
func TestClientProxyProtoV2UnsupportedProtocol(t *testing.T) { |
| 245 |
buf := &bytes.Buffer{} |
| 246 |
buf.WriteString(proxyProtoV2Sig) |
| 247 |
buf.WriteByte(proxyProtoV2Ver | proxyProtoCmdProxy) |
| 248 |
buf.WriteByte(proxyProtoFamilyInet | proxyProtoProtoDatagram) // UDP instead of TCP |
| 249 |
buf.WriteByte(0) |
| 250 |
buf.WriteByte(12) |
| 251 |
|
| 252 |
conn := newMockConn(buf.Bytes()) |
| 253 |
|
| 254 |
_, err := readProxyProtoV2Header(conn) |
| 255 |
require_Error(t, err, errProxyProtoUnsupported) |
| 256 |
} |
| 257 |
|
| 258 |
func TestClientProxyProtoV2TruncatedHeader(t *testing.T) { |
| 259 |
header := buildProxyV2Header(t, "192.168.1.50", "10.0.0.1", 12345, 4222, proxyProtoFamilyInet) |
| 260 |
// Only send first 10 bytes (incomplete header) |
| 261 |
conn := newMockConn(header[:10]) |
| 262 |
|
| 263 |
_, err := readProxyProtoV2Header(conn) |
| 264 |
require_Error(t, err, io.ErrUnexpectedEOF) |
| 265 |
} |
| 266 |
|
| 267 |
func TestClientProxyProtoV2ShortAddressData(t *testing.T) { |
| 268 |
buf := &bytes.Buffer{} |
| 269 |
buf.WriteString(proxyProtoV2Sig) |
| 270 |
buf.WriteByte(proxyProtoV2Ver | proxyProtoCmdProxy) |
| 271 |
buf.WriteByte(proxyProtoFamilyInet | proxyProtoProtoStream) |
| 272 |
// Set address length to 12 but don't provide data |
| 273 |
buf.WriteByte(0) |
| 274 |
buf.WriteByte(12) |
| 275 |
// Only provide 5 bytes instead of 12 |
| 276 |
buf.Write([]byte{1, 2, 3, 4, 5}) |
| 277 |
|
| 278 |
conn := newMockConn(buf.Bytes()) |
| 279 |
|
| 280 |
_, err := readProxyProtoV2Header(conn) |
| 281 |
require_Error(t, err, io.ErrUnexpectedEOF) |
| 282 |
} |
| 283 |
|
| 284 |
func TestProxyConnRemoteAddr(t *testing.T) { |
| 285 |
// Create a real TCP connection for testing |
| 286 |
originalAddr := &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 54321} |
| 287 |
|
| 288 |
// Create proxy address |
| 289 |
proxyAddr := &proxyProtoAddr{ |
| 290 |
srcIP: net.ParseIP("10.0.0.50"), |
| 291 |
srcPort: 12345, |
| 292 |
dstIP: net.ParseIP("10.0.0.1"), |
| 293 |
dstPort: 4222, |
| 294 |
} |
| 295 |
|
| 296 |
mockConn := newMockConn(nil) |
| 297 |
wrapped := &proxyConn{ |
| 298 |
Conn: mockConn, |
| 299 |
remoteAddr: proxyAddr, |
| 300 |
} |
| 301 |
|
| 302 |
// Verify RemoteAddr returns the proxied address |
| 303 |
addr := wrapped.RemoteAddr() |
| 304 |
require_Equal(t, addr.String(), "10.0.0.50:12345") |
| 305 |
require_Equal(t, mockConn.RemoteAddr().String(), originalAddr.String()) |
| 306 |
} |
| 307 |
|
| 308 |
func TestClientProxyProtoV2EndToEnd(t *testing.T) { |
| 309 |
// Start a test server with PROXY protocol enabled |
| 310 |
opts := DefaultOptions() |
| 311 |
opts.Port = -1 // Random port |
| 312 |
opts.ProxyProtocol = true |
| 313 |
|
| 314 |
s := RunServer(opts) |
| 315 |
defer s.Shutdown() |
| 316 |
|
| 317 |
// Get the server's listening port |
| 318 |
addr := s.Addr().String() |
| 319 |
|
| 320 |
// Connect to the server |
| 321 |
conn, err := net.Dial("tcp", addr) |
| 322 |
require_NoError(t, err) |
| 323 |
defer conn.Close() |
| 324 |
|
| 325 |
// Send PROXY protocol header |
| 326 |
clientIP := "203.0.113.50" |
| 327 |
clientPort := uint16(54321) |
| 328 |
header := buildProxyV2Header(t, clientIP, "127.0.0.1", clientPort, 4222, proxyProtoFamilyInet) |
| 329 |
|
| 330 |
_, err = conn.Write(header) |
| 331 |
require_NoError(t, err) |
| 332 |
|
| 333 |
// Send CONNECT message |
| 334 |
connectMsg := "CONNECT {\"verbose\":false,\"pedantic\":false,\"protocol\":1}\r\n" |
| 335 |
_, err = conn.Write([]byte(connectMsg)) |
| 336 |
require_NoError(t, err) |
| 337 |
|
| 338 |
// Read INFO and +OK |
| 339 |
buf := make([]byte, 4096) |
| 340 |
n, err := conn.Read(buf) |
| 341 |
require_NoError(t, err) |
| 342 |
|
| 343 |
response := string(buf[:n]) |
| 344 |
require_True(t, strings.Contains(response, "INFO")) |
| 345 |
|
| 346 |
// Give server time to process |
| 347 |
time.Sleep(100 * time.Millisecond) |
| 348 |
|
| 349 |
// Check server's client list to verify the IP was extracted correctly |
| 350 |
s.mu.Lock() |
| 351 |
clients := s.clients |
| 352 |
s.mu.Unlock() |
| 353 |
require_True(t, len(clients) != 0) |
| 354 |
|
| 355 |
// Find our client |
| 356 |
var foundClient *client |
| 357 |
for _, c := range clients { |
| 358 |
c.mu.Lock() |
| 359 |
if c.host == clientIP && c.port == clientPort { |
| 360 |
foundClient = c |
| 361 |
} |
| 362 |
c.mu.Unlock() |
| 363 |
if foundClient != nil { |
| 364 |
break |
| 365 |
} |
| 366 |
} |
| 367 |
require_NotNil(t, foundClient) |
| 368 |
} |
| 369 |
|
| 370 |
func TestClientProxyProtoV2LocalCommandEndToEnd(t *testing.T) { |
| 371 |
// Start a test server with PROXY protocol enabled |
| 372 |
opts := DefaultOptions() |
| 373 |
opts.Port = -1 // Random port |
| 374 |
opts.ProxyProtocol = true |
| 375 |
|
| 376 |
s := RunServer(opts) |
| 377 |
defer s.Shutdown() |
| 378 |
|
| 379 |
// Get the server's listening port |
| 380 |
addr := s.Addr().String() |
| 381 |
|
| 382 |
// Connect to the server |
| 383 |
conn, err := net.Dial("tcp", addr) |
| 384 |
require_NoError(t, err) |
| 385 |
defer conn.Close() |
| 386 |
|
| 387 |
// Send PROXY protocol LOCAL header (health check) |
| 388 |
header := buildProxyV2LocalHeader() |
| 389 |
|
| 390 |
_, err = conn.Write(header) |
| 391 |
require_NoError(t, err) |
| 392 |
|
| 393 |
// Send CONNECT message |
| 394 |
connectMsg := "CONNECT {\"verbose\":false,\"pedantic\":false,\"protocol\":1}\r\n" |
| 395 |
_, err = conn.Write([]byte(connectMsg)) |
| 396 |
require_NoError(t, err) |
| 397 |
|
| 398 |
// Read INFO and +OK |
| 399 |
buf := make([]byte, 4096) |
| 400 |
n, err := conn.Read(buf) |
| 401 |
require_NoError(t, err) |
| 402 |
|
| 403 |
response := string(buf[:n]) |
| 404 |
require_True(t, strings.Contains(response, "INFO")) |
| 405 |
|
| 406 |
// Connection should work normally with LOCAL command |
| 407 |
time.Sleep(100 * time.Millisecond) |
| 408 |
|
| 409 |
// Verify at least one client is connected |
| 410 |
s.mu.Lock() |
| 411 |
numClients := len(s.clients) |
| 412 |
s.mu.Unlock() |
| 413 |
require_NotEqual(t, numClients, 0) |
| 414 |
} |
| 415 |
|
| 416 |
// ============================================================================ |
| 417 |
// PROXY Protocol v1 Tests |
| 418 |
// ============================================================================ |
| 419 |
|
| 420 |
func TestClientProxyProtoV1ParseTCP4(t *testing.T) { |
| 421 |
header := buildProxyV1Header(t, "TCP4", "192.168.1.50", "10.0.0.1", 12345, 4222) |
| 422 |
conn := newMockConn(header) |
| 423 |
|
| 424 |
addr, _, err := readProxyProtoHeader(conn) |
| 425 |
require_NoError(t, err) |
| 426 |
require_NotNil(t, addr) |
| 427 |
|
| 428 |
require_Equal(t, addr.srcIP.String(), "192.168.1.50") |
| 429 |
require_Equal(t, addr.srcPort, 12345) |
| 430 |
|
| 431 |
require_Equal(t, addr.dstIP.String(), "10.0.0.1") |
| 432 |
require_Equal(t, addr.dstPort, 4222) |
| 433 |
} |
| 434 |
|
| 435 |
func TestClientProxyProtoV1ParseTCP6(t *testing.T) { |
| 436 |
header := buildProxyV1Header(t, "TCP6", "2001:db8::1", "2001:db8::2", 54321, 4222) |
| 437 |
conn := newMockConn(header) |
| 438 |
|
| 439 |
addr, _, err := readProxyProtoHeader(conn) |
| 440 |
require_NoError(t, err) |
| 441 |
require_NotNil(t, addr) |
| 442 |
|
| 443 |
require_Equal(t, addr.srcIP.String(), "2001:db8::1") |
| 444 |
require_Equal(t, addr.srcPort, 54321) |
| 445 |
|
| 446 |
require_Equal(t, addr.dstIP.String(), "2001:db8::2") |
| 447 |
require_Equal(t, addr.dstPort, 4222) |
| 448 |
} |
| 449 |
|
| 450 |
func TestClientProxyProtoV1ParseTCP6IPv4Mapped(t *testing.T) { |
| 451 |
// Dual-stack proxies can emit IPv4-mapped IPv6 addresses for TCP6 |
| 452 |
// (an IPv4 client connecting to an IPv6 socket). These are valid IPv6 |
| 453 |
// textual addresses and must be accepted, matching the v2 parser. |
| 454 |
header := buildProxyV1Header(t, "TCP6", "::ffff:192.0.2.1", "::ffff:10.0.0.1", 1234, 4222) |
| 455 |
conn := newMockConn(header) |
| 456 |
|
| 457 |
addr, _, err := readProxyProtoHeader(conn) |
| 458 |
require_NoError(t, err) |
| 459 |
require_NotNil(t, addr) |
| 460 |
|
| 461 |
require_Equal(t, addr.srcIP.String(), "192.0.2.1") |
| 462 |
require_Equal(t, addr.srcPort, 1234) |
| 463 |
|
| 464 |
require_Equal(t, addr.dstIP.String(), "10.0.0.1") |
| 465 |
require_Equal(t, addr.dstPort, 4222) |
| 466 |
} |
| 467 |
|
| 468 |
func TestClientProxyProtoV1MismatchedDestProtocol(t *testing.T) { |
| 469 |
// TCP4 with IPv6 destination address |
| 470 |
header := buildProxyV1Header(t, "TCP4", "192.168.1.1", "2001:db8::2", 12345, 443) |
| 471 |
conn := newMockConn(header) |
| 472 |
|
| 473 |
_, _, err := readProxyProtoHeader(conn) |
| 474 |
require_Error(t, err, errProxyProtoInvalid) |
| 475 |
|
| 476 |
// TCP6 with IPv4 destination address |
| 477 |
header2 := buildProxyV1Header(t, "TCP6", "2001:db8::1", "10.0.0.1", 12345, 443) |
| 478 |
conn2 := newMockConn(header2) |
| 479 |
|
| 480 |
_, _, err = readProxyProtoHeader(conn2) |
| 481 |
require_Error(t, err, errProxyProtoInvalid) |
| 482 |
} |
| 483 |
|
| 484 |
func TestClientProxyProtoV1ParseUnknown(t *testing.T) { |
| 485 |
header := buildProxyV1Header(t, "UNKNOWN", "", "", 0, 0) |
| 486 |
conn := newMockConn(header) |
| 487 |
|
| 488 |
addr, _, err := readProxyProtoHeader(conn) |
| 489 |
require_NoError(t, err) |
| 490 |
require_True(t, addr == nil) |
| 491 |
} |
| 492 |
|
| 493 |
func TestClientProxyProtoV1PreservesCoalescedClientBytes(t *testing.T) { |
| 494 |
header := buildProxyV1Header(t, "TCP4", "192.168.1.50", "10.0.0.1", 12345, 4222) |
| 495 |
connect := []byte("CONNECT {\"verbose\":false,\"pedantic\":false,\"protocol\":1}\r\n") |
| 496 |
conn := newMockConn(append(header, connect...)) |
| 497 |
|
| 498 |
addr, remaining, err := readProxyProtoHeader(conn) |
| 499 |
require_NoError(t, err) |
| 500 |
require_NotNil(t, addr) |
| 501 |
require_Equal(t, string(remaining), string(connect)) |
| 502 |
|
| 503 |
rest, err := io.ReadAll(conn) |
| 504 |
require_NoError(t, err) |
| 505 |
require_Equal(t, len(rest), 0) |
| 506 |
} |
| 507 |
|
| 508 |
func TestClientProxyProtoV1InvalidFormat(t *testing.T) { |
| 509 |
// Missing fields |
| 510 |
header := []byte("PROXY TCP4 192.168.1.1\r\n") |
| 511 |
conn := newMockConn(header) |
| 512 |
|
| 513 |
_, _, err := readProxyProtoHeader(conn) |
| 514 |
require_Error(t, err, errProxyProtoInvalid) |
| 515 |
} |
| 516 |
|
| 517 |
func TestClientProxyProtoV1LineTooLong(t *testing.T) { |
| 518 |
// Create a line longer than 107 bytes |
| 519 |
longIP := strings.Repeat("1234567890", 12) // 120 chars |
| 520 |
header := fmt.Appendf(nil, "PROXY TCP4 %s 10.0.0.1 12345 443\r\n", longIP) |
| 521 |
conn := newMockConn(header) |
| 522 |
|
| 523 |
_, _, err := readProxyProtoHeader(conn) |
| 524 |
require_Error(t, err, errProxyProtoInvalid) |
| 525 |
} |
| 526 |
|
| 527 |
func TestClientProxyProtoV1InvalidIP(t *testing.T) { |
| 528 |
header := []byte("PROXY TCP4 not.an.ip.addr 10.0.0.1 12345 443\r\n") |
| 529 |
conn := newMockConn(header) |
| 530 |
|
| 531 |
_, _, err := readProxyProtoHeader(conn) |
| 532 |
require_Error(t, err, errProxyProtoInvalid) |
| 533 |
} |
| 534 |
|
| 535 |
func TestClientProxyProtoV1MismatchedProtocol(t *testing.T) { |
| 536 |
// TCP4 with IPv6 address |
| 537 |
header := buildProxyV1Header(t, "TCP4", "2001:db8::1", "2001:db8::2", 12345, 443) |
| 538 |
conn := newMockConn(header) |
| 539 |
|
| 540 |
_, _, err := readProxyProtoHeader(conn) |
| 541 |
require_Error(t, err, errProxyProtoInvalid) |
| 542 |
|
| 543 |
// TCP6 with IPv4 address |
| 544 |
header2 := buildProxyV1Header(t, "TCP6", "192.168.1.1", "10.0.0.1", 12345, 443) |
| 545 |
conn2 := newMockConn(header2) |
| 546 |
|
| 547 |
_, _, err = readProxyProtoHeader(conn2) |
| 548 |
require_Error(t, err, errProxyProtoInvalid) |
| 549 |
} |
| 550 |
|
| 551 |
func TestClientProxyProtoV1InvalidPort(t *testing.T) { |
| 552 |
header := []byte("PROXY TCP4 192.168.1.1 10.0.0.1 99999 443\r\n") |
| 553 |
conn := newMockConn(header) |
| 554 |
|
| 555 |
_, _, err := readProxyProtoHeader(conn) |
| 556 |
require_True(t, err != nil) |
| 557 |
} |
| 558 |
|
| 559 |
func TestClientProxyProtoV1EndToEnd(t *testing.T) { |
| 560 |
// Start a test server with PROXY protocol enabled |
| 561 |
opts := DefaultOptions() |
| 562 |
opts.Port = -1 // Random port |
| 563 |
opts.ProxyProtocol = true |
| 564 |
|
| 565 |
s := RunServer(opts) |
| 566 |
defer s.Shutdown() |
| 567 |
|
| 568 |
// Get the server's listening port |
| 569 |
addr := s.Addr().String() |
| 570 |
|
| 571 |
// Connect to the server |
| 572 |
conn, err := net.Dial("tcp", addr) |
| 573 |
require_NoError(t, err) |
| 574 |
defer conn.Close() |
| 575 |
|
| 576 |
// Send the PROXY protocol header and first client commands in one write so |
| 577 |
// the parser must preserve bytes read past the end of the v1 header. |
| 578 |
clientIP, clientPort := "203.0.113.50", uint16(54321) |
| 579 |
header := buildProxyV1Header(t, "TCP4", clientIP, "127.0.0.1", clientPort, 4222) |
| 580 |
payload := append(header, []byte("CONNECT {\"verbose\":true,\"pedantic\":false,\"protocol\":1}\r\nPING\r\n")...) |
| 581 |
|
| 582 |
_, err = conn.Write(payload) |
| 583 |
require_NoError(t, err) |
| 584 |
|
| 585 |
require_NoError(t, conn.SetReadDeadline(time.Now().Add(2*time.Second))) |
| 586 |
cr := bufio.NewReader(conn) |
| 587 |
|
| 588 |
line, err := cr.ReadString('\n') |
| 589 |
require_NoError(t, err) |
| 590 |
require_True(t, strings.HasPrefix(line, "INFO ")) |
| 591 |
|
| 592 |
line, err = cr.ReadString('\n') |
| 593 |
require_NoError(t, err) |
| 594 |
require_True(t, strings.HasPrefix(line, "+OK")) |
| 595 |
|
| 596 |
expectPong(t, cr) |
| 597 |
|
| 598 |
// Give server time to process |
| 599 |
time.Sleep(100 * time.Millisecond) |
| 600 |
|
| 601 |
// Check server's client list to verify the IP was extracted correctly |
| 602 |
s.mu.Lock() |
| 603 |
clients := s.clients |
| 604 |
var foundClient *client |
| 605 |
for _, c := range clients { |
| 606 |
c.mu.Lock() |
| 607 |
if c.host == clientIP && c.port == clientPort { |
| 608 |
foundClient = c |
| 609 |
} |
| 610 |
c.mu.Unlock() |
| 611 |
if foundClient != nil { |
| 612 |
break |
| 613 |
} |
| 614 |
} |
| 615 |
s.mu.Unlock() |
| 616 |
require_NotNil(t, foundClient) |
| 617 |
} |
| 618 |
|
| 619 |
// ============================================================================ |
| 620 |
// Mixed Protocol Version Tests |
| 621 |
// ============================================================================ |
| 622 |
|
| 623 |
func TestClientProxyProtoVersionDetection(t *testing.T) { |
| 624 |
// Test v1 detection |
| 625 |
v1Header := buildProxyV1Header(t, "TCP4", "192.168.1.1", "10.0.0.1", 12345, 443) |
| 626 |
conn1 := newMockConn(v1Header) |
| 627 |
|
| 628 |
addr1, _, err := readProxyProtoHeader(conn1) |
| 629 |
require_NoError(t, err) |
| 630 |
require_NotNil(t, addr1) |
| 631 |
require_Equal(t, addr1.srcIP.String(), "192.168.1.1") |
| 632 |
|
| 633 |
// Test v2 detection |
| 634 |
v2Header := buildProxyV2Header(t, "192.168.1.2", "10.0.0.1", 54321, 443, proxyProtoFamilyInet) |
| 635 |
conn2 := newMockConn(v2Header) |
| 636 |
|
| 637 |
addr2, _, err := readProxyProtoHeader(conn2) |
| 638 |
require_NoError(t, err) |
| 639 |
require_NotNil(t, addr2) |
| 640 |
require_Equal(t, addr2.srcIP.String(), "192.168.1.2") |
| 641 |
} |
| 642 |
|
| 643 |
func TestClientProxyProtoUnrecognizedVersion(t *testing.T) { |
| 644 |
// Invalid header that doesn't match v1 or v2 |
| 645 |
header := []byte("HELLO WORLD\r\n") |
| 646 |
conn := newMockConn(header) |
| 647 |
|
| 648 |
_, _, err := readProxyProtoHeader(conn) |
| 649 |
require_Error(t, err, errProxyProtoUnrecognized) |
| 650 |
} |
| 651 |
|
| 652 |
// ============================================================================ |
| 653 |
// PROXY Protocol + TLS Tests (regression for issue #7571) |
| 654 |
// ============================================================================ |
| 655 |
|
| 656 |
// runProxyProtoTLSServer starts a server with proxy_protocol and a required |
| 657 |
// TLS listener (no allow_non_tls, no tls_first). |
| 658 |
func runProxyProtoTLSServer(t *testing.T) *Server { |
| 659 |
t.Helper() |
| 660 |
tc := &TLSConfigOpts{ |
| 661 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 662 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 663 |
CaFile: "../test/configs/certs/ca.pem", |
| 664 |
} |
| 665 |
tlsConfig, err := GenTLSConfig(tc) |
| 666 |
require_NoError(t, err) |
| 667 |
|
| 668 |
opts := DefaultOptions() |
| 669 |
opts.Port = -1 |
| 670 |
opts.ProxyProtocol = true |
| 671 |
opts.TLSConfig = tlsConfig |
| 672 |
opts.TLSTimeout = 2 |
| 673 |
return RunServer(opts) |
| 674 |
} |
| 675 |
|
| 676 |
// proxyProtoTLSClientConfig builds a tls.Config trusting the test CA. The |
| 677 |
// server cert is issued for "localhost" / 127.0.0.1, so ServerName must match. |
| 678 |
func proxyProtoTLSClientConfig(t *testing.T) *tls.Config { |
| 679 |
t.Helper() |
| 680 |
caPEM, err := os.ReadFile("../test/configs/certs/ca.pem") |
| 681 |
require_NoError(t, err) |
| 682 |
pool := x509.NewCertPool() |
| 683 |
require_True(t, pool.AppendCertsFromPEM(caPEM)) |
| 684 |
return &tls.Config{ |
| 685 |
RootCAs: pool, |
| 686 |
ServerName: "localhost", |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
// findProxyProtoClient finds a connected client whose host/port matches what |
| 691 |
// was advertised in the PROXY header. |
| 692 |
func findProxyProtoClient(t *testing.T, s *Server, clientIP string, clientPort uint16) *client { |
| 693 |
t.Helper() |
| 694 |
s.mu.Lock() |
| 695 |
clients := make([]*client, 0, len(s.clients)) |
| 696 |
for _, c := range s.clients { |
| 697 |
clients = append(clients, c) |
| 698 |
} |
| 699 |
s.mu.Unlock() |
| 700 |
|
| 701 |
for _, c := range clients { |
| 702 |
c.mu.Lock() |
| 703 |
host, port := c.host, c.port |
| 704 |
c.mu.Unlock() |
| 705 |
if host == clientIP && port == clientPort { |
| 706 |
return c |
| 707 |
} |
| 708 |
} |
| 709 |
return nil |
| 710 |
} |
| 711 |
|
| 712 |
// connectProxyProtoTLS mirrors what an L4 proxy and a TLS-enabled NATS client |
| 713 |
// do over a single TCP connection: prepend the PROXY header, read the initial |
| 714 |
// plaintext INFO, then upgrade to TLS. Returns the buffered reader and the |
| 715 |
// TLS-wrapped connection for subsequent protocol writes. |
| 716 |
func connectProxyProtoTLS(t *testing.T, addr string, header []byte) (*bufio.Reader, *tls.Conn) { |
| 717 |
t.Helper() |
| 718 |
rawConn, err := net.Dial("tcp", addr) |
| 719 |
require_NoError(t, err) |
| 720 |
require_NoError(t, rawConn.SetDeadline(time.Now().Add(5*time.Second))) |
| 721 |
|
| 722 |
_, err = rawConn.Write(header) |
| 723 |
require_NoError(t, err) |
| 724 |
|
| 725 |
// Server emits INFO over plaintext before the TLS upgrade. Read it now |
| 726 |
// so the bytes don't end up as input to the TLS handshake. |
| 727 |
plainReader := bufio.NewReader(rawConn) |
| 728 |
infoLine, err := plainReader.ReadString('\n') |
| 729 |
require_NoError(t, err) |
| 730 |
require_True(t, strings.HasPrefix(infoLine, "INFO ")) |
| 731 |
require_Equal(t, plainReader.Buffered(), 0) |
| 732 |
|
| 733 |
tlsConn := tls.Client(rawConn, proxyProtoTLSClientConfig(t)) |
| 734 |
require_NoError(t, tlsConn.Handshake()) |
| 735 |
return bufio.NewReader(tlsConn), tlsConn |
| 736 |
} |
| 737 |
|
| 738 |
// TestClientProxyProtoV1WithRequiredTLS verifies that with proxy_protocol and |
| 739 |
// required TLS, a client may send the PROXY v1 header followed by the TLS |
| 740 |
// upgrade on a single TCP connection. Regression for issue #7571. |
| 741 |
func TestClientProxyProtoV1WithRequiredTLS(t *testing.T) { |
| 742 |
s := runProxyProtoTLSServer(t) |
| 743 |
defer s.Shutdown() |
| 744 |
|
| 745 |
clientIP, clientPort := "203.0.113.50", uint16(54321) |
| 746 |
header := buildProxyV1Header(t, "TCP4", clientIP, "127.0.0.1", clientPort, 4222) |
| 747 |
cr, tlsConn := connectProxyProtoTLS(t, s.Addr().String(), header) |
| 748 |
defer tlsConn.Close() |
| 749 |
|
| 750 |
_, err := tlsConn.Write([]byte("CONNECT {\"verbose\":true,\"pedantic\":false,\"protocol\":1}\r\nPING\r\n")) |
| 751 |
require_NoError(t, err) |
| 752 |
|
| 753 |
line, err := cr.ReadString('\n') |
| 754 |
require_NoError(t, err) |
| 755 |
require_True(t, strings.HasPrefix(line, "+OK")) |
| 756 |
expectPong(t, cr) |
| 757 |
|
| 758 |
checkFor(t, time.Second, 10*time.Millisecond, func() error { |
| 759 |
if findProxyProtoClient(t, s, clientIP, clientPort) == nil { |
| 760 |
return fmt.Errorf("no client with PROXY-supplied host/port yet") |
| 761 |
} |
| 762 |
return nil |
| 763 |
}) |
| 764 |
} |
| 765 |
|
| 766 |
// TestClientProxyProtoV2WithRequiredTLS is the v2 counterpart to |
| 767 |
// TestClientProxyProtoV1WithRequiredTLS. |
| 768 |
func TestClientProxyProtoV2WithRequiredTLS(t *testing.T) { |
| 769 |
s := runProxyProtoTLSServer(t) |
| 770 |
defer s.Shutdown() |
| 771 |
|
| 772 |
clientIP, clientPort := "203.0.113.51", uint16(54322) |
| 773 |
header := buildProxyV2Header(t, clientIP, "127.0.0.1", clientPort, 4222, proxyProtoFamilyInet) |
| 774 |
cr, tlsConn := connectProxyProtoTLS(t, s.Addr().String(), header) |
| 775 |
defer tlsConn.Close() |
| 776 |
|
| 777 |
_, err := tlsConn.Write([]byte("CONNECT {\"verbose\":true,\"pedantic\":false,\"protocol\":1}\r\nPING\r\n")) |
| 778 |
require_NoError(t, err) |
| 779 |
|
| 780 |
line, err := cr.ReadString('\n') |
| 781 |
require_NoError(t, err) |
| 782 |
require_True(t, strings.HasPrefix(line, "+OK")) |
| 783 |
expectPong(t, cr) |
| 784 |
|
| 785 |
checkFor(t, time.Second, 10*time.Millisecond, func() error { |
| 786 |
if findProxyProtoClient(t, s, clientIP, clientPort) == nil { |
| 787 |
return fmt.Errorf("no client with PROXY-supplied host/port yet") |
| 788 |
} |
| 789 |
return nil |
| 790 |
}) |
| 791 |
} |
| 792 |
|
| 793 |
func TestClientProxyProtoNonProxiedTLSFirstFallback(t *testing.T) { |
| 794 |
tc := &TLSConfigOpts{ |
| 795 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 796 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 797 |
CaFile: "../test/configs/certs/ca.pem", |
| 798 |
} |
| 799 |
tlsConfig, err := GenTLSConfig(tc) |
| 800 |
require_NoError(t, err) |
| 801 |
|
| 802 |
opts := DefaultOptions() |
| 803 |
opts.Port = -1 |
| 804 |
opts.ProxyProtocol = true |
| 805 |
opts.TLSConfig = tlsConfig |
| 806 |
opts.TLSTimeout = 2 |
| 807 |
opts.TLSHandshakeFirst = true |
| 808 |
opts.TLSHandshakeFirstFallback = 250 * time.Millisecond |
| 809 |
s := RunServer(opts) |
| 810 |
defer s.Shutdown() |
| 811 |
|
| 812 |
rawConn, err := net.Dial("tcp", s.Addr().String()) |
| 813 |
require_NoError(t, err) |
| 814 |
defer rawConn.Close() |
| 815 |
require_NoError(t, rawConn.SetDeadline(time.Now().Add(5*time.Second))) |
| 816 |
|
| 817 |
// Direct TLS-first client: start the handshake right away (within the |
| 818 |
// fallback delay), no PROXY header. |
| 819 |
tlsConn := tls.Client(rawConn, proxyProtoTLSClientConfig(t)) |
| 820 |
require_NoError(t, tlsConn.Handshake()) |
| 821 |
|
| 822 |
cr := bufio.NewReader(tlsConn) |
| 823 |
infoLine, err := cr.ReadString('\n') |
| 824 |
require_NoError(t, err) |
| 825 |
require_True(t, strings.HasPrefix(infoLine, "INFO ")) |
| 826 |
|
| 827 |
_, err = tlsConn.Write([]byte("CONNECT {\"verbose\":true,\"pedantic\":false,\"protocol\":1}\r\nPING\r\n")) |
| 828 |
require_NoError(t, err) |
| 829 |
|
| 830 |
line, err := cr.ReadString('\n') |
| 831 |
require_NoError(t, err) |
| 832 |
require_True(t, strings.HasPrefix(line, "+OK")) |
| 833 |
expectPong(t, cr) |
| 834 |
} |
| 835 |
|
| 836 |
// runProxyProtoAllowNonTLSServer starts a server with proxy_protocol and a |
| 837 |
// TLS listener that also allows non-TLS clients (allow_non_tls). |
| 838 |
func runProxyProtoAllowNonTLSServer(t *testing.T) *Server { |
| 839 |
t.Helper() |
| 840 |
tc := &TLSConfigOpts{ |
| 841 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 842 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 843 |
CaFile: "../test/configs/certs/ca.pem", |
| 844 |
} |
| 845 |
tlsConfig, err := GenTLSConfig(tc) |
| 846 |
require_NoError(t, err) |
| 847 |
|
| 848 |
opts := DefaultOptions() |
| 849 |
opts.Port = -1 |
| 850 |
opts.ProxyProtocol = true |
| 851 |
opts.TLSConfig = tlsConfig |
| 852 |
opts.TLSTimeout = 2 |
| 853 |
opts.AllowNonTLS = true |
| 854 |
return RunServer(opts) |
| 855 |
} |
| 856 |
|
| 857 |
// testClientProxyProtoAllowNonTLS verifies that with proxy_protocol and |
| 858 |
// allow_non_tls, the TLS-vs-plaintext detection is performed on the first |
| 859 |
// byte of the client's actual traffic, not on the first byte of the PROXY |
| 860 |
// header. Both a TLS client and a plaintext client behind the proxy must |
| 861 |
// be able to connect on the same listener. |
| 862 |
func testClientProxyProtoAllowNonTLS(t *testing.T, header []byte, clientIP string, clientPort uint16) { |
| 863 |
t.Helper() |
| 864 |
s := runProxyProtoAllowNonTLSServer(t) |
| 865 |
defer s.Shutdown() |
| 866 |
|
| 867 |
// TLS client behind the proxy: the sniff must detect the TLS |
| 868 |
// ClientHello that follows the PROXY header. |
| 869 |
cr, tlsConn := connectProxyProtoTLS(t, s.Addr().String(), header) |
| 870 |
defer tlsConn.Close() |
| 871 |
|
| 872 |
_, err := tlsConn.Write([]byte("CONNECT {\"verbose\":true,\"pedantic\":false,\"protocol\":1}\r\nPING\r\n")) |
| 873 |
require_NoError(t, err) |
| 874 |
|
| 875 |
line, err := cr.ReadString('\n') |
| 876 |
require_NoError(t, err) |
| 877 |
require_True(t, strings.HasPrefix(line, "+OK")) |
| 878 |
expectPong(t, cr) |
| 879 |
|
| 880 |
checkFor(t, time.Second, 10*time.Millisecond, func() error { |
| 881 |
if findProxyProtoClient(t, s, clientIP, clientPort) == nil { |
| 882 |
return fmt.Errorf("no client with PROXY-supplied host/port yet") |
| 883 |
} |
| 884 |
return nil |
| 885 |
}) |
| 886 |
|
| 887 |
// Plaintext client behind the proxy must still be allowed. |
| 888 |
rawConn, err := net.Dial("tcp", s.Addr().String()) |
| 889 |
require_NoError(t, err) |
| 890 |
defer rawConn.Close() |
| 891 |
require_NoError(t, rawConn.SetDeadline(time.Now().Add(5*time.Second))) |
| 892 |
|
| 893 |
_, err = rawConn.Write(header) |
| 894 |
require_NoError(t, err) |
| 895 |
|
| 896 |
plainReader := bufio.NewReader(rawConn) |
| 897 |
infoLine, err := plainReader.ReadString('\n') |
| 898 |
require_NoError(t, err) |
| 899 |
require_True(t, strings.HasPrefix(infoLine, "INFO ")) |
| 900 |
|
| 901 |
_, err = rawConn.Write([]byte("CONNECT {\"verbose\":true,\"pedantic\":false,\"protocol\":1}\r\nPING\r\n")) |
| 902 |
require_NoError(t, err) |
| 903 |
|
| 904 |
line, err = plainReader.ReadString('\n') |
| 905 |
require_NoError(t, err) |
| 906 |
require_True(t, strings.HasPrefix(line, "+OK")) |
| 907 |
expectPong(t, plainReader) |
| 908 |
} |
| 909 |
|
| 910 |
// TestClientProxyProtoV1WithAllowNonTLS verifies that a proxied TLS client is |
| 911 |
// detected as TLS (and a proxied plaintext client as non-TLS) when the |
| 912 |
// listener has both tls and allow_non_tls configured, using a PROXY v1 header. |
| 913 |
func TestClientProxyProtoV1WithAllowNonTLS(t *testing.T) { |
| 914 |
clientIP, clientPort := "203.0.113.60", uint16(54331) |
| 915 |
header := buildProxyV1Header(t, "TCP4", clientIP, "127.0.0.1", clientPort, 4222) |
| 916 |
testClientProxyProtoAllowNonTLS(t, header, clientIP, clientPort) |
| 917 |
} |
| 918 |
|
| 919 |
// TestClientProxyProtoV2WithAllowNonTLS is the v2 counterpart to |
| 920 |
// TestClientProxyProtoV1WithAllowNonTLS. |
| 921 |
func TestClientProxyProtoV2WithAllowNonTLS(t *testing.T) { |
| 922 |
clientIP, clientPort := "203.0.113.61", uint16(54332) |
| 923 |
header := buildProxyV2Header(t, clientIP, "127.0.0.1", clientPort, 4222, proxyProtoFamilyInet) |
| 924 |
testClientProxyProtoAllowNonTLS(t, header, clientIP, clientPort) |
| 925 |
} |