feat(ssl): Add LetsEncrypt certificate option

This commit is contained in:
Björn Benouarets
2025-12-16 14:15:16 +01:00
parent 69a42d957d
commit eec632ff97
10 changed files with 568 additions and 11 deletions

View File

@@ -1,11 +1,13 @@
package proxy
import (
"crypto/tls"
"fmt"
"net"
"git.secnex.io/secnex/masterlog"
"git.secnex.io/secnex/pgproxy/config"
"github.com/caddyserver/certmagic"
)
// Proxy handles PostgreSQL connection proxying
@@ -16,16 +18,59 @@ type Proxy struct {
host string
port int
}
certmagic *certmagic.Config // For Let's Encrypt certificate management
certificate *tls.Certificate // For regular TLS (non-Let's Encrypt)
}
// NewProxy creates a new proxy instance
func NewProxy(config *config.Config) (*Proxy, error) {
addr := fmt.Sprintf("%s:%d", config.Listen.Address, config.Listen.Port)
listener, err := net.Listen("tcp", addr)
var listener net.Listener
var err error
var certmagicConfig *certmagic.Config
var certificate *tls.Certificate
// Always create a TCP listener (not TLS listener)
// We'll handle TLS in handleConnection to support both TLS and non-TLS connections
tcpListener, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
// If TLS is enabled, prepare certificates but don't wrap listener in TLS
// This allows both TLS and non-TLS connections
if config.TLS.Enabled {
// Check if Let's Encrypt is enabled
if config.TLS.LetsEncrypt.Enabled {
// Setup Let's Encrypt
certmagicConfig, err = getCertificateForMappingsWithLetsEncrypt(config)
if err != nil {
return nil, fmt.Errorf("failed to setup Let's Encrypt: %w", err)
}
masterlog.Info("TLS enabled with Let's Encrypt (optional)", map[string]interface{}{
"email": config.TLS.LetsEncrypt.Email,
"staging": config.TLS.LetsEncrypt.Staging,
"cacheDir": config.TLS.LetsEncrypt.CacheDir,
})
} else {
// Get certificate (load from files or generate self-signed)
cert, err := getCertificateForMappings(config)
if err != nil {
return nil, fmt.Errorf("failed to get TLS certificate: %w", err)
}
certificate = &cert
masterlog.Info("TLS enabled (optional)", map[string]interface{}{
"certFile": config.TLS.CertFile,
"keyFile": config.TLS.KeyFile,
})
}
}
listener = tcpListener
// Build mappings map for quick lookup
mappings := make(map[string]struct {
host string
@@ -46,9 +91,11 @@ func NewProxy(config *config.Config) (*Proxy, error) {
}
return &Proxy{
listener: listener,
config: config,
mappings: mappings,
listener: listener,
config: config,
mappings: mappings,
certmagic: certmagicConfig,
certificate: certificate,
}, nil
}