-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.go
More file actions
627 lines (559 loc) · 17 KB
/
proxy.go
File metadata and controls
627 lines (559 loc) · 17 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package pgmux
import (
"context"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"strconv"
"sync"
"time"
"github.com/jackc/pgproto3/v2"
)
type (
// ConnectionPool manages a pool of connections to a backend server
ConnectionPool struct {
mu sync.Mutex
connections []*BackendConnection
maxSize int
config *BackendConfig
}
// BackendConnection represents a connection to a backend PostgreSQL server
BackendConnection struct {
conn net.Conn
inUse bool
lastUsed time.Time
}
// TLSConfig holds TLS configuration for the proxy server
TLSConfig struct {
// Enable TLS support
Enabled bool
// Path to certificate file
CertFile string
// Path to key file
KeyFile string
// Optional TLS config for advanced settings
Config *tls.Config
}
// ProxyServer is a PostgreSQL proxy server that routes connections based on username
ProxyServer struct {
listenAddr string
router Router
pools map[string]*ConnectionPool
mu sync.RWMutex
tlsConfig *TLSConfig
}
)
// NewProxyServer creates a new ProxyServer with the given listen address and router
func NewProxyServer(listenAddr string, router Router) *ProxyServer {
return &ProxyServer{
listenAddr: listenAddr,
router: router,
pools: make(map[string]*ConnectionPool),
}
}
// WithTLS configures TLS support for the proxy server
func (ps *ProxyServer) WithTLS(config *TLSConfig) *ProxyServer {
ps.tlsConfig = config
return ps
}
// Start starts the proxy server and listens for connections
func (ps *ProxyServer) Start(ctx context.Context) error {
// Always start with a plain TCP listener
// TLS upgrade happens after SSL negotiation
listener, err := net.Listen("tcp", ps.listenAddr)
if err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
defer listener.Close()
if ps.tlsConfig != nil && ps.tlsConfig.Enabled {
log.Printf("PostgreSQL proxy listening on %s (TLS available)", ps.listenAddr)
} else {
log.Printf("PostgreSQL proxy listening on %s", ps.listenAddr)
}
// Close listener when context is cancelled
go func() {
<-ctx.Done()
listener.Close()
}()
for {
conn, err := listener.Accept()
if err != nil {
select {
case <-ctx.Done():
return nil
default:
log.Printf("Failed to accept connection: %v", err)
continue
}
}
go ps.handleConnection(ctx, conn)
}
}
func (ps *ProxyServer) handleConnection(ctx context.Context, clientConn net.Conn) {
defer clientConn.Close()
backend := pgproto3.NewBackend(pgproto3.NewChunkReader(clientConn), clientConn)
startupMsg, err := backend.ReceiveStartupMessage()
if err != nil {
log.Printf("Failed to receive startup message: %v", err)
return
}
log.Printf("Received startup message type: %T", startupMsg)
switch msg := startupMsg.(type) {
case *pgproto3.StartupMessage:
log.Printf("Protocol version: %d.%d", msg.ProtocolVersion>>16, msg.ProtocolVersion&0xFFFF)
ps.handleStartupMessage(ctx, backend, msg, clientConn)
case *pgproto3.SSLRequest:
// Handle SSL negotiation
if ps.tlsConfig != nil && ps.tlsConfig.Enabled {
// Send 'S' to indicate SSL is supported
_, err := clientConn.Write([]byte{'S'})
if err != nil {
log.Printf("Failed to send SSL response: %v", err)
return
}
// Upgrade connection to TLS
var tlsConfig *tls.Config
if ps.tlsConfig.Config != nil {
tlsConfig = ps.tlsConfig.Config
} else if ps.tlsConfig.CertFile != "" && ps.tlsConfig.KeyFile != "" {
cert, err := tls.LoadX509KeyPair(ps.tlsConfig.CertFile, ps.tlsConfig.KeyFile)
if err != nil {
log.Printf("Failed to load TLS certificates: %v", err)
return
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
}
} else {
log.Printf("TLS enabled but no certificates configured")
return
}
// Perform TLS handshake
tlsConn := tls.Server(clientConn, tlsConfig)
if err := tlsConn.Handshake(); err != nil {
log.Printf("TLS handshake failed: %v", err)
return
}
log.Printf("TLS connection established")
// Create new backend with TLS connection
tlsBackend := pgproto3.NewBackend(pgproto3.NewChunkReader(tlsConn), tlsConn)
// Receive the actual startup message over TLS
startupMsg, err := tlsBackend.ReceiveStartupMessage()
if err != nil {
log.Printf("Failed to receive startup message after TLS: %v", err)
return
}
if sm, ok := startupMsg.(*pgproto3.StartupMessage); ok {
ps.handleStartupMessage(ctx, tlsBackend, sm, tlsConn)
}
} else {
// TLS not configured, respond with 'N'
_, err := clientConn.Write([]byte{'N'})
if err != nil {
log.Printf("Failed to send SSL response: %v", err)
return
}
// Continue to receive the actual startup message without TLS
startupMsg, err := backend.ReceiveStartupMessage()
if err != nil {
log.Printf("Failed to receive startup message after SSL: %v", err)
return
}
if sm, ok := startupMsg.(*pgproto3.StartupMessage); ok {
ps.handleStartupMessage(ctx, backend, sm, clientConn)
}
}
default:
log.Printf("Unexpected startup message type: %T", msg)
}
}
func (ps *ProxyServer) handleStartupMessage(ctx context.Context, clientBackend *pgproto3.Backend,
startupMsg *pgproto3.StartupMessage, clientConn net.Conn,
) {
originalUser := startupMsg.Parameters["user"]
log.Printf("New connection for user: %s", originalUser)
log.Printf("Startup parameters: %+v", startupMsg.Parameters)
// Route the user to get backend configuration
backendConfig, err := ps.router.Route(ctx, originalUser)
if err != nil {
var errorMsg *pgproto3.ErrorResponse
if err == ErrUserNotFound {
errorMsg = &pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "28P01",
Message: fmt.Sprintf("User mapping not found for: %s", originalUser),
}
} else {
errorMsg = &pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08001",
Message: fmt.Sprintf("Routing error: %v", err),
}
}
buf, _ := errorMsg.Encode(nil)
clientConn.Write(buf)
return
}
// Create new connection for authentication (with retries for port changes)
addr := net.JoinHostPort(backendConfig.Host, strconv.Itoa(backendConfig.Port))
log.Printf("Connecting to backend %s as user %s", addr, backendConfig.User)
var backendConn net.Conn
maxRetries := 3
for attempt := range maxRetries {
if attempt > 0 {
// progressive wait
time.Sleep(time.Duration(attempt) * 500 * time.Millisecond)
backendConfig, err = ps.router.Route(ctx, originalUser)
if err != nil {
break
}
addr = net.JoinHostPort(backendConfig.Host, strconv.Itoa(backendConfig.Port))
log.Printf("Retrying backend connection (attempt %d) to %s", attempt+1, addr)
}
dialer := net.Dialer{Timeout: 5 * time.Second}
backendConn, err = dialer.DialContext(ctx, "tcp", addr)
if err == nil {
break
}
log.Printf("Backend dial failed (attempt %d/%d): %v", attempt+1, maxRetries, err)
}
if err != nil {
errorMsg := &pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08001",
Message: fmt.Sprintf("Could not connect to backend: %v", err),
}
buf, _ := errorMsg.Encode(nil)
clientConn.Write(buf)
return
}
defer backendConn.Close()
// Modify only the user parameter, keep all others
startupMsg.Parameters["user"] = backendConfig.User
serverFrontend := pgproto3.NewFrontend(pgproto3.NewChunkReader(backendConn), backendConn)
buf, _ := startupMsg.Encode(nil)
log.Printf("Sending startup message to backend with parameters: %+v", startupMsg.Parameters)
_, err = backendConn.Write(buf)
if err != nil {
log.Printf("Failed to send startup message to backend: %v", err)
return
}
if err := ps.handleAuthentication(clientBackend, serverFrontend, clientConn, backendConn); err != nil {
log.Printf("Authentication failed: %v", err)
return
}
log.Printf("Authentication successful for user %s", originalUser)
ps.proxyMessages(ctx, clientBackend, serverFrontend, clientConn, backendConn)
}
func (ps *ProxyServer) handleAuthentication(clientBackend *pgproto3.Backend, serverFrontend *pgproto3.Frontend,
clientConn, serverConn net.Conn,
) error {
// Set a reasonable timeout for authentication
serverConn.SetReadDeadline(time.Now().Add(30 * time.Second))
clientConn.SetReadDeadline(time.Now().Add(30 * time.Second))
defer func() {
serverConn.SetReadDeadline(time.Time{})
clientConn.SetReadDeadline(time.Time{})
}()
for {
msg, err := serverFrontend.Receive()
if err != nil {
return fmt.Errorf("failed to receive from backend: %w", err)
}
log.Printf("Received auth message from backend: %T", msg)
var buf []byte
switch msg := msg.(type) {
case *pgproto3.AuthenticationOk:
log.Printf("Authentication OK received")
buf, _ = msg.Encode(nil)
case *pgproto3.AuthenticationCleartextPassword:
buf, _ = msg.Encode(nil)
_, err = clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send auth request to client: %w", err)
}
passMsg, err := clientBackend.Receive()
if err != nil {
return fmt.Errorf("failed to receive password: %w", err)
}
if pm, ok := passMsg.(*pgproto3.PasswordMessage); ok {
buf, _ = pm.Encode(nil)
_, err = serverConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send password to server: %w", err)
}
}
continue
case *pgproto3.AuthenticationMD5Password:
buf, _ = msg.Encode(nil)
_, err = clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send auth request to client: %w", err)
}
passMsg, err := clientBackend.Receive()
if err != nil {
return fmt.Errorf("failed to receive password: %w", err)
}
if pm, ok := passMsg.(*pgproto3.PasswordMessage); ok {
buf, _ = pm.Encode(nil)
_, err = serverConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send password to server: %w", err)
}
}
continue
case *pgproto3.AuthenticationSASL:
// SASL authentication - forward to client
log.Printf("SASL authentication requested, mechanisms: %v", msg.AuthMechanisms)
buf, _ := msg.Encode(nil)
log.Printf("Sending SASL auth to client, message length: %d bytes", len(buf))
n, err := clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send SASL auth to client: %w", err)
}
log.Printf("Wrote %d bytes to client", n)
// Get SASL initial response from client
log.Printf("Waiting for SASL response from client...")
clientConn.SetReadDeadline(time.Now().Add(10 * time.Second))
rawBuf := make([]byte, 1024)
n, err = clientConn.Read(rawBuf)
clientConn.SetReadDeadline(time.Time{})
if err != nil {
return fmt.Errorf("failed to read from client: %w", err)
}
log.Printf("Raw message from client (%d bytes): %x", n, rawBuf[:n])
// Forward the client's SASL initial response to backend
log.Printf("Forwarding client SASL response to backend server")
_, err = serverConn.Write(rawBuf[:n])
if err != nil {
return fmt.Errorf("failed to forward client response: %w", err)
}
// Handle the rest of the SASL handshake
for {
// Read response from server
serverMsg, err := serverFrontend.Receive()
if err != nil {
return fmt.Errorf("failed to receive from server during SASL: %w", err)
}
log.Printf("Received from server during SASL: %T", serverMsg)
// Forward to client
var buf []byte
switch msg := serverMsg.(type) {
case *pgproto3.AuthenticationSASLContinue:
buf, _ = msg.Encode(nil)
case *pgproto3.AuthenticationSASLFinal:
buf, _ = msg.Encode(nil)
case *pgproto3.AuthenticationOk:
buf, _ = msg.Encode(nil)
clientConn.Write(buf)
log.Printf("SASL authentication completed successfully")
return nil // Auth complete, exit this function
case *pgproto3.ErrorResponse:
buf, _ = msg.Encode(nil)
clientConn.Write(buf)
return fmt.Errorf("server auth error: %s", msg.Message)
default:
// Forward any other message types
if encoder, ok := msg.(interface{ Encode([]byte) ([]byte, error) }); ok {
buf, _ = encoder.Encode(nil)
}
}
if buf != nil {
_, err = clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to forward server message to client: %w", err)
}
}
// If it was SASL Continue, read client's response
if _, ok := serverMsg.(*pgproto3.AuthenticationSASLContinue); ok {
// Read client's SASL response
clientBuf := make([]byte, 4096)
n, err := clientConn.Read(clientBuf)
if err != nil {
return fmt.Errorf("failed to read SASL response from client: %w", err)
}
log.Printf("Forwarding client SASL continue response (%d bytes) to server", n)
// Forward to server
_, err = serverConn.Write(clientBuf[:n])
if err != nil {
return fmt.Errorf("failed to forward client SASL response: %w", err)
}
}
}
case *pgproto3.ParameterStatus:
buf, _ = msg.Encode(nil)
case *pgproto3.BackendKeyData:
buf, _ = msg.Encode(nil)
case *pgproto3.ReadyForQuery:
buf, _ = msg.Encode(nil)
_, err = clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send ready to client: %w", err)
}
return nil
case *pgproto3.ErrorResponse:
buf, _ = msg.Encode(nil)
_, err = clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to send error to client: %w", err)
}
return fmt.Errorf("authentication error: %s", msg.Message)
default:
log.Printf("Unexpected auth message type: %T", msg)
continue
}
if buf != nil {
_, err = clientConn.Write(buf)
if err != nil {
return fmt.Errorf("failed to forward auth message: %w", err)
}
}
}
}
func (ps *ProxyServer) proxyMessages(ctx context.Context, clientBackend *pgproto3.Backend,
serverFrontend *pgproto3.Frontend, clientConn, serverConn net.Conn,
) {
errChan := make(chan error, 2)
// Client to server
go func() {
for {
select {
case <-ctx.Done():
return
default:
msg, err := clientBackend.Receive()
if err != nil {
if err != io.EOF && !isConnectionClosed(err) {
errChan <- fmt.Errorf("client receive: %w", err)
}
return
}
var buf []byte
switch m := msg.(type) {
case *pgproto3.Query:
buf, _ = m.Encode(nil)
case *pgproto3.Parse:
buf, _ = m.Encode(nil)
case *pgproto3.Bind:
buf, _ = m.Encode(nil)
case *pgproto3.Execute:
buf, _ = m.Encode(nil)
case *pgproto3.Describe:
buf, _ = m.Encode(nil)
case *pgproto3.Sync:
buf, _ = m.Encode(nil)
case *pgproto3.Close:
buf, _ = m.Encode(nil)
case *pgproto3.Terminate:
buf, _ = m.Encode(nil)
case *pgproto3.CopyData:
buf, _ = m.Encode(nil)
case *pgproto3.CopyDone:
buf, _ = m.Encode(nil)
case *pgproto3.CopyFail:
buf, _ = m.Encode(nil)
case *pgproto3.Flush:
buf, _ = m.Encode(nil)
default:
log.Printf("Unknown client message type: %T", m)
continue
}
if buf != nil {
_, err = serverConn.Write(buf)
if err != nil {
errChan <- fmt.Errorf("server send: %w", err)
return
}
}
}
}
}()
// Server to client
go func() {
for {
select {
case <-ctx.Done():
return
default:
msg, err := serverFrontend.Receive()
if err != nil {
if err != io.EOF && !isConnectionClosed(err) {
errChan <- fmt.Errorf("server receive: %w", err)
}
return
}
var buf []byte
switch m := msg.(type) {
case *pgproto3.RowDescription:
buf, _ = m.Encode(nil)
case *pgproto3.DataRow:
buf, _ = m.Encode(nil)
case *pgproto3.CommandComplete:
buf, _ = m.Encode(nil)
case *pgproto3.ReadyForQuery:
buf, _ = m.Encode(nil)
case *pgproto3.ErrorResponse:
buf, _ = m.Encode(nil)
case *pgproto3.NoticeResponse:
buf, _ = m.Encode(nil)
case *pgproto3.ParameterStatus:
buf, _ = m.Encode(nil)
case *pgproto3.BackendKeyData:
buf, _ = m.Encode(nil)
case *pgproto3.ParseComplete:
buf, _ = m.Encode(nil)
case *pgproto3.BindComplete:
buf, _ = m.Encode(nil)
case *pgproto3.NoData:
buf, _ = m.Encode(nil)
case *pgproto3.EmptyQueryResponse:
buf, _ = m.Encode(nil)
case *pgproto3.ParameterDescription:
buf, _ = m.Encode(nil)
case *pgproto3.CloseComplete:
buf, _ = m.Encode(nil)
case *pgproto3.NotificationResponse:
buf, _ = m.Encode(nil)
case *pgproto3.CopyInResponse:
buf, _ = m.Encode(nil)
case *pgproto3.CopyOutResponse:
buf, _ = m.Encode(nil)
case *pgproto3.CopyBothResponse:
buf, _ = m.Encode(nil)
case *pgproto3.CopyData:
buf, _ = m.Encode(nil)
case *pgproto3.CopyDone:
buf, _ = m.Encode(nil)
case *pgproto3.PortalSuspended:
buf, _ = m.Encode(nil)
default:
log.Printf("Unknown server message type: %T", m)
continue
}
if buf != nil {
_, err = clientConn.Write(buf)
if err != nil {
errChan <- fmt.Errorf("client send: %w", err)
return
}
}
}
}
}()
select {
case err := <-errChan:
if err != nil {
log.Printf("Proxy error: %v", err)
}
case <-ctx.Done():
log.Println("Context cancelled, closing proxy connection")
}
}
func isConnectionClosed(err error) bool {
if netErr, ok := err.(*net.OpError); ok {
return netErr.Op == "read" || netErr.Op == "write"
}
return false
}