完善证书管理与邮件通知流程
This commit is contained in:
1 parent
c74372284a
commit
b2833b761d
60 files changed
+7340
-254
No files matched your search
@@ -3,6 +3,7 @@ package certificate
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
@@ -38,14 +39,20 @@ type Resource struct {
|
||||
}
|
||||
|
||||
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"`
|
||||
Domain string `json:"domain"`
|
||||
CertificateType string `json:"certificate_type,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
SANs []string `json:"sans,omitempty"`
|
||||
SerialNumber string `json:"serial_number,omitempty"`
|
||||
FingerprintSHA256 string `json:"fingerprint_sha256,omitempty"`
|
||||
ChainLength int `json:"chain_length,omitempty"`
|
||||
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 {
|
||||
@@ -148,6 +155,15 @@ func ValidateResourceForDomains(resource Resource, expected []string) (Resource,
|
||||
}
|
||||
|
||||
func (s FileStore) Save(ctx context.Context, domain string, resource Resource) (SavedResource, error) {
|
||||
return s.save(ctx, domain, "", resource)
|
||||
}
|
||||
|
||||
// SaveForType 按证书类型保存当前证书和历史版本。
|
||||
func (s FileStore) SaveForType(ctx context.Context, domain, certificateType string, resource Resource) (SavedResource, error) {
|
||||
return s.save(ctx, domain, certificateType, resource)
|
||||
}
|
||||
|
||||
func (s FileStore) save(ctx context.Context, domain, certificateType string, resource Resource) (SavedResource, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
@@ -166,46 +182,114 @@ func (s FileStore) Save(ctx context.Context, domain string, resource Resource) (
|
||||
if root == "." || root == "" {
|
||||
return SavedResource{}, errors.New("证书存储根目录不能为空")
|
||||
}
|
||||
directory := filepath.Join(root, directoryName(primary))
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
baseDirectory := filepath.Join(root, directoryName(primary))
|
||||
directory := baseDirectory
|
||||
if certificateType != "" {
|
||||
certificateType = strings.ToLower(strings.TrimSpace(certificateType))
|
||||
if certificateType != "single" && certificateType != "wildcard" && certificateType != "san" {
|
||||
return SavedResource{}, fmt.Errorf("证书类型无效:%s", certificateType)
|
||||
}
|
||||
directory = filepath.Join(baseDirectory, certificateType)
|
||||
}
|
||||
currentDirectory := directory
|
||||
if certificateType != "" {
|
||||
currentDirectory = filepath.Join(directory, "current")
|
||||
}
|
||||
if err := os.MkdirAll(currentDirectory, 0o700); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("创建证书目录失败:%w", err)
|
||||
}
|
||||
backupDirectory, err := s.backupExisting(directory, primary)
|
||||
backupDirectory, err := s.backupExisting(currentDirectory, 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)
|
||||
version := ""
|
||||
if certificateType != "" {
|
||||
now := time.Now
|
||||
if s.Now != nil {
|
||||
now = s.Now
|
||||
}
|
||||
version = now().UTC().Format("20060102-150405.000000000")
|
||||
versionDirectory := filepath.Join(directory, "versions", version)
|
||||
for suffix := 1; ; suffix++ {
|
||||
if _, statErr := os.Stat(versionDirectory); errors.Is(statErr, os.ErrNotExist) {
|
||||
break
|
||||
} else if statErr != nil {
|
||||
return SavedResource{}, fmt.Errorf("读取证书版本目录失败:%w", statErr)
|
||||
}
|
||||
version = fmt.Sprintf("%s-%02d", now().UTC().Format("20060102-150405.000000000"), suffix)
|
||||
versionDirectory = filepath.Join(directory, "versions", version)
|
||||
}
|
||||
if err := os.MkdirAll(versionDirectory, 0o700); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("创建证书版本目录失败:%w", err)
|
||||
}
|
||||
if err := writeCertificateFiles(versionDirectory, resource.Certificate, fullChain, resource.PrivateKey); err != nil {
|
||||
return SavedResource{}, 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)
|
||||
if err := writeCertificateFiles(currentDirectory, resource.Certificate, fullChain, resource.PrivateKey); err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
leaf, _ := parseLeafCertificate(resource.Certificate)
|
||||
result := SavedResource{
|
||||
Domain: primary, Directory: directory, CertificatePath: certificatePath,
|
||||
FullChainPath: fullChainPath, PrivateKeyPath: privateKeyPath,
|
||||
NotBefore: resource.NotBefore, NotAfter: resource.NotAfter,
|
||||
BackupDirectory: backupDirectory,
|
||||
Domain: primary, CertificateType: certificateType, Version: version, SANs: append([]string(nil), resource.Domains...),
|
||||
Directory: currentDirectory, CertificatePath: filepath.Join(currentDirectory, "cert.pem"),
|
||||
FullChainPath: filepath.Join(currentDirectory, "fullchain.pem"), PrivateKeyPath: filepath.Join(currentDirectory, "key.pem"),
|
||||
NotBefore: resource.NotBefore, NotAfter: resource.NotAfter, BackupDirectory: backupDirectory,
|
||||
ChainLength: certificateChainLength(fullChain),
|
||||
}
|
||||
if leaf != nil {
|
||||
result.SerialNumber = leaf.SerialNumber.Text(16)
|
||||
result.FingerprintSHA256 = fmt.Sprintf("%X", sha256.Sum256(leaf.Raw))
|
||||
}
|
||||
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)
|
||||
if err := atomicWrite(filepath.Join(currentDirectory, "metadata.json"), metadata, 0o600); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("写入证书元数据失败:%w", err)
|
||||
}
|
||||
if certificateType != "" {
|
||||
versionMetadata := filepath.Join(directory, "versions", version, "metadata.json")
|
||||
if err := atomicWrite(versionMetadata, metadata, 0o600); err != nil {
|
||||
return SavedResource{}, fmt.Errorf("写入历史证书元数据失败:%w", err)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func writeCertificateFiles(directory string, certificate, fullChain, privateKey []byte) error {
|
||||
if err := atomicWrite(filepath.Join(directory, "cert.pem"), certificate, 0o644); err != nil {
|
||||
return fmt.Errorf("写入证书文件失败:%w", err)
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(directory, "fullchain.pem"), fullChain, 0o644); err != nil {
|
||||
return fmt.Errorf("写入完整证书链失败:%w", err)
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(directory, "key.pem"), privateKey, 0o600); err != nil {
|
||||
return fmt.Errorf("写入私钥文件失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func certificateChainLength(data []byte) int {
|
||||
count := 0
|
||||
remaining := data
|
||||
for len(remaining) > 0 {
|
||||
block, rest := pem.Decode(remaining)
|
||||
if block == nil {
|
||||
break
|
||||
}
|
||||
remaining = rest
|
||||
if block.Type == "CERTIFICATE" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func (s FileStore) backupExisting(directory, domain string) (string, error) {
|
||||
entries, err := os.ReadDir(directory)
|
||||
if err != nil {
|
||||
@@ -328,3 +412,168 @@ func validDomain(value string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CurrentDirectory returns the active certificate directory for a domain and certificate type.
|
||||
func (s FileStore) CurrentDirectory(domain, certificateType string) (string, error) {
|
||||
primary := strings.TrimSpace(domain)
|
||||
if _, err := NormalizeDomains([]string{primary}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
certificateType = strings.ToLower(strings.TrimSpace(certificateType))
|
||||
if certificateType != "single" && certificateType != "wildcard" && certificateType != "san" {
|
||||
return "", fmt.Errorf("证书类型无效:%s", certificateType)
|
||||
}
|
||||
root := filepath.Clean(strings.TrimSpace(s.Root))
|
||||
if root == "." || root == "" {
|
||||
return "", errors.New("证书存储根目录不能为空")
|
||||
}
|
||||
return filepath.Join(root, directoryName(primary), certificateType, "current"), nil
|
||||
}
|
||||
|
||||
// LoadCurrent reads the active certificate files and metadata.
|
||||
func (s FileStore) LoadCurrent(ctx context.Context, domain, certificateType string) (SavedResource, Resource, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return SavedResource{}, Resource{}, err
|
||||
}
|
||||
directory, err := s.CurrentDirectory(domain, certificateType)
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, err
|
||||
}
|
||||
certificateData, err := os.ReadFile(filepath.Join(directory, "cert.pem"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取证书文件失败:%w", err)
|
||||
}
|
||||
fullChainData, err := os.ReadFile(filepath.Join(directory, "fullchain.pem"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取完整证书链失败:%w", err)
|
||||
}
|
||||
privateKeyData, err := os.ReadFile(filepath.Join(directory, "key.pem"))
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("读取私钥文件失败:%w", err)
|
||||
}
|
||||
resource, err := ValidateResourceForDomains(Resource{
|
||||
Domains: []string{domain},
|
||||
Certificate: certificateData,
|
||||
IssuerCertificate: fullChainData,
|
||||
PrivateKey: privateKeyData,
|
||||
}, []string{domain})
|
||||
if err != nil {
|
||||
return SavedResource{}, Resource{}, err
|
||||
}
|
||||
resource.IssuerCertificate = nil
|
||||
var saved SavedResource
|
||||
metadata, metadataErr := os.ReadFile(filepath.Join(directory, "metadata.json"))
|
||||
if metadataErr == nil {
|
||||
if err := json.Unmarshal(metadata, &saved); err != nil {
|
||||
return SavedResource{}, Resource{}, fmt.Errorf("解析证书元数据失败:%w", err)
|
||||
}
|
||||
}
|
||||
if saved.Domain == "" {
|
||||
saved = SavedResource{
|
||||
Domain: domain,
|
||||
CertificateType: certificateType,
|
||||
Directory: directory,
|
||||
CertificatePath: filepath.Join(directory, "cert.pem"),
|
||||
FullChainPath: filepath.Join(directory, "fullchain.pem"),
|
||||
PrivateKeyPath: filepath.Join(directory, "key.pem"),
|
||||
NotBefore: resource.NotBefore,
|
||||
NotAfter: resource.NotAfter,
|
||||
SANs: resource.Domains,
|
||||
ChainLength: certificateChainLength(fullChainData),
|
||||
}
|
||||
}
|
||||
return saved, resource, nil
|
||||
}
|
||||
|
||||
// ListVersions returns all stored certificate versions in descending order.
|
||||
func (s FileStore) ListVersions(ctx context.Context, domain, certificateType string) ([]SavedResource, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := s.CurrentDirectory(domain, certificateType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
certificateDirectory := filepath.Dir(current)
|
||||
versionsDirectory := filepath.Join(certificateDirectory, "versions")
|
||||
entries, err := os.ReadDir(versionsDirectory)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return []SavedResource{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("读取证书版本失败:%w", err)
|
||||
}
|
||||
versions := make([]SavedResource, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
metadata, readErr := os.ReadFile(filepath.Join(versionsDirectory, entry.Name(), "metadata.json"))
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("读取证书版本元数据失败:%w", readErr)
|
||||
}
|
||||
var item SavedResource
|
||||
if err := json.Unmarshal(metadata, &item); err != nil {
|
||||
return nil, fmt.Errorf("解析证书版本元数据失败:%w", err)
|
||||
}
|
||||
versions = append(versions, item)
|
||||
}
|
||||
sort.SliceStable(versions, func(i, j int) bool { return versions[i].Version > versions[j].Version })
|
||||
return versions, nil
|
||||
}
|
||||
|
||||
// RollbackSavedResource 在初始化后续阶段失败时恢复证书目录。
|
||||
// 如果保存前存在旧证书,则从备份目录恢复;否则仅清理本次写入的固定证书文件。
|
||||
func RollbackSavedResource(ctx context.Context, saved SavedResource) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
directory := filepath.Clean(strings.TrimSpace(saved.Directory))
|
||||
if directory == "." || directory == "" {
|
||||
return errors.New("证书回滚目录不能为空")
|
||||
}
|
||||
if strings.TrimSpace(saved.BackupDirectory) != "" {
|
||||
backupDirectory := filepath.Clean(strings.TrimSpace(saved.BackupDirectory))
|
||||
if backupDirectory == "." || backupDirectory == "" {
|
||||
return errors.New("证书备份目录无效")
|
||||
}
|
||||
if _, err := os.Stat(backupDirectory); err != nil {
|
||||
return fmt.Errorf("读取证书备份目录失败:%w", err)
|
||||
}
|
||||
if err := restoreCertificateFiles(directory, backupDirectory); err != nil {
|
||||
return fmt.Errorf("恢复原证书失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
path := filepath.Join(directory, name)
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("清理失败证书文件 %s 失败:%w", name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreCertificateFiles(directory, backupDirectory string) error {
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
source := filepath.Join(backupDirectory, name)
|
||||
data, err := os.ReadFile(source)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
mode := os.FileMode(0o600)
|
||||
if name == "cert.pem" || name == "fullchain.pem" {
|
||||
mode = 0o644
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(directory, name), data, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFileStoreVersionedLayoutAndHistory(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, 27, 12, 0, 0, 0, time.UTC) },
|
||||
}
|
||||
resource := testResource(t, "example.com")
|
||||
first, err := store.SaveForType(context.Background(), "example.com", "single", resource)
|
||||
if err != nil {
|
||||
t.Fatalf("保存第一版证书失败:%v", err)
|
||||
}
|
||||
second, err := store.SaveForType(context.Background(), "example.com", "single", resource)
|
||||
if err != nil {
|
||||
t.Fatalf("保存第二版证书失败:%v", err)
|
||||
}
|
||||
if first.Version == second.Version {
|
||||
t.Fatalf("重复保存不应覆盖历史版本:%q", first.Version)
|
||||
}
|
||||
wantCurrent := filepath.Join(root, "ssl", "example.com", "single", "current")
|
||||
if second.Directory != wantCurrent {
|
||||
t.Fatalf("当前目录错误:got=%q want=%q", second.Directory, wantCurrent)
|
||||
}
|
||||
for _, path := range []string{
|
||||
filepath.Join(wantCurrent, "cert.pem"),
|
||||
filepath.Join(wantCurrent, "fullchain.pem"),
|
||||
filepath.Join(wantCurrent, "key.pem"),
|
||||
filepath.Join(wantCurrent, "metadata.json"),
|
||||
filepath.Join(root, "ssl", "example.com", "single", "versions", first.Version, "metadata.json"),
|
||||
filepath.Join(root, "ssl", "example.com", "single", "versions", second.Version, "metadata.json"),
|
||||
} {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("证书文件不存在:%s:%v", path, err)
|
||||
}
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
info, err := os.Stat(second.PrivateKeyPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取私钥权限失败:%v", err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("私钥权限错误:%o", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
versions, err := store.ListVersions(context.Background(), "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("读取证书版本失败:%v", err)
|
||||
}
|
||||
if len(versions) != 2 || versions[0].Version != second.Version || versions[1].Version != first.Version {
|
||||
t.Fatalf("证书版本历史错误:%+v", versions)
|
||||
}
|
||||
metadata, loaded, err := store.LoadCurrent(context.Background(), "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("读取当前证书失败:%v", err)
|
||||
}
|
||||
if metadata.Version != second.Version || len(loaded.Certificate) == 0 || len(loaded.PrivateKey) == 0 {
|
||||
t.Fatalf("当前证书内容错误:metadata=%+v", metadata)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileStoreListVersionsReturnsEmptyWhenNoHistory(t *testing.T) {
|
||||
store := FileStore{Root: t.TempDir()}
|
||||
versions, err := store.ListVersions(context.Background(), "example.com", "san")
|
||||
if err != nil {
|
||||
t.Fatalf("无版本记录时查询失败:%v", err)
|
||||
}
|
||||
if versions == nil || len(versions) != 0 {
|
||||
t.Fatalf("无版本记录时应返回空列表:%+v", versions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRollbackSavedResourceRestoresPreviousCertificate(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, 28, 12, 0, 0, 0, time.UTC) },
|
||||
}
|
||||
resource := testResource(t, "example.com")
|
||||
first, err := store.SaveForType(context.Background(), "example.com", "single", resource)
|
||||
if err != nil {
|
||||
t.Fatalf("保存初始证书失败:%v", err)
|
||||
}
|
||||
second, err := store.SaveForType(context.Background(), "example.com", "single", resource)
|
||||
if err != nil {
|
||||
t.Fatalf("保存新证书失败:%v", err)
|
||||
}
|
||||
if second.BackupDirectory == "" {
|
||||
t.Fatal("替换已有证书时应生成备份目录")
|
||||
}
|
||||
if err := RollbackSavedResource(context.Background(), second); err != nil {
|
||||
t.Fatalf("回滚证书失败:%v", err)
|
||||
}
|
||||
if _, err := os.Stat(first.FullChainPath); err != nil {
|
||||
t.Fatalf("回滚后当前证书不存在:%v", err)
|
||||
}
|
||||
if _, err := os.Stat(second.PrivateKeyPath); err != nil {
|
||||
t.Fatalf("回滚后当前私钥不存在:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRollbackSavedResourceClearsNewCertificateFiles(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := FileStore{
|
||||
Root: filepath.Join(root, "ssl"),
|
||||
BackupRoot: filepath.Join(root, "backups"),
|
||||
}
|
||||
saved, err := store.SaveForType(context.Background(), "example.com", "single", testResource(t, "example.com"))
|
||||
if err != nil {
|
||||
t.Fatalf("保存证书失败:%v", err)
|
||||
}
|
||||
if err := RollbackSavedResource(context.Background(), saved); err != nil {
|
||||
t.Fatalf("清理失败证书失败:%v", err)
|
||||
}
|
||||
for _, name := range []string{"cert.pem", "fullchain.pem", "key.pem", "metadata.json"} {
|
||||
if _, err := os.Stat(filepath.Join(saved.Directory, name)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("回滚后文件仍存在:%s,错误:%v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,17 @@ type ImportRequest struct {
|
||||
IssuerBundle string
|
||||
}
|
||||
|
||||
type SetupCertificateRequest struct {
|
||||
Domains []string
|
||||
CertificateType string
|
||||
ProviderID string
|
||||
CredentialRef string
|
||||
AccountEmail string
|
||||
Environment string
|
||||
CertificateRoot string
|
||||
BackupRoot 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,
|
||||
@@ -141,7 +152,10 @@ func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, erro
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
saved, err := s.store.Save(ctx, item.Name, resource)
|
||||
if err := validateIssuedResource(ctx, resource, domains); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
saved, err := s.store.SaveForType(ctx, item.Name, string(item.CertificateType), resource)
|
||||
if err != nil {
|
||||
return fail(fmt.Errorf("保存证书文件失败:%w", err))
|
||||
}
|
||||
@@ -151,6 +165,75 @@ func (s *Service) Issue(ctx context.Context, domainID string) (IssueResult, erro
|
||||
return IssueResult{DomainID: item.ID, Domains: domains, Saved: saved}, nil
|
||||
}
|
||||
|
||||
// IssueForSetup 在初始化标记完成前申请并保存管理后台证书。
|
||||
func (s *Service) IssueForSetup(ctx context.Context, request SetupCertificateRequest) (SavedResource, error) {
|
||||
if s == nil || s.credentials == nil || s.providers == nil || s.accounts == nil || s.newIssuer == nil {
|
||||
return SavedResource{}, errors.New("初始化证书申请服务未初始化")
|
||||
}
|
||||
domains, err := NormalizeDomains(request.Domains)
|
||||
if err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
certificateType := strings.ToLower(strings.TrimSpace(request.CertificateType))
|
||||
if certificateType != "single" && certificateType != "wildcard" && certificateType != "san" {
|
||||
return SavedResource{}, fmt.Errorf("初始化证书类型无效:%s", certificateType)
|
||||
}
|
||||
providerID := strings.ToLower(strings.TrimSpace(request.ProviderID))
|
||||
credentialRef := strings.TrimSpace(request.CredentialRef)
|
||||
if providerID == "" || credentialRef == "" {
|
||||
return SavedResource{}, errors.New("初始化证书的 DNS Provider 或凭据引用未配置")
|
||||
}
|
||||
environment := strings.ToLower(strings.TrimSpace(request.Environment))
|
||||
if environment == "" {
|
||||
environment = s.config.ACME.Environment
|
||||
}
|
||||
if environment == "" {
|
||||
environment = "staging"
|
||||
}
|
||||
credentials, err := s.credentials.Get(ctx, credentialRef)
|
||||
if err != nil {
|
||||
return SavedResource{}, fmt.Errorf("读取初始化证书 DNS 凭据失败:%w", err)
|
||||
}
|
||||
provider, err := s.providers.Create(providerID, credentials)
|
||||
if err != nil {
|
||||
return SavedResource{}, fmt.Errorf("创建初始化证书 DNS Provider 失败:%w", err)
|
||||
}
|
||||
accountEmail := strings.TrimSpace(request.AccountEmail)
|
||||
if accountEmail == "" {
|
||||
accountEmail = strings.TrimSpace(s.config.ACME.AccountEmail)
|
||||
}
|
||||
user, err := s.accounts.LoadOrCreate(ctx, environment, accountEmail)
|
||||
if err != nil {
|
||||
return SavedResource{}, fmt.Errorf("读取 ACME 账户失败:%w", err)
|
||||
}
|
||||
issuer := s.newIssuer(user, provider, environment)
|
||||
resource, issueErr := issuer.Obtain(ctx, ObtainRequest{
|
||||
Domains: domains, AccountEmail: accountEmail, Environment: environment, PreferredChain: s.preferredChain,
|
||||
})
|
||||
if saveErr := s.accounts.Save(ctx, environment, user); saveErr != nil {
|
||||
if issueErr != nil {
|
||||
return SavedResource{}, fmt.Errorf("%v;保存 ACME 账户状态失败:%w", issueErr, saveErr)
|
||||
}
|
||||
return SavedResource{}, fmt.Errorf("保存 ACME 账户状态失败:%w", saveErr)
|
||||
}
|
||||
if issueErr != nil {
|
||||
return SavedResource{}, issueErr
|
||||
}
|
||||
resource, err = ValidateResourceForDomains(resource, domains)
|
||||
if err != nil {
|
||||
return SavedResource{}, fmt.Errorf("初始化证书校验失败:%w", err)
|
||||
}
|
||||
if err := validateIssuedResource(ctx, resource, domains); err != nil {
|
||||
return SavedResource{}, err
|
||||
}
|
||||
store := FileStore{Root: request.CertificateRoot, BackupRoot: request.BackupRoot}
|
||||
saved, err := store.SaveForType(ctx, domains[0], certificateType, resource)
|
||||
if err != nil {
|
||||
return SavedResource{}, fmt.Errorf("保存初始化证书失败:%w", err)
|
||||
}
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
func (s *Service) Import(ctx context.Context, request ImportRequest) (IssueResult, error) {
|
||||
if s == nil || s.repository == nil {
|
||||
return IssueResult{}, errors.New("证书导入服务未初始化")
|
||||
@@ -193,7 +276,10 @@ func (s *Service) Import(ctx context.Context, request ImportRequest) (IssueResul
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
saved, err := s.store.Save(ctx, item.Name, resource)
|
||||
if err := validateIssuedResource(ctx, resource, domains); err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
saved, err := s.store.SaveForType(ctx, item.Name, string(item.CertificateType), resource)
|
||||
if err != nil {
|
||||
return IssueResult{}, fmt.Errorf("保存导入证书失败:%w", err)
|
||||
}
|
||||
@@ -203,6 +289,16 @@ func (s *Service) Import(ctx context.Context, request ImportRequest) (IssueResul
|
||||
return IssueResult{DomainID: item.ID, Domains: resource.Domains, Saved: saved}, nil
|
||||
}
|
||||
|
||||
func validateIssuedResource(ctx context.Context, resource Resource, domains []string) error {
|
||||
chainData := append([]byte(nil), resource.Certificate...)
|
||||
chainData = append(chainData, resource.IssuerCertificate...)
|
||||
_, err := (LocalValidator{VerifyChain: len(resource.IssuerCertificate) > 0}).ValidatePEM(ctx, chainData, domains)
|
||||
if err != nil {
|
||||
return fmt.Errorf("本地证书校验失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cleanInputPath(value, label string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
@@ -229,3 +325,58 @@ func requestedDomains(item domain.Domain) ([]string, error) {
|
||||
}
|
||||
return NormalizeDomains(values)
|
||||
}
|
||||
|
||||
// Current returns and validates the active certificate for a managed domain.
|
||||
func (s *Service) Current(ctx context.Context, domainID string) (IssueResult, error) {
|
||||
if s == nil || s.repository == nil {
|
||||
return IssueResult{}, errors.New("当前证书服务未初始化")
|
||||
}
|
||||
item, err := s.repository.GetByID(ctx, strings.TrimSpace(domainID))
|
||||
if err != nil {
|
||||
return IssueResult{}, fmt.Errorf("读取域名配置失败:%w", err)
|
||||
}
|
||||
domains, err := requestedDomains(item)
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
saved, resource, err := s.store.LoadCurrent(ctx, item.Name, string(item.CertificateType))
|
||||
if err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
if _, err := ValidateResourceForDomains(resource, domains); err != nil {
|
||||
return IssueResult{}, err
|
||||
}
|
||||
saved.SANs = append([]string(nil), resource.Domains...)
|
||||
return IssueResult{DomainID: item.ID, Domains: domains, Saved: saved}, nil
|
||||
}
|
||||
|
||||
// ValidateCurrent 校验当前证书文件、私钥、证书链和域名覆盖范围。
|
||||
func (s *Service) ValidateCurrent(ctx context.Context, domainID string) (ValidationResult, error) {
|
||||
result, err := s.Current(ctx, domainID)
|
||||
if err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
validation, err := (LocalValidator{VerifyChain: true}).ValidateFiles(
|
||||
ctx,
|
||||
result.Saved.CertificatePath,
|
||||
result.Saved.FullChainPath,
|
||||
result.Saved.PrivateKeyPath,
|
||||
result.Domains,
|
||||
)
|
||||
if err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("当前证书校验失败:%w", err)
|
||||
}
|
||||
return validation, nil
|
||||
}
|
||||
|
||||
// ListVersions returns the certificate history for a managed domain.
|
||||
func (s *Service) ListVersions(ctx context.Context, domainID string) ([]SavedResource, error) {
|
||||
if s == nil || s.repository == nil {
|
||||
return nil, errors.New("证书服务未初始化")
|
||||
}
|
||||
item, err := s.repository.GetByID(ctx, strings.TrimSpace(domainID))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取域名配置失败:%w", err)
|
||||
}
|
||||
return s.store.ListVersions(ctx, item.Name, string(item.CertificateType))
|
||||
}
|
||||
@@ -232,3 +232,33 @@ func testResourceForDomains(t *testing.T, names []string) Resource {
|
||||
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}),
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceIssuesSetupCertificateWithTypedLayout(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
cfg := certificateTestConfig(root)
|
||||
issuer := &serviceIssuer{resource: testResource(t, "scert.example.com")}
|
||||
service := NewService(cfg, nil, serviceCredentials{}, serviceProviderFactory{}, serviceAccounts{})
|
||||
service.newIssuer = func(*AccountUser, challenge.Provider, string) Issuer { return issuer }
|
||||
|
||||
saved, err := service.IssueForSetup(context.Background(), SetupCertificateRequest{
|
||||
Domains: []string{"scert.example.com"}, CertificateType: "single",
|
||||
ProviderID: "cloudflare", CredentialRef: "secret://dns/cloudflare/test",
|
||||
AccountEmail: "admin@example.com", Environment: "staging",
|
||||
CertificateRoot: cfg.Paths.Certificate, BackupRoot: cfg.Paths.Backup,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("申请初始化证书失败:%v", err)
|
||||
}
|
||||
wantDirectory := filepath.Join(cfg.Paths.Certificate, "scert.example.com", "single", "current")
|
||||
if saved.Directory != wantDirectory {
|
||||
t.Fatalf("初始化证书目录错误:got=%q want=%q", saved.Directory, wantDirectory)
|
||||
}
|
||||
if issuer.request.AccountEmail != "admin@example.com" || len(issuer.request.Domains) != 1 {
|
||||
t.Fatalf("初始化证书申请参数错误:%+v", issuer.request)
|
||||
}
|
||||
for _, path := range []string{saved.CertificatePath, saved.FullChainPath, saved.PrivateKeyPath} {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("初始化证书文件不存在:%s:%v", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ValidationResult 保存证书校验后的关键元数据。
|
||||
type ValidationResult struct {
|
||||
Domains []string `json:"domains"`
|
||||
SerialNumber string `json:"serial_number"`
|
||||
FingerprintSHA256 string `json:"fingerprint_sha256"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
ChainLength int `json:"chain_length"`
|
||||
}
|
||||
|
||||
// LocalValidator 校验本地证书、私钥和证书链。
|
||||
type LocalValidator struct {
|
||||
Roots *x509.CertPool
|
||||
Now func() time.Time
|
||||
VerifyChain bool
|
||||
}
|
||||
|
||||
// ValidateFiles 校验证书文件、私钥文件以及期望覆盖的域名。
|
||||
func (v LocalValidator) ValidateFiles(ctx context.Context, certificatePath, fullChainPath, privateKeyPath string, expectedDomains []string) (ValidationResult, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
certificateData, err := os.ReadFile(certificatePath)
|
||||
if err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("读取证书文件失败:%w", err)
|
||||
}
|
||||
chainData := certificateData
|
||||
if strings.TrimSpace(fullChainPath) != "" {
|
||||
chainData, err = os.ReadFile(fullChainPath)
|
||||
if err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("读取完整证书链失败:%w", err)
|
||||
}
|
||||
}
|
||||
privateKeyData, err := os.ReadFile(privateKeyPath)
|
||||
if err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("读取私钥文件失败:%w", err)
|
||||
}
|
||||
if _, err := tls.X509KeyPair(chainData, privateKeyData); err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("证书与私钥不匹配:%w", err)
|
||||
}
|
||||
return v.validatePEM(ctx, chainData, expectedDomains)
|
||||
}
|
||||
|
||||
// ValidatePEM 校验内存中的证书链和期望域名。
|
||||
func (v LocalValidator) ValidatePEM(ctx context.Context, chainData []byte, expectedDomains []string) (ValidationResult, error) {
|
||||
return v.validatePEM(ctx, chainData, expectedDomains)
|
||||
}
|
||||
|
||||
func (v LocalValidator) validatePEM(ctx context.Context, chainData []byte, expectedDomains []string) (ValidationResult, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
certificates, err := parseCertificates(chainData)
|
||||
if err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
leaf := certificates[0]
|
||||
wanted, err := normalizeValidationNames(expectedDomains)
|
||||
if err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if v.Now != nil {
|
||||
now = v.Now().UTC()
|
||||
}
|
||||
if now.Before(leaf.NotBefore) || !now.Before(leaf.NotAfter) {
|
||||
return ValidationResult{}, fmt.Errorf("证书当前不在有效期内:%s 至 %s", leaf.NotBefore.UTC().Format(time.RFC3339), 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 ValidationResult{}, fmt.Errorf("证书不覆盖域名 %s:%w", name, err)
|
||||
}
|
||||
}
|
||||
if v.VerifyChain {
|
||||
if err := verifyChain(certificates, v.Roots, now); err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
}
|
||||
return validationResult(leaf, len(certificates)), nil
|
||||
}
|
||||
|
||||
// RemoteValidator 校验远程 HTTPS 服务实际返回的证书。
|
||||
type RemoteValidator struct {
|
||||
Roots *x509.CertPool
|
||||
Dialer *net.Dialer
|
||||
Timeout time.Duration
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// ValidateHTTPS 连接目标 HTTPS 地址并校验证书链和域名。
|
||||
func (v RemoteValidator) ValidateHTTPS(ctx context.Context, endpoint string, expectedDomains []string) (ValidationResult, error) {
|
||||
target, err := normalizeHTTPSURL(endpoint)
|
||||
if err != nil {
|
||||
return ValidationResult{}, err
|
||||
}
|
||||
parsed, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("解析 HTTPS 地址失败:%w", err)
|
||||
}
|
||||
address := parsed.Host
|
||||
if _, _, splitErr := net.SplitHostPort(address); splitErr != nil {
|
||||
address = net.JoinHostPort(parsed.Hostname(), "443")
|
||||
}
|
||||
dialer := v.Dialer
|
||||
if dialer == nil {
|
||||
dialer = &net.Dialer{Timeout: v.timeout()}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, v.timeout())
|
||||
defer cancel()
|
||||
tlsDialer := &tls.Dialer{
|
||||
NetDialer: dialer,
|
||||
Config: &tls.Config{
|
||||
ServerName: parsed.Hostname(),
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
}
|
||||
connection, err := tlsDialer.DialContext(ctx, "tcp", address)
|
||||
if err != nil {
|
||||
return ValidationResult{}, fmt.Errorf("remote HTTPS connection failed: %w", err)
|
||||
}
|
||||
tlsConnection, ok := connection.(*tls.Conn)
|
||||
if !ok {
|
||||
_ = connection.Close()
|
||||
return ValidationResult{}, errors.New("remote HTTPS connection type is invalid")
|
||||
}
|
||||
defer tlsConnection.Close()
|
||||
state := tlsConnection.ConnectionState()
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return ValidationResult{}, errors.New("远程 HTTPS 服务未返回证书")
|
||||
}
|
||||
certificates := make([]*x509.Certificate, len(state.PeerCertificates))
|
||||
copy(certificates, state.PeerCertificates)
|
||||
wanted := expectedDomains
|
||||
if len(wanted) == 0 {
|
||||
wanted = []string{parsed.Hostname()}
|
||||
}
|
||||
chainData := make([]byte, 0)
|
||||
for _, certificate := range certificates {
|
||||
chainData = append(chainData, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw})...)
|
||||
}
|
||||
validator := LocalValidator{Roots: v.Roots, Now: v.Now, VerifyChain: true}
|
||||
return validator.ValidatePEM(ctx, chainData, wanted)
|
||||
}
|
||||
|
||||
func (v RemoteValidator) timeout() time.Duration {
|
||||
if v.Timeout > 0 {
|
||||
return v.Timeout
|
||||
}
|
||||
return 10 * time.Second
|
||||
}
|
||||
|
||||
func normalizeHTTPSURL(value string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "", errors.New("HTTPS 地址不能为空")
|
||||
}
|
||||
if !strings.Contains(value, "://") {
|
||||
value = "https://" + value
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return "", errors.New("HTTPS 地址格式无效")
|
||||
}
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
func normalizeValidationNames(values []string) ([]string, error) {
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
value = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
if net.ParseIP(strings.TrimPrefix(value, "*.")) == nil && !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("证书校验域名不能为空")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func parseCertificates(data []byte) ([]*x509.Certificate, error) {
|
||||
remaining := data
|
||||
certificates := make([]*x509.Certificate, 0, 2)
|
||||
for len(remaining) > 0 {
|
||||
block, rest := pem.Decode(remaining)
|
||||
if block == nil {
|
||||
break
|
||||
}
|
||||
remaining = rest
|
||||
if block.Type != "CERTIFICATE" {
|
||||
continue
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析证书链失败:%w", err)
|
||||
}
|
||||
certificates = append(certificates, certificate)
|
||||
}
|
||||
if len(certificates) == 0 {
|
||||
return nil, errors.New("未找到 PEM 证书链")
|
||||
}
|
||||
return certificates, nil
|
||||
}
|
||||
|
||||
func verifyChain(certificates []*x509.Certificate, roots *x509.CertPool, now time.Time) error {
|
||||
if roots == nil {
|
||||
var err error
|
||||
roots, err = x509.SystemCertPool()
|
||||
if err != nil || roots == nil {
|
||||
roots = x509.NewCertPool()
|
||||
}
|
||||
}
|
||||
intermediates := x509.NewCertPool()
|
||||
for _, certificate := range certificates[1:] {
|
||||
if !certificate.IsCA {
|
||||
continue
|
||||
}
|
||||
intermediates.AddCert(certificate)
|
||||
}
|
||||
_, err := certificates[0].Verify(x509.VerifyOptions{
|
||||
Roots: roots,
|
||||
Intermediates: intermediates,
|
||||
DNSName: "",
|
||||
CurrentTime: now,
|
||||
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("证书链校验失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validationResult(leaf *x509.Certificate, chainLength int) ValidationResult {
|
||||
return ValidationResult{
|
||||
Domains: append([]string(nil), leaf.DNSNames...),
|
||||
SerialNumber: leaf.SerialNumber.Text(16),
|
||||
FingerprintSHA256: fmt.Sprintf("%X", sha256.Sum256(leaf.Raw)),
|
||||
NotBefore: leaf.NotBefore,
|
||||
NotAfter: leaf.NotAfter,
|
||||
ChainLength: chainLength,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalValidatorChecksKeyChainAndSAN(t *testing.T) {
|
||||
certificateData, privateKeyData, leaf := validationTestCertificate(t, []string{"example.com", "www.example.com"})
|
||||
rootPool := x509.NewCertPool()
|
||||
rootPool.AddCert(leaf)
|
||||
validator := LocalValidator{Roots: rootPool, VerifyChain: true}
|
||||
|
||||
result, err := validator.ValidatePEM(context.Background(), certificateData, []string{"example.com", "www.example.com"})
|
||||
if err != nil {
|
||||
t.Fatalf("valid certificate should pass: %v", err)
|
||||
}
|
||||
if result.SerialNumber == "" || result.ChainLength != 1 || len(result.Domains) != 2 {
|
||||
t.Fatalf("unexpected validation result: %+v", result)
|
||||
}
|
||||
if _, err := tls.X509KeyPair(certificateData, privateKeyData); err != nil {
|
||||
t.Fatalf("test certificate and key should match: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalValidatorRejectsMissingSAN(t *testing.T) {
|
||||
certificateData, _, leaf := validationTestCertificate(t, []string{"example.com"})
|
||||
rootPool := x509.NewCertPool()
|
||||
rootPool.AddCert(leaf)
|
||||
_, err := (LocalValidator{Roots: rootPool, VerifyChain: true}).ValidatePEM(context.Background(), certificateData, []string{"api.example.com"})
|
||||
if err == nil {
|
||||
t.Fatal("certificate without requested SAN should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteValidatorChecksPresentedCertificate(t *testing.T) {
|
||||
certificateData, privateKeyData, leaf := validationTestCertificate(t, []string{"localhost", "127.0.0.1"})
|
||||
pair, err := tls.X509KeyPair(certificateData, privateKeyData)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewUnstartedServer(nil)
|
||||
server.TLS = &tls.Config{Certificates: []tls.Certificate{pair}}
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(leaf)
|
||||
result, err := (RemoteValidator{Roots: roots, Timeout: 5 * time.Second}).ValidateHTTPS(context.Background(), server.URL, []string{"127.0.0.1"})
|
||||
if err != nil {
|
||||
t.Fatalf("remote certificate should pass: %v", err)
|
||||
}
|
||||
if result.ChainLength != 1 || len(result.FingerprintSHA256) != 64 {
|
||||
t.Fatalf("unexpected remote validation result: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func validationTestCertificate(t *testing.T, names []string) ([]byte, []byte, *x509.Certificate) {
|
||||
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(99),
|
||||
Subject: pkix.Name{CommonName: names[0]},
|
||||
DNSNames: names,
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
NotBefore: now.Add(-time.Minute),
|
||||
NotAfter: now.Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certificateData := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
privateKeyData := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
return certificateData, privateKeyData, leaf
|
||||
}
|
||||
Reference in new issue
Block a user