Merge pull request #6 from bitechdev/copilot/sub-pr-5

Implement persistent certificate storage with reuse for self-signed SSL
This commit is contained in:
Hein Puth (Warkanum)
2025-12-30 13:27:50 +02:00
committed by GitHub
4 changed files with 193 additions and 18 deletions

4
go.mod
View File

@@ -12,6 +12,7 @@ require (
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
github.com/jackc/pgx/v5 v5.6.0
github.com/klauspost/compress v1.18.0
github.com/prometheus/client_golang v1.23.2
github.com/redis/go-redis/v9 v9.17.1
github.com/spf13/viper v1.21.0
@@ -29,6 +30,7 @@ require (
go.opentelemetry.io/otel/sdk v1.38.0
go.opentelemetry.io/otel/trace v1.38.0
go.uber.org/zap v1.27.0
golang.org/x/crypto v0.43.0
golang.org/x/time v0.14.0
gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.25.12
@@ -68,7 +70,6 @@ require (
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -117,7 +118,6 @@ require (
go.uber.org/multierr v1.10.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
golang.org/x/net v0.45.0 // indirect
golang.org/x/sync v0.18.0 // indirect

View File

@@ -397,8 +397,8 @@ func (sm *serverManager) ServeWithGracefulShutdown() error {
type serverInstance struct {
cfg Config
gracefulServer *gracefulServer
certFile string // Path to certificate file (may be temporary for self-signed)
keyFile string // Path to key file (may be temporary for self-signed)
certFile string // Path to certificate file (may be persistent for self-signed)
keyFile string // Path to key file (may be persistent for self-signed)
mu sync.RWMutex
running bool
serverErr chan error

View File

@@ -6,6 +6,8 @@ import (
"io"
"net"
"net/http"
"os"
"path/filepath"
"sync"
"testing"
"time"
@@ -326,3 +328,72 @@ func TestShutdownCallbacks(t *testing.T) {
assert.True(t, executed, "Shutdown callback should have been executed")
}
func TestSelfSignedSSLCertificateReuse(t *testing.T) {
logger.Init(true)
// Get expected cert directory location
cacheDir, err := os.UserCacheDir()
require.NoError(t, err)
certDir := filepath.Join(cacheDir, "resolvespec", "certs")
host := "localhost"
certFile := filepath.Join(certDir, fmt.Sprintf("%s-cert.pem", host))
keyFile := filepath.Join(certDir, fmt.Sprintf("%s-key.pem", host))
// Clean up any existing cert files from previous tests
os.Remove(certFile)
os.Remove(keyFile)
// First server creation - should generate new certificates
sm1 := NewManager()
testPort1 := getFreePort(t)
_, err = sm1.Add(Config{
Name: "SSLTestServer1",
Host: host,
Port: testPort1,
Handler: http.NewServeMux(),
SelfSignedSSL: true,
ShutdownTimeout: 5 * time.Second,
})
require.NoError(t, err)
// Verify certificates were created
_, err = os.Stat(certFile)
require.NoError(t, err, "certificate file should exist after first creation")
_, err = os.Stat(keyFile)
require.NoError(t, err, "key file should exist after first creation")
// Get modification time of cert file
info1, err := os.Stat(certFile)
require.NoError(t, err)
modTime1 := info1.ModTime()
// Wait a bit to ensure different modification times
time.Sleep(100 * time.Millisecond)
// Second server creation - should reuse existing certificates
sm2 := NewManager()
testPort2 := getFreePort(t)
_, err = sm2.Add(Config{
Name: "SSLTestServer2",
Host: host,
Port: testPort2,
Handler: http.NewServeMux(),
SelfSignedSSL: true,
ShutdownTimeout: 5 * time.Second,
})
require.NoError(t, err)
// Get modification time of cert file after second creation
info2, err := os.Stat(certFile)
require.NoError(t, err)
modTime2 := info2.ModTime()
// Verify the certificate was reused (same modification time)
assert.Equal(t, modTime1, modTime2, "certificate should be reused, not regenerated")
// Clean up
sm1.StopAll()
sm2.StopAll()
}

View File

@@ -13,11 +13,15 @@ import (
"net"
"os"
"path/filepath"
"sync"
"time"
"golang.org/x/crypto/acme/autocert"
)
// certGenerationMutex protects concurrent certificate generation for the same host
var certGenerationMutex sync.Mutex
// generateSelfSignedCert generates a self-signed certificate for the given host.
// Returns the certificate and private key in PEM format.
func generateSelfSignedCert(host string) (certPEM, keyPEM []byte, err error) {
@@ -75,30 +79,101 @@ func generateSelfSignedCert(host string) (certPEM, keyPEM []byte, err error) {
return certPEM, keyPEM, nil
}
// saveCertToTempFiles saves certificate and key PEM data to temporary files.
// Returns the file paths for the certificate and key.
func saveCertToTempFiles(certPEM, keyPEM []byte) (certFile, keyFile string, err error) {
// Create temporary directory
tmpDir, err := os.MkdirTemp("", "resolvespec-certs-*")
if err != nil {
return "", "", fmt.Errorf("failed to create temp directory: %w", err)
// sanitizeHostname converts a hostname to a safe filename by replacing invalid characters.
func sanitizeHostname(host string) string {
// Replace any character that's not alphanumeric, dot, or dash with underscore
safe := ""
for _, r := range host {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '.' || r == '-' {
safe += string(r)
} else {
safe += "_"
}
}
return safe
}
certFile = filepath.Join(tmpDir, "cert.pem")
keyFile = filepath.Join(tmpDir, "key.pem")
// getCertDirectory returns the directory path for storing self-signed certificates.
// Creates the directory if it doesn't exist.
func getCertDirectory() (string, error) {
// Use a consistent directory in the user's cache directory
cacheDir, err := os.UserCacheDir()
if err != nil {
// Fallback to current directory if cache dir is not available
cacheDir = "."
}
certDir := filepath.Join(cacheDir, "resolvespec", "certs")
// Create directory if it doesn't exist
if err := os.MkdirAll(certDir, 0700); err != nil {
return "", fmt.Errorf("failed to create certificate directory: %w", err)
}
return certDir, nil
}
// isCertificateValid checks if a certificate file exists and is not expired.
func isCertificateValid(certFile string) bool {
// Check if file exists
certData, err := os.ReadFile(certFile)
if err != nil {
return false
}
// Parse certificate
block, _ := pem.Decode(certData)
if block == nil {
return false
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return false
}
// Check if certificate is expired or will expire in the next 30 days
now := time.Now()
expiryThreshold := now.Add(30 * 24 * time.Hour)
if now.Before(cert.NotBefore) || now.After(cert.NotAfter) {
return false
}
// Renew if expiring soon
if expiryThreshold.After(cert.NotAfter) {
return false
}
return true
}
// saveCertToFiles saves certificate and key PEM data to persistent files.
// Returns the file paths for the certificate and key.
func saveCertToFiles(certPEM, keyPEM []byte, host string) (certFile, keyFile string, err error) {
// Get certificate directory
certDir, err := getCertDirectory()
if err != nil {
return "", "", err
}
// Sanitize hostname for safe file naming
safeHost := sanitizeHostname(host)
// Use consistent file names based on host
certFile = filepath.Join(certDir, fmt.Sprintf("%s-cert.pem", safeHost))
keyFile = filepath.Join(certDir, fmt.Sprintf("%s-key.pem", safeHost))
// Write certificate
if err := os.WriteFile(certFile, certPEM, 0600); err != nil {
os.RemoveAll(tmpDir)
return "", "", fmt.Errorf("failed to write certificate: %w", err)
}
// Write key
if err := os.WriteFile(keyFile, keyPEM, 0600); err != nil {
os.RemoveAll(tmpDir)
return "", "", fmt.Errorf("failed to write private key: %w", err)
}
return certFile, keyFile, nil
}
@@ -170,12 +245,41 @@ func configureTLS(cfg Config) (*tls.Config, string, string, error) {
host = "localhost"
}
// Sanitize hostname for safe file naming
safeHost := sanitizeHostname(host)
// Lock to prevent concurrent certificate generation for the same host
certGenerationMutex.Lock()
defer certGenerationMutex.Unlock()
// Get certificate directory
certDir, err := getCertDirectory()
if err != nil {
return nil, "", "", fmt.Errorf("failed to get certificate directory: %w", err)
}
// Check for existing valid certificates
certFile := filepath.Join(certDir, fmt.Sprintf("%s-cert.pem", safeHost))
keyFile := filepath.Join(certDir, fmt.Sprintf("%s-key.pem", safeHost))
// If valid certificates exist, reuse them
if isCertificateValid(certFile) {
// Verify key file also exists
if _, err := os.Stat(keyFile); err == nil {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
}
return tlsConfig, certFile, keyFile, nil
}
}
// Generate new certificates
certPEM, keyPEM, err := generateSelfSignedCert(host)
if err != nil {
return nil, "", "", fmt.Errorf("failed to generate self-signed certificate: %w", err)
}
certFile, keyFile, err := saveCertToTempFiles(certPEM, keyPEM)
certFile, keyFile, err = saveCertToFiles(certPEM, keyPEM, host)
if err != nil {
return nil, "", "", fmt.Errorf("failed to save self-signed certificate: %w", err)
}