diff --git a/cmd/kat-agent/main.go b/cmd/kat-agent/main.go index 3e85ff6..90c8d69 100644 --- a/cmd/kat-agent/main.go +++ b/cmd/kat-agent/main.go @@ -4,12 +4,14 @@ import ( "context" "fmt" "log" + "net/http" "os" "os/signal" "path/filepath" "syscall" "time" + "git.dws.rip/dubey/kat/internal/api" "git.dws.rip/dubey/kat/internal/config" "git.dws.rip/dubey/kat/internal/leader" "git.dws.rip/dubey/kat/internal/pki" @@ -208,6 +210,45 @@ func runInit(cmd *cobra.Command, args []string) { parsedClusterConfig.Spec.ApiPort) } } + + // Start API server with mTLS + log.Println("Starting API server with mTLS...") + apiAddr := fmt.Sprintf(":%d", parsedClusterConfig.Spec.ApiPort) + apiServer, err := api.NewServer(apiAddr, leaderCertPath, leaderKeyPath, caCertPath) + if err != nil { + log.Printf("Failed to create API server: %v", err) + } else { + // Register the join handler + apiServer.RegisterJoinHandler(func(w http.ResponseWriter, r *http.Request) { + log.Printf("Received join request from %s", r.RemoteAddr) + w.WriteHeader(http.StatusOK) + w.Write([]byte("Join endpoint is operational")) + }) + + // Start the server in a goroutine + go func() { + if err := apiServer.Start(); err != nil && err != http.ErrServerClosed { + log.Printf("API server error: %v", err) + } + }() + + // Add a shutdown hook to the leadership context + go func() { + <-leadershipCtx.Done() + log.Println("Leadership lost, shutting down API server...") + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := apiServer.Stop(shutdownCtx); err != nil { + log.Printf("Error shutting down API server: %v", err) + } + }() + + log.Printf("API server started on port %d with mTLS", parsedClusterConfig.Spec.ApiPort) + log.Printf("Verification: API server requires client certificates signed by the cluster CA") + log.Printf("Test with: curl --cacert %s --cert --key https://localhost:%d/internal/v1alpha1/join", + caCertPath, parsedClusterConfig.Spec.ApiPort) + } + log.Println("Initial leader setup complete. Waiting for leadership context to end or agent to be stopped.") <-leadershipCtx.Done() // Wait until leadership is lost or context is cancelled by manager },