Mostly implemented issue and provision commands. Restructured AI generateed code.
This commit is contained in:
325
ca.go
325
ca.go
@@ -57,6 +57,62 @@ type CertificateDefinition struct {
|
||||
SAN []string `hcl:"san,optional"`
|
||||
}
|
||||
|
||||
func (def *CertificateDefinition) fillDefaultValues(defaults *CertificateDefaults) {
|
||||
if defaults == nil {
|
||||
return
|
||||
}
|
||||
if def.Subject == "" {
|
||||
def.Subject = defaults.Subject
|
||||
}
|
||||
if def.Type == "" {
|
||||
def.Type = defaults.Type
|
||||
}
|
||||
if def.Validity == "" {
|
||||
def.Validity = defaults.Validity
|
||||
}
|
||||
if len(def.SAN) == 0 && len(defaults.SAN) > 0 {
|
||||
def.SAN = defaults.SAN
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: renderTemplates applies Go template to a string
|
||||
// using the provided variables map. It returns an error if the template execution fails.
|
||||
func applyTemplateToString(s string, variables map[string]string) (string, error) {
|
||||
tmpl, err := template.New("").Parse(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
err = tmpl.Execute(&buf, variables)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func (c *CertificateDefinition) RenderTemplates(variables map[string]string) error {
|
||||
// Apply Go templates to Subject and SAN fields using
|
||||
// the variables map
|
||||
if c.Subject != "" {
|
||||
renderedSubject, err := applyTemplateToString(c.Subject, variables)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to render subject template: %v", err)
|
||||
}
|
||||
c.Subject = renderedSubject
|
||||
}
|
||||
|
||||
if len(c.SAN) > 0 {
|
||||
for i, san := range c.SAN {
|
||||
renderedSAN, err := applyTemplateToString(san, variables)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to render SAN template: %v", err)
|
||||
}
|
||||
c.SAN[i] = renderedSAN
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type CertificateDefaults struct {
|
||||
Subject string `hcl:"subject,optional"`
|
||||
Type string `hcl:"type,optional"`
|
||||
@@ -66,10 +122,27 @@ type CertificateDefaults struct {
|
||||
|
||||
type Certificates struct {
|
||||
Defaults *CertificateDefaults `hcl:"defaults,block"`
|
||||
Variables map[string]string `hcl:"variables,optional"`
|
||||
Certificates []CertificateDefinition `hcl:"certificate,block"`
|
||||
}
|
||||
|
||||
// Load certificate provisioning configuration from the given path.
|
||||
func (c *Certificates) LoadFromFile(path string) error {
|
||||
parser := hclparse.NewParser()
|
||||
file, diags := parser.ParseHCLFile(path)
|
||||
if diags.HasErrors() {
|
||||
return fmt.Errorf("failed to parse HCL: %s", diags.Error())
|
||||
}
|
||||
diags = gohcl.DecodeBody(file.Body, nil, c)
|
||||
if diags.HasErrors() {
|
||||
return fmt.Errorf("failed to decode HCL: %s", diags.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Global CA configuration and state variables
|
||||
var CAConfigPath string
|
||||
var CAState *_CAState
|
||||
var CAConfig *_CAConfig
|
||||
var CAKey *rsa.PrivateKey
|
||||
@@ -77,9 +150,9 @@ var CACert *x509.Certificate
|
||||
|
||||
// LoadCAConfig parses and validates the CA config from the given path and stores it in the CAConfig global variable
|
||||
func LoadCAConfig() error {
|
||||
fmt.Printf("Loading CA config from %s\n", configPath)
|
||||
fmt.Printf("Loading CA config from %s\n", CAConfigPath)
|
||||
parser := hclparse.NewParser()
|
||||
file, diags := parser.ParseHCLFile(configPath)
|
||||
file, diags := parser.ParseHCLFile(CAConfigPath)
|
||||
if diags.HasErrors() {
|
||||
return fmt.Errorf("failed to parse HCL: %s", diags.Error())
|
||||
}
|
||||
@@ -162,10 +235,17 @@ func LoadCertificatesFile(path string) ([]CertificateDefinition, *CertificateDef
|
||||
return certsFile.Certificates, certsFile.Defaults, nil
|
||||
}
|
||||
|
||||
// Certificate definitions can have validity in various formats:
|
||||
// - "1y" for 1 year
|
||||
// - "6m" for 6 months
|
||||
// - "30d" for 30 days
|
||||
// Check the syntax and parse validity string into time.Duration
|
||||
func parseValidity(validity string) (time.Duration, error) {
|
||||
// Return error is the function is called with an empty validity
|
||||
if validity == "" {
|
||||
return time.Hour * 24 * 365 * 5, nil // default 5 years
|
||||
return 0, fmt.Errorf("validity cannot be empty")
|
||||
}
|
||||
|
||||
var n int
|
||||
var unit rune
|
||||
_, err := fmt.Sscanf(validity, "%d%c", &n, &unit)
|
||||
@@ -173,10 +253,12 @@ func parseValidity(validity string) (time.Duration, error) {
|
||||
// If no unit, assume years
|
||||
_, err2 := fmt.Sscanf(validity, "%d", &n)
|
||||
if err2 != nil {
|
||||
// Still no success, return error
|
||||
return 0, fmt.Errorf("invalid validity format: %s", validity)
|
||||
}
|
||||
unit = 'y'
|
||||
}
|
||||
|
||||
switch unit {
|
||||
case 'y':
|
||||
return time.Hour * 24 * 365 * time.Duration(n), nil
|
||||
@@ -283,6 +365,11 @@ func InitCA(overwrite bool) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate serial number: %v", err)
|
||||
}
|
||||
|
||||
if CAConfig.Validity == "" {
|
||||
CAConfig.Validity = "5y" // Use default validity of 5 years
|
||||
}
|
||||
|
||||
validity, err := parseValidity(CAConfig.Validity)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -381,7 +468,7 @@ func issueSingleCertificate(def CertificateDefinition, overwrite, verbose bool)
|
||||
var validityDur time.Duration
|
||||
validity := def.Validity
|
||||
if validity == "" {
|
||||
validity = "1y"
|
||||
validity = "1y" // default to 1 year
|
||||
}
|
||||
|
||||
validityDur, err = parseValidity(validity)
|
||||
@@ -480,81 +567,115 @@ Certificate:
|
||||
return nil
|
||||
}
|
||||
|
||||
func IssueCertificate(configPath, subject, certType, validity string, san []string, name, fromFile string, overwrite, dryRun, verbose bool) error {
|
||||
if fromFile != "" {
|
||||
certDefs, defaults, err := LoadCertificatesFile(fromFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error loading certificates file: %v", err)
|
||||
}
|
||||
successes := 0
|
||||
errors := 0
|
||||
for i, def := range certDefs {
|
||||
if defaults != nil {
|
||||
if def.Type == "" {
|
||||
def.Type = defaults.Type
|
||||
}
|
||||
if def.Validity == "" {
|
||||
def.Validity = defaults.Validity
|
||||
}
|
||||
if len(def.SAN) == 0 && len(defaults.SAN) > 0 {
|
||||
def.SAN = defaults.SAN
|
||||
}
|
||||
}
|
||||
finalDef := renderCertificateDefTemplates(def, defaults)
|
||||
fmt.Printf("[%d/%d] Issuing %s... ", i+1, len(certDefs), finalDef.Name)
|
||||
if dryRun {
|
||||
fmt.Printf("(dry run)\n")
|
||||
successes++
|
||||
continue
|
||||
}
|
||||
err := issueSingleCertificate(finalDef, overwrite, verbose)
|
||||
if err != nil {
|
||||
fmt.Printf("error: %v\n", err)
|
||||
errors++
|
||||
} else {
|
||||
if !verbose {
|
||||
fmt.Printf("done\n")
|
||||
}
|
||||
successes++
|
||||
}
|
||||
}
|
||||
fmt.Printf("Batch complete: %d succeeded, %d failed.\n", successes, errors)
|
||||
if err := SaveCAState(); err != nil {
|
||||
fmt.Printf("Error saving CA state: %v\n", err)
|
||||
}
|
||||
if errors > 0 {
|
||||
return fmt.Errorf("%d certificate(s) failed to issue", errors)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Single mode
|
||||
finalDef := renderCertificateDefTemplates(CertificateDefinition{Name: name, Subject: subject, Type: certType, Validity: validity, SAN: san}, nil)
|
||||
if dryRun {
|
||||
fmt.Printf("Would issue %s certificate for '%s' (dry run)\n", finalDef.Type, finalDef.Subject)
|
||||
return nil
|
||||
}
|
||||
err := issueSingleCertificate(finalDef, overwrite, verbose)
|
||||
// A prototype of certificate provisioning function
|
||||
func ProvisionCertificates(filePath string, overwrite bool, dryRun bool, verbose bool) error {
|
||||
err := LoadCA()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("%s certificate and key for '%s' generated.\n", finalDef.Type, finalDef.Subject)
|
||||
if err := SaveCAState(); err != nil {
|
||||
|
||||
// Make an empty Certificates struct to hold the definitions
|
||||
certDefs := Certificates{}
|
||||
|
||||
// Load certificates provisioning configuration from the file (HCL syntax)
|
||||
err = certDefs.LoadFromFile(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error loading certificates file: %v", err)
|
||||
}
|
||||
|
||||
// The certificate provisioning file must contain at least one certificate definition
|
||||
if len(certDefs.Certificates) < 1 {
|
||||
return fmt.Errorf("No certificates defined in %s", filePath)
|
||||
}
|
||||
|
||||
// We will be counting successes and errors
|
||||
successes := 0
|
||||
errors := 0
|
||||
|
||||
// Loop through all certificate definitions
|
||||
// to render templates and fill missing fields from defaults
|
||||
for i := range certDefs.Certificates {
|
||||
// Fill missing fields from defaults, if provided
|
||||
certDefs.Certificates[i].fillDefaultValues(certDefs.Defaults)
|
||||
// Render templates in the definition using the variables map
|
||||
// with added definition name.
|
||||
variables := certDefs.Variables
|
||||
if variables == nil {
|
||||
variables = make(map[string]string)
|
||||
}
|
||||
variables["Name"] = certDefs.Certificates[i].Name
|
||||
err = certDefs.Certificates[i].RenderTemplates(variables)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to render templates for certificate %s: %v", certDefs.Certificates[i].Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// No errors so far, now we can issue certificates
|
||||
for i := range certDefs.Certificates {
|
||||
fmt.Printf("[%d/%d] Issuing %s... ", i+1, len(certDefs.Certificates), certDefs.Certificates[i].Name)
|
||||
|
||||
if dryRun {
|
||||
fmt.Printf("(dry run)\n")
|
||||
successes++
|
||||
continue
|
||||
}
|
||||
|
||||
err = issueSingleCertificate(certDefs.Certificates[i], overwrite, verbose)
|
||||
if err != nil {
|
||||
fmt.Printf("error: %v\n", err)
|
||||
errors++
|
||||
} else {
|
||||
if !verbose {
|
||||
fmt.Printf("done\n")
|
||||
}
|
||||
successes++
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Provisioning complete: %d succeeded, %d failed.\n", successes, errors)
|
||||
|
||||
err = SaveCAState()
|
||||
if err != nil {
|
||||
fmt.Printf("Error saving CA state: %v\n", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Extract defaults from certificates.hcl (now using new LoadCertificatesFile signature)
|
||||
func GetCertificateDefaults(path string) CertificateDefinition {
|
||||
_, defaults, err := LoadCertificatesFile(path)
|
||||
if err != nil || defaults == nil {
|
||||
return CertificateDefinition{}
|
||||
func IssueCertificate(certDef CertificateDefinition, overwrite bool, dryRun bool, verbose bool) error {
|
||||
err := LoadCA()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return CertificateDefinition{
|
||||
Type: defaults.Type,
|
||||
Validity: defaults.Validity,
|
||||
SAN: defaults.SAN,
|
||||
|
||||
if certDef.Subject == "" {
|
||||
certDef.Subject = certDef.Name
|
||||
}
|
||||
|
||||
// Render templates in the certificae subject and SAN fields
|
||||
variables := map[string]string{"Name": certDef.Name}
|
||||
certDef.RenderTemplates(variables)
|
||||
|
||||
if dryRun {
|
||||
fmt.Printf("Would issue %s certificate for '%s' (dry run)\n", certDef.Type, certDef.Subject)
|
||||
return nil
|
||||
}
|
||||
|
||||
err = issueSingleCertificate(certDef, overwrite, verbose)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("%s certificate and key for '%s' generated.\n", certDef.Type, certDef.Subject)
|
||||
if err := SaveCAState(); err != nil {
|
||||
fmt.Printf("Error saving CA state: %v\n", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper: check if string looks like a DN (contains at least CN=...)
|
||||
@@ -595,70 +716,6 @@ func parseDistinguishedName(dn string) pkix.Name {
|
||||
return name
|
||||
}
|
||||
|
||||
// Helper: apply Go template to a string using only the certificate label as data
|
||||
func applyTemplate(s string, name string) (string, error) {
|
||||
data := struct {
|
||||
Name string
|
||||
}{
|
||||
Name: name,
|
||||
}
|
||||
tmpl, err := template.New("").Parse(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Execute(&buf, data); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// Render all string fields in CertificateDefinition using Go templates and return a new CertificateDefinition
|
||||
func renderCertificateDefTemplates(def CertificateDefinition, defaults *CertificateDefaults) CertificateDefinition {
|
||||
newDef := def
|
||||
// Subject: use def.Subject if set, else defaults.Subject (rendered)
|
||||
if def.Subject != "" {
|
||||
if rendered, err := applyTemplate(def.Subject, def.Name); err == nil {
|
||||
newDef.Subject = rendered
|
||||
}
|
||||
} else if defaults != nil && defaults.Subject != "" {
|
||||
if rendered, err := applyTemplate(defaults.Subject, def.Name); err == nil {
|
||||
newDef.Subject = rendered
|
||||
}
|
||||
}
|
||||
// Type: use def.Type if set, else defaults.Type (no template)
|
||||
if def.Type == "" && defaults != nil && defaults.Type != "" {
|
||||
newDef.Type = defaults.Type
|
||||
}
|
||||
// Validity: use def.Validity if set, else defaults.Validity (no template)
|
||||
if def.Validity == "" && defaults != nil && defaults.Validity != "" {
|
||||
newDef.Validity = defaults.Validity
|
||||
}
|
||||
// SAN: use def.SAN if set, else defaults.SAN (rendered)
|
||||
if len(def.SAN) > 0 {
|
||||
newSAN := make([]string, len(def.SAN))
|
||||
for i, s := range def.SAN {
|
||||
if rendered, err := applyTemplate(s, def.Name); err == nil {
|
||||
newSAN[i] = rendered
|
||||
} else {
|
||||
newSAN[i] = s
|
||||
}
|
||||
}
|
||||
newDef.SAN = newSAN
|
||||
} else if defaults != nil && len(defaults.SAN) > 0 {
|
||||
newSAN := make([]string, len(defaults.SAN))
|
||||
for i, s := range defaults.SAN {
|
||||
if rendered, err := applyTemplate(s, def.Name); err == nil {
|
||||
newSAN[i] = rendered
|
||||
} else {
|
||||
newSAN[i] = s
|
||||
}
|
||||
}
|
||||
newDef.SAN = newSAN
|
||||
}
|
||||
return newDef
|
||||
}
|
||||
|
||||
// Helper: convert optional string to []string or nil
|
||||
func optionalSlice(s string) []string {
|
||||
if s == "" {
|
||||
|
Reference in New Issue
Block a user