clavitor/operations/pop-sync/cmd/pop-example/main.go

75 lines
2.1 KiB
Go

// Example: POP runtime mTLS usage
//
// This file demonstrates how a Clavitor POP would use the popmtls package
// to configure mutual TLS for POP-to-POP communication.
//
// Place this in your POP server code to enable mTLS.
package main
import (
"fmt"
"log"
"net/http"
"clavitor.ai/pop-sync/popmtls"
)
func main() {
// Load mTLS configuration for this POP
// Assumes certificates are deployed at /opt/clavitor/certs/
// Files expected:
// - /opt/clavitor/certs/<region>.key (POP private key)
// - /opt/clavitor/certs/<region>.crt (POP certificate)
// - /opt/clavitor/certs/ca-chain.crt (intermediate + root CA)
region := "use1" // This would come from env var or config
certDir := "/opt/clavitor/certs"
tlsConfig, err := popmtls.LoadConfig(certDir, region)
if err != nil {
log.Fatalf("Failed to load mTLS config: %v", err)
}
// Example 1: As server (accepting connections from other POPs)
server := &http.Server{
Addr: ":8443",
TLSConfig: tlsConfig,
Handler: popHandler(),
}
log.Println("POP server starting with mTLS on :8443")
log.Fatal(server.ListenAndServeTLS("", "")) // Certs are in tlsConfig
}
func popHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
// In mTLS mode, you can access the peer certificate
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
peer := r.TLS.PeerCertificates[0]
log.Printf("Request from verified POP: %s (CN=%s)",
r.RemoteAddr, peer.Subject.CommonName)
}
w.Write([]byte("OK"))
})
mux.HandleFunc("/replicate", func(w http.ResponseWriter, r *http.Request) {
// Verify peer is a valid POP before accepting replication data
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
http.Error(w, "mTLS required", http.StatusForbidden)
return
}
peer := r.TLS.PeerCertificates[0]
region := peer.Subject.CommonName
// Process replication request from verified POP
log.Printf("Replication request from %s", region)
w.Write([]byte(fmt.Sprintf("Replication accepted from %s", region)))
})
return mux
}