fix: handle CSR file path and raw PEM data in SignCertificateRequest

This commit is contained in:
2025-05-16 21:17:23 -04:00
parent 47f9b69876
commit 4f6365d453
2 changed files with 24 additions and 9 deletions

View File

@ -172,6 +172,11 @@ func runInit(cmd *cobra.Command, args []string) {
// Generate key and CSR for leader
if err := pki.GenerateCertificateRequest(leaderCertCN, leaderKeyPath, leaderCSRPath); err != nil {
log.Printf("Failed to generate leader key and CSR: %v", err)
} else {
// Read the CSR file
csrData, err := os.ReadFile(leaderCSRPath)
if err != nil {
log.Printf("Failed to read leader CSR file: %v", err)
} else {
// Sign the CSR with our CA
if err := pki.SignCertificateRequest(caKeyPath, caCertPath, leaderCSRPath, leaderCertPath, 365*24*time.Hour); err != nil {
@ -180,6 +185,7 @@ func runInit(cmd *cobra.Command, args []string) {
log.Println("Successfully generated and signed leader server certificate")
}
}
}
} else {
log.Println("Leader certificate already exists, skipping generation")
}

View File

@ -10,6 +10,7 @@ import (
"math/big"
"os"
"path/filepath"
"strings"
"time"
)
@ -167,7 +168,8 @@ func GenerateCertificateRequest(commonName, keyOutPath, csrOutPath string) error
// SignCertificateRequest signs a CSR using the CA key and certificate.
// It reads the CSR from csrPath and saves the signed certificate to certOutPath.
func SignCertificateRequest(caKeyPath, caCertPath, csrPath, certOutPath string, duration time.Duration) error {
// If csrPath contains PEM data (starts with "-----BEGIN"), it uses that directly instead of reading a file.
func SignCertificateRequest(caKeyPath, caCertPath, csrPathOrData, certOutPath string, duration time.Duration) error {
// Load CA key
caKey, err := LoadCAPrivateKey(caKeyPath)
if err != nil {
@ -180,11 +182,18 @@ func SignCertificateRequest(caKeyPath, caCertPath, csrPath, certOutPath string,
return fmt.Errorf("failed to load CA certificate: %w", err)
}
// Read CSR
csrPEM, err := os.ReadFile(csrPath)
// Determine if csrPathOrData is a file path or PEM data
var csrPEM []byte
if strings.HasPrefix(csrPathOrData, "-----BEGIN") {
// It's PEM data, use it directly
csrPEM = []byte(csrPathOrData)
} else {
// It's a file path, read the file
csrPEM, err = os.ReadFile(csrPathOrData)
if err != nil {
return fmt.Errorf("failed to read CSR file: %w", err)
}
}
block, _ := pem.Decode(csrPEM)
if block == nil || block.Type != "CERTIFICATE REQUEST" {