86 lines
2.6 KiB
Go
86 lines
2.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"git.nevets.tech/Steven/certman/app"
|
|
"git.nevets.tech/Steven/certman/common"
|
|
"git.nevets.tech/Steven/certman/server"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var (
|
|
noPush bool
|
|
renewCertSubCmd = &cobra.Command{
|
|
Use: "renew",
|
|
Short: "Renews a domains certificate",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
return renewCertCmd(args[0], noPush)
|
|
},
|
|
}
|
|
)
|
|
|
|
func init() {
|
|
renewCertSubCmd.Flags().BoolVar(&noPush, "no-push", false, "Don't push certs to repo, renew locally only [server mode only]")
|
|
app.CertCmd.AddCommand(renewCertSubCmd)
|
|
}
|
|
|
|
func renewCertCmd(domain string, noPush bool) error {
|
|
if err := app.LoadConfig(); err != nil {
|
|
return err
|
|
}
|
|
if err := app.LoadDomainConfigs(); err != nil {
|
|
return err
|
|
}
|
|
mgr, err := server.NewACMEManager(app.Config())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return renewCerts(domain, noPush, mgr)
|
|
}
|
|
|
|
func renewCerts(domain string, noPush bool, mgr *server.ACMEManager) error {
|
|
config := app.Config()
|
|
domainConfig, exists := app.DomainStore().Get(domain)
|
|
if !exists {
|
|
return fmt.Errorf("domain %s does not exist", domain)
|
|
}
|
|
|
|
if _, err := mgr.RenewForDomain(domain); err != nil {
|
|
// If the domain has no stored resource yet, fall through to Obtain.
|
|
if _, err := mgr.ObtainForDomain(domain, config, domainConfig); err != nil {
|
|
return fmt.Errorf("error obtaining domain certificates for domain %s: %v", domain, err)
|
|
}
|
|
}
|
|
|
|
domainConfig.Internal.LastIssued = time.Now().UTC().Unix()
|
|
if err := app.WriteDomainConfig(domainConfig); err != nil {
|
|
return fmt.Errorf("error saving domain config %s: %v", domain, err)
|
|
}
|
|
|
|
certsDir := filepath.Join(mgr.CertsRoot, domain)
|
|
if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domain+".crt"), filepath.Join(certsDir, domain+".crt.crpt"), nil); err != nil {
|
|
return fmt.Errorf("error encrypting domain cert for domain %s: %v", domain, err)
|
|
}
|
|
if err := common.EncryptFileXChaCha(domainConfig.Certificates.CryptoKey, filepath.Join(certsDir, domain+".key"), filepath.Join(certsDir, domain+".key.crpt"), nil); err != nil {
|
|
return fmt.Errorf("error encrypting domain key for domain %s: %v", domain, err)
|
|
}
|
|
|
|
if noPush {
|
|
return nil
|
|
}
|
|
|
|
ws, err := prepareServerWorkspace(config, domainConfig, domain)
|
|
if err != nil {
|
|
return fmt.Errorf("prepare workspace for %s: %w", domain, err)
|
|
}
|
|
if err := server.AddAndPushCerts(ws, certsDir, config); err != nil {
|
|
return fmt.Errorf("push certificates for %s: %w", domain, err)
|
|
}
|
|
fmt.Printf("Successfully pushed certificates for domain %s\n", domain)
|
|
return nil
|
|
}
|