完善证书申请续期与安装初始化流程

This commit is contained in:
xuans committed 2026-08-27 00:31:40 +08:00
1 parent fd8d8608f5
commit 07636abe44
66 files changed
+9470 -165

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
package certificate
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/go-acme/lego/v5/acme"
"github.com/go-acme/lego/v5/certcrypto"
)
type AccountSecretStore interface {
Put(ctx context.Context, reference string, value map[string]string) error
Get(ctx context.Context, reference string) (map[string]string, error)
Has(ctx context.Context, reference string) (bool, error)
}
type AccountRepository struct {
store AccountSecretStore
}
func NewAccountRepository(store AccountSecretStore) *AccountRepository {
return &AccountRepository{store: store}
}
func (r *AccountRepository) LoadOrCreate(ctx context.Context, environment, email string) (*AccountUser, error) {
if r == nil || r.store == nil {
return nil, errors.New("ACME 账户存储未初始化")
}
reference, err := accountReference(environment)
if err != nil {
return nil, err
}
exists, err := r.store.Has(ctx, reference)
if err != nil {
return nil, fmt.Errorf("检查 ACME 账户失败:%w", err)
}
if !exists {
key, err := certcrypto.GeneratePrivateKey(certcrypto.EC256)
if err != nil {
return nil, fmt.Errorf("生成 ACME 账户私钥失败:%w", err)
}
user := &AccountUser{Email: strings.TrimSpace(email), PrivateKey: key}
if err := r.Save(ctx, environment, user); err != nil {
return nil, err
}
return user, nil
}
payload, err := r.store.Get(ctx, reference)
if err != nil {
return nil, fmt.Errorf("读取 ACME 账户失败:%w", err)
}
key, err := certcrypto.ParsePEMPrivateKey([]byte(payload["private_key"]))
if err != nil {
return nil, fmt.Errorf("解析 ACME 账户私钥失败:%w", err)
}
storedEmail := strings.TrimSpace(payload["email"])
if strings.TrimSpace(email) != "" {
storedEmail = strings.TrimSpace(email)
}
user := &AccountUser{Email: storedEmail, PrivateKey: key}
if value := strings.TrimSpace(payload["registration"]); value != "" {
var registration acme.ExtendedAccount
if err := json.Unmarshal([]byte(value), &registration); err != nil {
return nil, fmt.Errorf("解析 ACME 注册状态失败:%w", err)
}
user.Registration = &registration
}
return user, nil
}
func (r *AccountRepository) Save(ctx context.Context, environment string, user *AccountUser) error {
if r == nil || r.store == nil {
return errors.New("ACME 账户存储未初始化")
}
if user == nil || user.PrivateKey == nil {
return errors.New("ACME 账户私钥未配置")
}
reference, err := accountReference(environment)
if err != nil {
return err
}
payload := map[string]string{
"email": strings.TrimSpace(user.Email),
"private_key": string(certcrypto.PEMEncode(user.PrivateKey)),
}
if user.Registration != nil {
value, err := json.Marshal(user.Registration)
if err != nil {
return fmt.Errorf("编码 ACME 注册状态失败:%w", err)
}
payload["registration"] = string(value)
}
if err := r.store.Put(ctx, reference, payload); err != nil {
return fmt.Errorf("保存 ACME 账户失败:%w", err)
}
return nil
}
func accountReference(environment string) (string, error) {
environment = strings.ToLower(strings.TrimSpace(environment))
if environment != "staging" && environment != "production" {
return "", fmt.Errorf("ACME 环境无效:%s", environment)
}
return "secret://acme/letsencrypt/" + environment, nil
}
@@ -0,0 +1,79 @@
package certificate
import (
"context"
"testing"
"github.com/go-acme/lego/v5/acme"
)
type memoryAccountStore struct {
items map[string]map[string]string
}
func (s *memoryAccountStore) Put(_ context.Context, reference string, value map[string]string) error {
if s.items == nil {
s.items = map[string]map[string]string{}
}
copyValue := make(map[string]string, len(value))
for key, item := range value {
copyValue[key] = item
}
s.items[reference] = copyValue
return nil
}
func (s *memoryAccountStore) Get(_ context.Context, reference string) (map[string]string, error) {
return s.items[reference], nil
}
func (s *memoryAccountStore) Has(_ context.Context, reference string) (bool, error) {
_, ok := s.items[reference]
return ok, nil
}
func TestAccountRepositoryPersistsKeyAndRegistration(t *testing.T) {
store := &memoryAccountStore{}
repository := NewAccountRepository(store)
user, err := repository.LoadOrCreate(context.Background(), "staging", "admin@example.com")
if err != nil {
t.Fatalf("创建 ACME 账户失败:%v", err)
}
if user.PrivateKey == nil {
t.Fatal("ACME 账户私钥未生成")
}
user.Registration = &acme.ExtendedAccount{
Account: acme.Account{Status: acme.StatusValid, TermsOfServiceAgreed: true},
Location: "https://acme.example.test/account/1",
}
if err := repository.Save(context.Background(), "staging", user); err != nil {
t.Fatalf("保存 ACME 账户失败:%v", err)
}
loaded, err := repository.LoadOrCreate(context.Background(), "staging", "")
if err != nil {
t.Fatalf("重新读取 ACME 账户失败:%v", err)
}
if loaded.Email != "admin@example.com" {
t.Fatalf("ACME 账户邮箱错误:%s", loaded.Email)
}
if loaded.Registration == nil || loaded.Registration.Location != user.Registration.Location {
t.Fatalf("ACME 注册状态未持久化:%+v", loaded.Registration)
}
if loaded.PrivateKey == nil {
t.Fatal("ACME 账户私钥未恢复")
}
}
func TestAccountRepositorySeparatesEnvironments(t *testing.T) {
store := &memoryAccountStore{}
repository := NewAccountRepository(store)
if _, err := repository.LoadOrCreate(context.Background(), "staging", ""); err != nil {
t.Fatal(err)
}
if _, err := repository.LoadOrCreate(context.Background(), "production", ""); err != nil {
t.Fatal(err)
}
if len(store.items) != 2 {
t.Fatalf("测试环境与生产环境应使用独立账户:%d", len(store.items))
}
}
+104
View File
@@ -0,0 +1,104 @@
package certificate
import (
"context"
"crypto"
"errors"
"fmt"
"net/http"
"strings"
"time"
acme "github.com/go-acme/lego/v5/acme"
"github.com/go-acme/lego/v5/certcrypto"
legoCertificate "github.com/go-acme/lego/v5/certificate"
"github.com/go-acme/lego/v5/challenge"
lego "github.com/go-acme/lego/v5/lego"
"github.com/go-acme/lego/v5/registration"
)
type AccountUser struct {
Email string
PrivateKey crypto.Signer
Registration *acme.ExtendedAccount
}
func (u *AccountUser) GetEmail() string { return u.Email }
func (u *AccountUser) GetRegistration() *acme.ExtendedAccount { return u.Registration }
func (u *AccountUser) GetPrivateKey() crypto.Signer { return u.PrivateKey }
type LegoIssuer struct {
User *AccountUser
Provider challenge.Provider
Environment string
HTTPClient *http.Client
Now func() time.Time
}
func (i *LegoIssuer) Obtain(ctx context.Context, request ObtainRequest) (Resource, error) {
if i == nil || i.User == nil || i.User.PrivateKey == nil {
return Resource{}, errors.New("ACME 账户未配置")
}
if i.Provider == nil {
return Resource{}, errors.New("DNS 验证服务商未配置")
}
domains, err := NormalizeDomains(request.Domains)
if err != nil {
return Resource{}, err
}
environment := strings.ToLower(strings.TrimSpace(request.Environment))
if environment == "" {
environment = "production"
}
caURL := lego.DirectoryURLLetsEncrypt
if environment == "staging" {
caURL = lego.DirectoryURLLetsEncryptStaging
} else if environment != "production" {
return Resource{}, fmt.Errorf("ACME 环境无效:%s", environment)
}
clientConfig := lego.NewConfig(i.User)
clientConfig.CADirURL = caURL
clientConfig.UserAgent = "Scert/0.1"
if i.HTTPClient != nil {
clientConfig.HTTPClient = i.HTTPClient
}
client, err := lego.NewClient(clientConfig)
if err != nil {
return Resource{}, fmt.Errorf("创建 ACME 客户端失败:%w", err)
}
if err := client.Challenge.SetDNS01Provider(i.Provider); err != nil {
return Resource{}, fmt.Errorf("配置 DNS-01 验证失败:%w", err)
}
if i.User.Registration == nil {
account, err := client.Registration.Register(ctx, registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
return Resource{}, fmt.Errorf("注册 ACME 账户失败:%w", err)
}
i.User.Registration = account
}
issued, err := client.Certificate.Obtain(ctx, legoCertificate.ObtainRequest{
Domains: domains, EmailAddresses: nonEmptyEmail(request.AccountEmail, i.User.Email),
KeyType: certcrypto.RSA2048, Bundle: true,
PreferredChain: request.PreferredChain,
})
if err != nil {
return Resource{}, fmt.Errorf("申请证书失败:%w", err)
}
resource := Resource{
Domains: issued.Domains, Certificate: issued.Certificate,
IssuerCertificate: issued.IssuerCertificate, PrivateKey: issued.PrivateKey,
}
if i.Now != nil {
_ = i.Now()
}
return ValidateResource(resource)
}
func nonEmptyEmail(values ...string) []string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return []string{strings.TrimSpace(value)}
}
}
return nil
}
+330
View File
@@ -0,0 +1,330 @@
package certificate
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
type Issuer interface {
Obtain(ctx context.Context, request ObtainRequest) (Resource, error)
}
type ObtainRequest struct {
Domains []string
AccountEmail string
Environment string
PreferredChain string
}
type Resource struct {
Domains []string
Certificate []byte
IssuerCertificate []byte
PrivateKey []byte
NotBefore time.Time
NotAfter time.Time
}
type SavedResource struct {
Domain string `json:"domain"`
Directory string `json:"directory"`
CertificatePath string `json:"certificate_path"`
FullChainPath string `json:"fullchain_path"`
PrivateKeyPath string `json:"private_key_path"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
BackupDirectory string `json:"backup_directory,omitempty"`
}
type FileStore struct {
Root string
BackupRoot string
Now func() time.Time
}
func NormalizeDomains(domains []string) ([]string, error) {
seen := make(map[string]struct{}, len(domains))
result := make([]string, 0, len(domains))
for _, value := range domains {
value = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
if value == "" {
continue
}
if strings.HasPrefix(value, "*.") {
value = "*." + strings.TrimPrefix(value, "*.")
}
if !validDomain(value) {
return nil, fmt.Errorf("证书域名无效:%s", value)
}
if _, exists := seen[value]; exists {
continue
}
seen[value] = struct{}{}
result = append(result, value)
}
if len(result) == 0 {
return nil, errors.New("证书域名不能为空")
}
sort.Strings(result)
return result, nil
}
func ValidateResource(resource Resource) (Resource, error) {
if len(resource.Certificate) == 0 || len(resource.PrivateKey) == 0 {
return Resource{}, errors.New("证书和私钥不能为空")
}
certificate, err := parseLeafCertificate(resource.Certificate)
if err != nil {
return Resource{}, fmt.Errorf("解析证书失败:%w", err)
}
if _, err := tls.X509KeyPair(resource.Certificate, resource.PrivateKey); err != nil {
return Resource{}, fmt.Errorf("证书与私钥不匹配:%w", err)
}
domains, err := NormalizeDomains(resource.Domains)
if err != nil {
return Resource{}, err
}
if resource.NotBefore.IsZero() {
resource.NotBefore = certificate.NotBefore
}
if resource.NotAfter.IsZero() {
resource.NotAfter = certificate.NotAfter
}
if !resource.NotAfter.After(resource.NotBefore) {
return Resource{}, errors.New("证书有效期无效")
}
resource.Domains = domains
if len(resource.IssuerCertificate) > 0 {
if _, err := parseLeafCertificate(resource.IssuerCertificate); err != nil {
return Resource{}, fmt.Errorf("解析签发者证书失败:%w", err)
}
}
return resource, nil
}
// ValidateResourceForDomains 校验证书内容,并确认叶子证书覆盖全部申请域名。
func ValidateResourceForDomains(resource Resource, expected []string) (Resource, error) {
resource, err := ValidateResource(resource)
if err != nil {
return Resource{}, err
}
wanted, err := NormalizeDomains(expected)
if err != nil {
return Resource{}, err
}
leaf, err := parseLeafCertificate(resource.Certificate)
if err != nil {
return Resource{}, fmt.Errorf("解析证书失败:%w", err)
}
now := time.Now().UTC()
if now.Before(leaf.NotBefore) {
return Resource{}, fmt.Errorf("证书尚未生效:%s", leaf.NotBefore.UTC().Format(time.RFC3339))
}
if !now.Before(leaf.NotAfter) {
return Resource{}, fmt.Errorf("证书已经过期:%s", leaf.NotAfter.UTC().Format(time.RFC3339))
}
for _, name := range wanted {
probe := name
if strings.HasPrefix(probe, "*.") {
probe = "scert-wildcard-probe." + strings.TrimPrefix(probe, "*.")
}
if err := leaf.VerifyHostname(probe); err != nil {
return Resource{}, fmt.Errorf("证书不覆盖域名 %s:%w", name, err)
}
}
return resource, nil
}
func (s FileStore) Save(ctx context.Context, domain string, resource Resource) (SavedResource, error) {
if err := ctx.Err(); err != nil {
return SavedResource{}, err
}
resource, err := ValidateResource(resource)
if err != nil {
return SavedResource{}, err
}
primary := strings.TrimSpace(domain)
if primary == "" {
primary = resource.Domains[0]
}
if _, err := NormalizeDomains([]string{primary}); err != nil {
return SavedResource{}, err
}
root := filepath.Clean(strings.TrimSpace(s.Root))
if root == "." || root == "" {
return SavedResource{}, errors.New("证书存储根目录不能为空")
}
directory := filepath.Join(root, directoryName(primary))
if err := os.MkdirAll(directory, 0o700); err != nil {
return SavedResource{}, fmt.Errorf("创建证书目录失败:%w", err)
}
backupDirectory, err := s.backupExisting(directory, primary)
if err != nil {
return SavedResource{}, err
}
certificatePath := filepath.Join(directory, "cert.pem")
fullChainPath := filepath.Join(directory, "fullchain.pem")
privateKeyPath := filepath.Join(directory, "key.pem")
fullChain := resource.Certificate
if len(resource.IssuerCertificate) > 0 && !bytes.Contains(resource.Certificate, resource.IssuerCertificate) {
fullChain = append(append([]byte(nil), resource.Certificate...), resource.IssuerCertificate...)
}
if err := atomicWrite(certificatePath, resource.Certificate, 0o644); err != nil {
return SavedResource{}, fmt.Errorf("保存证书失败:%w", err)
}
if err := atomicWrite(fullChainPath, fullChain, 0o644); err != nil {
return SavedResource{}, fmt.Errorf("保存完整证书链失败:%w", err)
}
if err := atomicWrite(privateKeyPath, resource.PrivateKey, 0o600); err != nil {
return SavedResource{}, fmt.Errorf("保存私钥失败:%w", err)
}
result := SavedResource{
Domain: primary, Directory: directory, CertificatePath: certificatePath,
FullChainPath: fullChainPath, PrivateKeyPath: privateKeyPath,
NotBefore: resource.NotBefore, NotAfter: resource.NotAfter,
BackupDirectory: backupDirectory,
}
metadata, err := json.MarshalIndent(result, "", " ")
if err != nil {
return SavedResource{}, fmt.Errorf("生成证书元数据失败:%w", err)
}
if err := atomicWrite(filepath.Join(directory, "metadata.json"), metadata, 0o600); err != nil {
return SavedResource{}, fmt.Errorf("保存证书元数据失败:%w", err)
}
return result, nil
}
func (s FileStore) backupExisting(directory, domain string) (string, error) {
entries, err := os.ReadDir(directory)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
return "", fmt.Errorf("读取原证书目录失败:%w", err)
}
if len(entries) == 0 {
return "", nil
}
backupRoot := filepath.Clean(strings.TrimSpace(s.BackupRoot))
if backupRoot == "." || backupRoot == "" {
return "", errors.New("证书备份根目录不能为空")
}
now := time.Now
if s.Now != nil {
now = s.Now
}
backupDirectory := filepath.Join(backupRoot, directoryName(domain), now().UTC().Format("20060102-150405.000000000"))
if err := os.MkdirAll(filepath.Dir(backupDirectory), 0o700); err != nil {
return "", fmt.Errorf("创建证书备份目录失败:%w", err)
}
if err := copyDirectory(directory, backupDirectory); err != nil {
return "", fmt.Errorf("备份原证书失败:%w", err)
}
return backupDirectory, nil
}
func atomicWrite(path string, data []byte, mode os.FileMode) error {
temporary, err := os.CreateTemp(filepath.Dir(path), ".scert-*")
if err != nil {
return err
}
temporaryName := temporary.Name()
defer os.Remove(temporaryName)
if err := temporary.Chmod(mode); err != nil {
_ = temporary.Close()
return err
}
if _, err := temporary.Write(data); err != nil {
_ = temporary.Close()
return err
}
if err := temporary.Sync(); err != nil {
_ = temporary.Close()
return err
}
if err := temporary.Close(); err != nil {
return err
}
if runtime.GOOS == "windows" {
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
}
return os.Rename(temporaryName, path)
}
func copyDirectory(source, target string) error {
entries, err := os.ReadDir(source)
if err != nil {
return err
}
if err := os.MkdirAll(target, 0o700); err != nil {
return err
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
data, err := os.ReadFile(filepath.Join(source, entry.Name()))
if err != nil {
return err
}
if err := atomicWrite(filepath.Join(target, entry.Name()), data, 0o600); err != nil {
return err
}
}
return nil
}
func parseLeafCertificate(data []byte) (*x509.Certificate, error) {
remaining := data
for len(remaining) > 0 {
block, rest := pem.Decode(remaining)
if block == nil {
break
}
remaining = rest
if block.Type != "CERTIFICATE" {
continue
}
return x509.ParseCertificate(block.Bytes)
}
return nil, errors.New("未找到 PEM 证书")
}
func directoryName(domain string) string {
name := strings.ToLower(strings.TrimSpace(domain))
name = strings.ReplaceAll(name, "*.", "_wildcard.")
name = strings.ReplaceAll(name, string(filepath.Separator), "_")
return name
}
func validDomain(value string) bool {
value = strings.TrimPrefix(value, "*.")
if len(value) < 3 || len(value) > 253 || !strings.Contains(value, ".") {
return false
}
for _, label := range strings.Split(value, ".") {
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
return false
}
for _, r := range label {
if !(r == '-' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9') {
return false
}
}
}
return true
}
@@ -0,0 +1,103 @@
package certificate
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
func TestNormalizeDomainsSupportsSANAndWildcard(t *testing.T) {
got, err := NormalizeDomains([]string{"Example.COM.", "*.example.com", "example.com"})
if err != nil {
t.Fatalf("规范化域名失败:%v", err)
}
if len(got) != 2 || got[0] != "*.example.com" || got[1] != "example.com" {
t.Fatalf("规范化结果错误:%v", got)
}
}
func TestFileStoreSaveBacksUpAndKeepsKeyRestricted(t *testing.T) {
root := t.TempDir()
store := FileStore{Root: filepath.Join(root, "ssl"), BackupRoot: filepath.Join(root, "backups"), Now: func() time.Time { return time.Date(2026, 8, 26, 10, 0, 0, 0, time.UTC) }}
resource := testResource(t, "example.com")
first, err := store.Save(context.Background(), "example.com", resource)
if err != nil {
t.Fatalf("第一次保存失败:%v", err)
}
if first.BackupDirectory != "" {
t.Fatal("第一次保存不应生成备份")
}
resource.Certificate = append([]byte(nil), resource.Certificate...)
second, err := store.Save(context.Background(), "example.com", resource)
if err != nil {
t.Fatalf("第二次保存失败:%v", err)
}
if second.BackupDirectory == "" {
t.Fatal("替换已有证书时应生成备份")
}
if _, err := os.Stat(second.FullChainPath); err != nil {
t.Fatalf("完整证书链不存在:%v", err)
}
if info, err := os.Stat(second.PrivateKeyPath); err != nil {
t.Fatalf("私钥不存在:%v", err)
} else if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 {
t.Fatalf("私钥权限错误:%o", info.Mode().Perm())
}
}
func TestValidateResourceRejectsMismatchedKey(t *testing.T) {
resource := testResource(t, "example.com")
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
resource.PrivateKey = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
if _, err := ValidateResource(resource); err == nil {
t.Fatal("证书与私钥不匹配时应失败")
}
}
func TestValidateResourceForDomainsSupportsWildcard(t *testing.T) {
resource := testResourceForWildcard(t, "*.example.com")
if _, err := ValidateResourceForDomains(resource, []string{"*.example.com"}); err != nil {
t.Fatalf("泛域名证书覆盖校验失败:%v", err)
}
}
func testResource(t *testing.T, name string) Resource {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, DNSNames: []string{name}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(90 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return Resource{Domains: []string{name}, Certificate: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})}
}
func testResourceForWildcard(t *testing.T, name string) Resource {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
template := &x509.Certificate{SerialNumber: big.NewInt(3), Subject: pkix.Name{CommonName: name}, DNSNames: []string{name}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(90 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return Resource{Domains: []string{name}, Certificate: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})}
}
+111
View File
@@ -0,0 +1,111 @@
package certificate
import (
"context"
"errors"
"fmt"
"sync"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
type DomainLister interface {
List(ctx context.Context) ([]domain.Domain, error)
}
type CertificateIssuer interface {
Issue(ctx context.Context, domainID string) (IssueResult, error)
}
type RenewalScheduler struct {
lister DomainLister
issuer CertificateIssuer
threshold time.Duration
now func() time.Time
interval time.Duration
mu sync.Mutex
runMu sync.Mutex
running bool
}
type RenewalReport struct {
Checked int `json:"checked"`
Selected int `json:"selected"`
Succeeded int `json:"succeeded"`
Failed int `json:"failed"`
Errors []string `json:"errors,omitempty"`
}
func NewRenewalScheduler(lister DomainLister, issuer CertificateIssuer, thresholdDays int) *RenewalScheduler {
if thresholdDays < 1 {
thresholdDays = 6
}
return &RenewalScheduler{
lister: lister, issuer: issuer, threshold: time.Duration(thresholdDays) * 24 * time.Hour,
now: time.Now, interval: 24 * time.Hour,
}
}
func (s *RenewalScheduler) RunOnce(ctx context.Context) (RenewalReport, error) {
if s == nil || s.lister == nil || s.issuer == nil {
return RenewalReport{}, errors.New("自动续期服务未初始化")
}
if !s.runMu.TryLock() {
return RenewalReport{}, errors.New("自动续期任务正在执行")
}
defer s.runMu.Unlock()
items, err := s.lister.List(ctx)
if err != nil {
return RenewalReport{}, fmt.Errorf("查询续期域名失败:%w", err)
}
report := RenewalReport{Checked: len(items)}
now := s.now().UTC()
for _, item := range items {
if !item.AutoRenew || item.Status == "issuing" {
continue
}
if item.ExpiresAt != nil && item.ExpiresAt.Sub(now) > s.threshold {
continue
}
report.Selected++
if _, err := s.issuer.Issue(ctx, item.ID); err != nil {
report.Failed++
report.Errors = append(report.Errors, fmt.Sprintf("%s:%v", item.Name, err))
continue
}
report.Succeeded++
}
return report, nil
}
func (s *RenewalScheduler) Start(ctx context.Context) {
if s == nil {
return
}
s.mu.Lock()
if s.running {
s.mu.Unlock()
return
}
s.running = true
s.mu.Unlock()
go func() {
defer func() {
s.mu.Lock()
s.running = false
s.mu.Unlock()
}()
_, _ = s.RunOnce(ctx)
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_, _ = s.RunOnce(ctx)
}
}
}()
}
@@ -0,0 +1,66 @@
package certificate
import (
"context"
"errors"
"testing"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
type renewalLister struct {
items []domain.Domain
err error
}
func (r renewalLister) List(context.Context) ([]domain.Domain, error) { return r.items, r.err }
type renewalService struct {
ids []string
err error
}
func (s *renewalService) Issue(_ context.Context, id string) (IssueResult, error) {
s.ids = append(s.ids, id)
return IssueResult{}, s.err
}
func TestRenewalSchedulerSelectsOnlyExpiringAutoRenewDomains(t *testing.T) {
now := time.Date(2026, 8, 26, 0, 0, 0, 0, time.UTC)
soon := now.Add(2 * 24 * time.Hour)
later := now.Add(20 * 24 * time.Hour)
items := []domain.Domain{
{ID: "soon", Name: "soon.example.com", AutoRenew: true, ExpiresAt: &soon},
{ID: "later", Name: "later.example.com", AutoRenew: true, ExpiresAt: &later},
{ID: "disabled", Name: "disabled.example.com", AutoRenew: false, ExpiresAt: &soon},
{ID: "missing", Name: "missing.example.com", AutoRenew: true},
}
service := &renewalService{}
scheduler := NewRenewalScheduler(renewalLister{items: items}, service, 6)
scheduler.now = func() time.Time { return now }
report, err := scheduler.RunOnce(context.Background())
if err != nil {
t.Fatal(err)
}
if report.Checked != 4 || report.Selected != 2 || report.Succeeded != 2 || report.Failed != 0 {
t.Fatalf("续期筛选结果错误:%+v", report)
}
if len(service.ids) != 2 || service.ids[0] != "soon" || service.ids[1] != "missing" {
t.Fatalf("续期执行域名错误:%v", service.ids)
}
}
func TestRenewalSchedulerReportsFailures(t *testing.T) {
now := time.Now().UTC()
expires := now.Add(time.Hour)
item := domain.Domain{ID: "one", Name: "one.example.com", AutoRenew: true, ExpiresAt: &expires}
scheduler := NewRenewalScheduler(renewalLister{items: []domain.Domain{item}}, &renewalService{err: errors.New("模拟续期失败")}, 6)
report, err := scheduler.RunOnce(context.Background())
if err != nil {
t.Fatal(err)
}
if report.Failed != 1 || len(report.Errors) != 1 {
t.Fatalf("续期失败结果错误:%+v", report)
}
}
+231
View File
@@ -0,0 +1,231 @@
package certificate
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/go-acme/lego/v5/challenge"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
type DomainStateRepository interface {
GetByID(ctx context.Context, id string) (domain.Domain, error)
UpdateCertificateState(ctx context.Context, id, status string, expiresAt *time.Time) error
}
type CredentialReader interface {
Get(ctx context.Context, reference string) (map[string]string, error)
}
type ProviderFactory interface {
Create(providerID string, credentials map[string]string) (challenge.Provider, error)
}
type AccountManager interface {
LoadOrCreate(ctx context.Context, environment, email string) (*AccountUser, error)
Save(ctx context.Context, environment string, user *AccountUser) error
}
type IssuerFactory func(user *AccountUser, provider challenge.Provider, environment string) Issuer
type Service struct {
config config.Config
repository DomainStateRepository
credentials CredentialReader
providers ProviderFactory
accounts AccountManager
store FileStore
newIssuer IssuerFactory
preferredChain string
}
type IssueResult struct {
DomainID string `json:"domain_id"`
Domains []string `json:"domains"`
Saved SavedResource `json:"saved"`
}
type ImportRequest struct {
DomainID string
Certificate string
PrivateKey string
IssuerBundle string
}
func NewService(cfg config.Config, repository DomainStateRepository, credentials CredentialReader, providers ProviderFactory, accounts AccountManager) *Service {
return &Service{
config: cfg, repository: repository, credentials: credentials, providers: providers, accounts: accounts,
store: FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup},
newIssuer: func(user *AccountUser, provider challenge.Provider, environment string) Issuer {
return &LegoIssuer{User: user, Provider: provider, Environment: environment}
},
}
}
func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, error) {
if s == nil || s.repository == nil || s.credentials == nil || s.providers == nil || s.accounts == nil || s.newIssuer == nil {
return IssueResult{}, errors.New("证书申请服务未初始化")
}
domainID = strings.TrimSpace(domainID)
if domainID == "" {
return IssueResult{}, errors.New("域名 ID 不能为空")
}
item, err := s.repository.GetByID(ctx, domainID)
if err != nil {
return IssueResult{}, fmt.Errorf("读取域名配置失败:%w", err)
}
domains, err := requestedDomains(item)
if err != nil {
return IssueResult{}, err
}
providerID := strings.ToLower(strings.TrimSpace(item.DNSProvider))
if providerID == "" {
providerID = strings.ToLower(strings.TrimSpace(s.config.DNS.Provider))
}
if providerID == "" || strings.TrimSpace(s.config.DNS.CredentialRef) == "" {
return IssueResult{}, errors.New("DNS Provider 或凭据引用未配置")
}
if configured := strings.ToLower(strings.TrimSpace(s.config.DNS.Provider)); configured != "" && providerID != configured {
return IssueResult{}, fmt.Errorf("域名配置的 DNS Provider %s 尚未绑定独立凭据,当前初始化凭据属于 %s", providerID, configured)
}
if s.config.DNS.VerificationState != "verified" {
return IssueResult{}, errors.New("DNS API 尚未通过验证")
}
if err := s.repository.UpdateCertificateState(ctx, item.ID, "issuing", item.ExpiresAt); err != nil {
return IssueResult{}, fmt.Errorf("更新证书申请状态失败:%w", err)
}
fail := func(cause error) (IssueResult, error) {
if stateErr := s.repository.UpdateCertificateState(context.Background(), item.ID, "failed", item.ExpiresAt); stateErr != nil {
return IssueResult{}, fmt.Errorf("%v;更新失败状态时发生错误:%w", cause, stateErr)
}
return IssueResult{}, cause
}
credentials, err := s.credentials.Get(ctx, s.config.DNS.CredentialRef)
if err != nil {
return fail(fmt.Errorf("读取 DNS 凭据失败:%w", err))
}
provider, err := s.providers.Create(providerID, credentials)
if err != nil {
return fail(fmt.Errorf("创建 DNS Provider 失败:%w", err))
}
email := strings.TrimSpace(s.config.ACME.AccountEmail)
if email == "" && len(s.config.Notification.Recipients) > 0 {
email = strings.TrimSpace(s.config.Notification.Recipients[0])
}
user, err := s.accounts.LoadOrCreate(ctx, item.ACMEEnvironment, email)
if err != nil {
return fail(err)
}
issuer := s.newIssuer(user, provider, item.ACMEEnvironment)
resource, issueErr := issuer.Obtain(ctx, ObtainRequest{
Domains: domains, AccountEmail: email, Environment: item.ACMEEnvironment, PreferredChain: s.preferredChain,
})
if saveErr := s.accounts.Save(ctx, item.ACMEEnvironment, user); saveErr != nil {
if issueErr != nil {
return fail(fmt.Errorf("%v;保存 ACME 账户状态失败:%w", issueErr, saveErr))
}
return fail(saveErr)
}
if issueErr != nil {
return fail(issueErr)
}
resource, err = ValidateResourceForDomains(resource, domains)
if err != nil {
return fail(err)
}
saved, err := s.store.Save(ctx, item.Name, resource)
if err != nil {
return fail(fmt.Errorf("保存证书文件失败:%w", err))
}
if err := s.repository.UpdateCertificateState(ctx, item.ID, "valid", &saved.NotAfter); err != nil {
return IssueResult{}, fmt.Errorf("证书已保存,但更新域名状态失败:%w", err)
}
return IssueResult{DomainID: item.ID, Domains: domains, Saved: saved}, nil
}
func (s *Service) Import(ctx context.Context, request ImportRequest) (IssueResult, error) {
if s == nil || s.repository == nil {
return IssueResult{}, errors.New("证书导入服务未初始化")
}
item, err := s.repository.GetByID(ctx, strings.TrimSpace(request.DomainID))
if err != nil {
return IssueResult{}, fmt.Errorf("读取域名配置失败:%w", err)
}
certificatePath, err := cleanInputPath(request.Certificate, "证书文件")
if err != nil {
return IssueResult{}, err
}
privateKeyPath, err := cleanInputPath(request.PrivateKey, "私钥文件")
if err != nil {
return IssueResult{}, err
}
certificateData, err := os.ReadFile(certificatePath)
if err != nil {
return IssueResult{}, fmt.Errorf("读取证书文件失败:%w", err)
}
privateKeyData, err := os.ReadFile(privateKeyPath)
if err != nil {
return IssueResult{}, fmt.Errorf("读取私钥文件失败:%w", err)
}
var issuerData []byte
if strings.TrimSpace(request.IssuerBundle) != "" {
issuerPath, err := cleanInputPath(request.IssuerBundle, "签发者证书文件")
if err != nil {
return IssueResult{}, err
}
issuerData, err = os.ReadFile(issuerPath)
if err != nil {
return IssueResult{}, fmt.Errorf("读取签发者证书文件失败:%w", err)
}
}
domains := requestedDomainsForImport(item)
resource, err := ValidateResourceForDomains(Resource{
Domains: domains, Certificate: certificateData, IssuerCertificate: issuerData, PrivateKey: privateKeyData,
}, domains)
if err != nil {
return IssueResult{}, err
}
saved, err := s.store.Save(ctx, item.Name, resource)
if err != nil {
return IssueResult{}, fmt.Errorf("保存导入证书失败:%w", err)
}
if err := s.repository.UpdateCertificateState(ctx, item.ID, "valid", &saved.NotAfter); err != nil {
return IssueResult{}, fmt.Errorf("证书已保存,但更新域名状态失败:%w", err)
}
return IssueResult{DomainID: item.ID, Domains: resource.Domains, Saved: saved}, nil
}
func cleanInputPath(value, label string) (string, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s不能为空", label)
}
path := filepath.Clean(value)
if path == "." {
return "", fmt.Errorf("%s路径无效", label)
}
return path, nil
}
func requestedDomainsForImport(item domain.Domain) []string {
if item.CertificateType == domain.CertificateSAN && len(item.SANs) > 0 {
return item.SANs
}
return []string{item.Name}
}
func requestedDomains(item domain.Domain) ([]string, error) {
values := item.SANs
if item.CertificateType != domain.CertificateSAN {
values = []string{item.Name}
}
return NormalizeDomains(values)
}
@@ -0,0 +1,234 @@
package certificate
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
"os"
"path/filepath"
"testing"
"time"
"github.com/go-acme/lego/v5/challenge"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
type serviceRepository struct {
item domain.Domain
states []string
}
func (r *serviceRepository) GetByID(_ context.Context, _ string) (domain.Domain, error) {
return r.item, nil
}
func (r *serviceRepository) UpdateCertificateState(_ context.Context, _ string, status string, expiresAt *time.Time) error {
r.states = append(r.states, status)
r.item.Status = status
r.item.ExpiresAt = expiresAt
return nil
}
type serviceCredentials struct{}
func (serviceCredentials) Get(context.Context, string) (map[string]string, error) {
return map[string]string{"api_token": "test-token"}, nil
}
type serviceProvider struct{}
func (serviceProvider) Present(context.Context, string, string, string) error { return nil }
func (serviceProvider) CleanUp(context.Context, string, string, string) error { return nil }
type serviceProviderFactory struct{}
func (serviceProviderFactory) Create(string, map[string]string) (challenge.Provider, error) {
return serviceProvider{}, nil
}
type serviceAccounts struct{}
func (serviceAccounts) LoadOrCreate(context.Context, string, string) (*AccountUser, error) {
return &AccountUser{}, nil
}
func (serviceAccounts) Save(context.Context, string, *AccountUser) error { return nil }
type serviceIssuer struct {
request ObtainRequest
resource Resource
err error
}
func (i *serviceIssuer) Obtain(_ context.Context, request ObtainRequest) (Resource, error) {
i.request = request
return i.resource, i.err
}
func TestServiceIssuesSANCertificateAndUpdatesState(t *testing.T) {
root := t.TempDir()
cfg := certificateTestConfig(root)
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSAN, []string{"example.com", "www.example.com"}, true, domain.ACMEEnvironmentStaging, "cloudflare")
if err != nil {
t.Fatal(err)
}
repository := &serviceRepository{item: item}
issuer := &serviceIssuer{resource: testResourceForDomains(t, []string{"example.com", "www.example.com"})}
service := NewService(cfg, repository, serviceCredentials{}, serviceProviderFactory{}, serviceAccounts{})
service.newIssuer = func(*AccountUser, challenge.Provider, string) Issuer { return issuer }
result, err := service.Issue(context.Background(), item.ID)
if err != nil {
t.Fatalf("申请 SAN 证书失败:%v", err)
}
if len(issuer.request.Domains) != 2 {
t.Fatalf("SAN 申请域名错误:%v", issuer.request.Domains)
}
if len(repository.states) != 2 || repository.states[0] != "issuing" || repository.states[1] != "valid" {
t.Fatalf("证书状态流转错误:%v", repository.states)
}
if _, err := os.Stat(result.Saved.PrivateKeyPath); err != nil {
t.Fatalf("证书私钥未保存:%v", err)
}
}
func TestServiceFailureKeepsExistingCertificate(t *testing.T) {
root := t.TempDir()
cfg := certificateTestConfig(root)
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare")
if err != nil {
t.Fatal(err)
}
oldExpiry := time.Now().UTC().Add(10 * 24 * time.Hour)
item.ExpiresAt = &oldExpiry
store := FileStore{Root: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup}
oldResource := testResource(t, "example.com")
saved, err := store.Save(context.Background(), item.Name, oldResource)
if err != nil {
t.Fatal(err)
}
before, err := os.ReadFile(saved.CertificatePath)
if err != nil {
t.Fatal(err)
}
repository := &serviceRepository{item: item}
issuer := &serviceIssuer{err: errors.New("模拟 ACME 申请失败")}
service := NewService(cfg, repository, serviceCredentials{}, serviceProviderFactory{}, serviceAccounts{})
service.newIssuer = func(*AccountUser, challenge.Provider, string) Issuer { return issuer }
if _, err := service.Issue(context.Background(), item.ID); err == nil {
t.Fatal("ACME 申请失败时应返回错误")
}
after, err := os.ReadFile(saved.CertificatePath)
if err != nil {
t.Fatal(err)
}
if string(after) != string(before) {
t.Fatal("申请失败时不应覆盖现有证书")
}
if len(repository.states) != 2 || repository.states[1] != "failed" {
t.Fatalf("失败状态未正确记录:%v", repository.states)
}
if repository.item.ExpiresAt == nil || !repository.item.ExpiresAt.Equal(oldExpiry) {
t.Fatal("申请失败时应保留原证书到期时间")
}
}
func TestServiceImportsOwnedCertificate(t *testing.T) {
root := t.TempDir()
cfg := certificateTestConfig(root)
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSAN, []string{"example.com", "api.example.com"}, true, domain.ACMEEnvironmentStaging, "cloudflare")
if err != nil {
t.Fatal(err)
}
resource := testResourceForDomains(t, []string{"example.com", "api.example.com"})
certificatePath := filepath.Join(root, "owned-cert.pem")
privateKeyPath := filepath.Join(root, "owned-key.pem")
if err := os.WriteFile(certificatePath, resource.Certificate, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(privateKeyPath, resource.PrivateKey, 0o600); err != nil {
t.Fatal(err)
}
repository := &serviceRepository{item: item}
service := NewService(cfg, repository, nil, nil, nil)
result, err := service.Import(context.Background(), ImportRequest{
DomainID: item.ID, Certificate: certificatePath, PrivateKey: privateKeyPath,
})
if err != nil {
t.Fatalf("导入自有证书失败:%v", err)
}
if len(result.Domains) != 2 || repository.item.Status != "valid" {
t.Fatalf("导入结果错误:%+v,状态:%s", result, repository.item.Status)
}
if _, err := os.Stat(result.Saved.FullChainPath); err != nil {
t.Fatalf("导入证书未保存:%v", err)
}
}
func TestServiceRejectsOwnedCertificateForWrongDomain(t *testing.T) {
root := t.TempDir()
cfg := certificateTestConfig(root)
item, err := domain.NewDomainWithOptions("example.com", domain.CertificateSingle, nil, true, domain.ACMEEnvironmentStaging, "cloudflare")
if err != nil {
t.Fatal(err)
}
resource := testResource(t, "other.example.com")
certificatePath := filepath.Join(root, "wrong-cert.pem")
privateKeyPath := filepath.Join(root, "wrong-key.pem")
if err := os.WriteFile(certificatePath, resource.Certificate, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(privateKeyPath, resource.PrivateKey, 0o600); err != nil {
t.Fatal(err)
}
service := NewService(cfg, &serviceRepository{item: item}, nil, nil, nil)
if _, err := service.Import(context.Background(), ImportRequest{
DomainID: item.ID, Certificate: certificatePath, PrivateKey: privateKeyPath,
}); err == nil {
t.Fatal("证书不覆盖托管域名时应拒绝导入")
}
if _, err := os.Stat(filepath.Join(cfg.Paths.Certificate, "example.com", "cert.pem")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("导入失败时不应写入证书:%v", err)
}
}
func certificateTestConfig(root string) config.Config {
cfg := config.Default(root)
cfg.Paths.Certificate = filepath.Join(root, "ssl")
cfg.Paths.Backup = filepath.Join(root, "backups")
cfg.DNS.Provider = "cloudflare"
cfg.DNS.CredentialRef = "secret://dns/cloudflare/test"
cfg.DNS.VerificationState = "verified"
cfg.Notification.Recipients = []string{"admin@example.com"}
return cfg
}
func testResourceForDomains(t *testing.T, names []string) Resource {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
template := &x509.Certificate{
SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: names[0]}, DNSNames: names,
NotBefore: now.Add(-time.Minute), NotAfter: now.Add(90 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return Resource{
Domains: names, Certificate: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}),
}
}