完善证书管理与初始化流程

This commit is contained in:
xuans committed 2026-08-27 22:16:10 +08:00
1 parent 07636abe44
commit c74372284a
84 files changed
+10151 -3502

No files matched your search

+20 -3
View File
@@ -7,9 +7,11 @@ import (
"path/filepath"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/admin"
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/database"
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/httpapi"
@@ -17,6 +19,7 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/repository"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup"
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
)
type App struct {
@@ -24,9 +27,13 @@ type App struct {
Logger *logging.Logger
Database *database.Database
Repository *repository.SQLDomainRepository
Servers *repository.SQLServerRepository
Deployment *deployment.Service
SecretStore *secretstore.Store
SSHKeys *sshkey.Service
DNSVerification *setup.DNSVerificationManager
Certificates *certificate.Service
Workflow *CertificateWorkflow
Renewal *certificate.RenewalScheduler
HTTP *httpapi.Server
}
@@ -67,17 +74,27 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
dnsTester := dnsprovider.NewTester(dnsprovider.NewLegoFactory())
dnsVerification := setup.NewDNSVerificationManager(dnsTester, secretStore)
repo := repository.NewSQLDomainRepository(db.DB)
serverRepo := repository.NewSQLServerRepository(db.DB)
auditRepo := repository.NewSQLAuditRepository(db.DB)
sshKeys := sshkey.NewService(secretStore)
accounts := certificate.NewAccountRepository(secretStore)
certificates := certificate.NewService(cfg, repo, secretStore, dnsprovider.NewLegoFactory(), accounts)
renewal := certificate.NewRenewalScheduler(repo, certificates, cfg.ACME.RenewalThresholdDays)
deploymentService := deployment.NewService(deployment.SSHFactory{Secrets: secretStore})
workflow := &CertificateWorkflow{Certificates: certificates, Domains: repo, Servers: serverRepo, Deployment: deploymentService}
renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays)
server := httpapi.New(httpapi.Dependencies{
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo,
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, SSHKeys: sshKeys,
SetupDNS: dnsVerification, Firewall: firewall.NewManager(),
IssueCertificate: workflow.IssueForHTTP,
ResetStatePath: admin.StatePath(cfg.Paths.Data),
Audit: auditRepo,
})
return &App{
Config: cfg, Logger: logger, Database: db, Repository: repo,
SecretStore: secretStore, DNSVerification: dnsVerification, HTTP: server,
Servers: serverRepo, Deployment: deploymentService,
SecretStore: secretStore, SSHKeys: sshKeys, DNSVerification: dnsVerification, HTTP: server,
Certificates: certificates,
Workflow: workflow,
Renewal: renewal,
}, nil
}
@@ -0,0 +1,120 @@
package app
import (
"context"
"errors"
"fmt"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
type CertificateWorkflow struct {
Certificates certificateService
Domains domainDeploymentRepository
Servers serverLister
Deployment savedDeployer
}
type certificateService interface {
Issue(context.Context, string) (certificate.IssueResult, error)
Import(context.Context, certificate.ImportRequest) (certificate.IssueResult, error)
}
type serverLister interface {
ListServersByDomainID(context.Context, string) ([]deployment.Server, error)
}
type savedDeployer interface {
DeploySaved(context.Context, []deployment.Target, deployment.SavedFiles) (deployment.Report, error)
}
type domainDeploymentRepository interface {
GetByID(context.Context, string) (domain.Domain, error)
UpdateCertificateState(context.Context, string, string, *time.Time) error
}
type CertificateWorkflowResult struct {
Certificate certificate.IssueResult `json:"certificate"`
Deployment deployment.Report `json:"deployment"`
}
func (w *CertificateWorkflow) Issue(ctx context.Context, domainID string) (certificate.IssueResult, error) {
result, err := w.IssueWithReport(ctx, domainID)
return result.Certificate, err
}
func (w *CertificateWorkflow) IssueWithReport(ctx context.Context, domainID string) (CertificateWorkflowResult, error) {
if w == nil || w.Certificates == nil || w.Domains == nil || w.Servers == nil || w.Deployment == nil {
return CertificateWorkflowResult{}, errors.New("证书部署流程未初始化")
}
certificateResult, err := w.Certificates.Issue(ctx, domainID)
if err != nil {
return CertificateWorkflowResult{}, err
}
report, err := w.deploy(ctx, certificateResult)
if err != nil {
w.markDeploymentError(certificateResult)
}
return CertificateWorkflowResult{Certificate: certificateResult, Deployment: report}, err
}
func (w *CertificateWorkflow) IssueForHTTP(ctx context.Context, domainID string) (certificate.IssueResult, deployment.Report, error) {
result, err := w.IssueWithReport(ctx, domainID)
return result.Certificate, result.Deployment, err
}
func (w *CertificateWorkflow) Import(ctx context.Context, request certificate.ImportRequest) (CertificateWorkflowResult, error) {
if w == nil || w.Certificates == nil || w.Domains == nil || w.Servers == nil || w.Deployment == nil {
return CertificateWorkflowResult{}, errors.New("证书部署流程未初始化")
}
certificateResult, err := w.Certificates.Import(ctx, request)
if err != nil {
return CertificateWorkflowResult{}, err
}
report, err := w.deploy(ctx, certificateResult)
if err != nil {
w.markDeploymentError(certificateResult)
}
return CertificateWorkflowResult{Certificate: certificateResult, Deployment: report}, err
}
func (w *CertificateWorkflow) deploy(ctx context.Context, result certificate.IssueResult) (deployment.Report, error) {
domainItem, err := w.Domains.GetByID(ctx, result.DomainID)
if err != nil {
return deployment.Report{}, fmt.Errorf("查询域名配置失败:%w", err)
}
servers, err := w.Servers.ListServersByDomainID(ctx, result.DomainID)
if err != nil {
return deployment.Report{}, fmt.Errorf("查询域名部署服务器失败:%w", err)
}
targets := make([]deployment.Target, 0, len(servers))
for _, server := range servers {
resolved, resolveErr := deployment.ResolveServerPaths(server, domainItem.Name, string(domainItem.CertificateType))
if resolveErr != nil {
return deployment.Report{}, fmt.Errorf("解析服务器 %s 的证书路径失败:%w", server.Name, resolveErr)
}
targets = append(targets, deployment.Target{Server: resolved})
}
report, err := w.Deployment.DeploySaved(ctx, targets, deployment.SavedFiles{
CertificatePath: result.Saved.CertificatePath,
FullChainPath: result.Saved.FullChainPath,
PrivateKeyPath: result.Saved.PrivateKeyPath,
})
if err != nil {
return report, err
}
if report.Status != "success" {
return report, fmt.Errorf("证书部署未全部成功:成功 %d 台,失败 %d 台", report.Success, report.Failed)
}
return report, nil
}
func (w *CertificateWorkflow) markDeploymentError(result certificate.IssueResult) {
if w == nil || w.Domains == nil {
return
}
_ = w.Domains.UpdateCertificateState(context.Background(), result.DomainID, "error", &result.Saved.NotAfter)
}
@@ -0,0 +1,145 @@
package app
import (
"context"
"testing"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
type workflowCertificateService struct {
result certificate.IssueResult
called bool
}
func (s *workflowCertificateService) Issue(context.Context, string) (certificate.IssueResult, error) {
s.called = true
return s.result, nil
}
func (s *workflowCertificateService) Import(context.Context, certificate.ImportRequest) (certificate.IssueResult, error) {
s.called = true
return s.result, nil
}
type workflowServerLister struct {
servers []deployment.Server
}
func (s workflowServerLister) ListServersByDomainID(context.Context, string) ([]deployment.Server, error) {
return s.servers, nil
}
type workflowDeployer struct {
targets []deployment.Target
files deployment.SavedFiles
report deployment.Report
}
type workflowDomainState struct {
id string
status string
item domain.Domain
}
func (s *workflowDomainState) GetByID(_ context.Context, id string) (domain.Domain, error) {
item := s.item
if item.ID == "" {
item.ID = id
}
if item.Name == "" {
item.Name = "example.com"
}
if item.CertificateType == "" {
item.CertificateType = domain.CertificateSingle
}
return item, nil
}
func (s *workflowDomainState) UpdateCertificateState(_ context.Context, id, status string, _ *time.Time) error {
s.id, s.status = id, status
return nil
}
func (d *workflowDeployer) DeploySaved(_ context.Context, targets []deployment.Target, files deployment.SavedFiles) (deployment.Report, error) {
d.targets = targets
d.files = files
return d.report, nil
}
func TestCertificateWorkflowDeploysIssuedCertificateToAssociatedServers(t *testing.T) {
certificateService := &workflowCertificateService{result: certificate.IssueResult{
DomainID: "domain-1",
Saved: certificate.SavedResource{CertificatePath: "cert.pem", FullChainPath: "fullchain.pem", PrivateKeyPath: "key.pem"},
}}
deployer := &workflowDeployer{report: deployment.Report{Total: 1, Success: 1, Status: "success"}}
state := &workflowDomainState{item: domain.Domain{ID: "domain-1", Name: "example.com", CertificateType: domain.CertificateSingle}}
workflow := &CertificateWorkflow{
Certificates: certificateService,
Domains: state,
Servers: workflowServerLister{servers: []deployment.Server{{ID: "server-1", Name: "生产服务器"}}},
Deployment: deployer,
}
result, err := workflow.IssueWithReport(context.Background(), "domain-1")
if err != nil {
t.Fatalf("证书工作流失败:%v", err)
}
if !certificateService.called || result.Deployment.Status != "success" || len(deployer.targets) != 1 {
t.Fatalf("证书工作流结果错误:%+v %+v", result, deployer.targets)
}
if deployer.files.PrivateKeyPath != "key.pem" {
t.Fatalf("部署文件路径错误:%+v", deployer.files)
}
if deployer.targets[0].Server.CertificatePath != "/ssl/example.com/single/cert.pem" || deployer.targets[0].Server.PrivateKeyPath != "/ssl/example.com/single/key.pem" {
t.Fatalf("部署目标路径未按域名和证书类型解析:%+v", deployer.targets[0].Server)
}
}
func TestCertificateWorkflowReturnsPartialDeploymentError(t *testing.T) {
deployer := &workflowDeployer{report: deployment.Report{Total: 2, Success: 1, Failed: 1, Status: "partial"}}
state := &workflowDomainState{item: domain.Domain{ID: "domain-1", Name: "*.example.com", CertificateType: domain.CertificateWildcard}}
workflow := &CertificateWorkflow{
Certificates: &workflowCertificateService{result: certificate.IssueResult{DomainID: "domain-1"}},
Domains: state,
Servers: workflowServerLister{servers: []deployment.Server{{ID: "server-1"}, {ID: "server-2"}}},
Deployment: deployer,
}
result, err := workflow.IssueWithReport(context.Background(), "domain-1")
if err == nil || result.Deployment.Status != "partial" {
t.Fatalf("部分部署应返回错误和报告:%+v %v", result, err)
}
if result.Certificate.DomainID != "domain-1" {
t.Fatalf("证书结果未保留:%+v", result.Certificate)
}
if state.id != "domain-1" || state.status != "error" {
t.Fatalf("部署失败后域名状态未标记为错误:%+v", state)
}
}
func TestCertificateWorkflowResolvesSameServerForDifferentDomains(t *testing.T) {
server := deployment.Server{ID: "server-1", Name: "共享服务器"}
deployer := &workflowDeployer{report: deployment.Report{Total: 1, Success: 1, Status: "success"}}
state := &workflowDomainState{item: domain.Domain{ID: "domain-1", Name: "example.com", CertificateType: domain.CertificateSAN}}
workflow := &CertificateWorkflow{
Certificates: &workflowCertificateService{result: certificate.IssueResult{DomainID: "domain-1"}},
Domains: state,
Servers: workflowServerLister{servers: []deployment.Server{server}},
Deployment: deployer,
}
if _, err := workflow.IssueWithReport(context.Background(), "domain-1"); err != nil {
t.Fatalf("第一个域名部署失败:%v", err)
}
firstPath := deployer.targets[0].Server.CertificatePath
state.item = domain.Domain{ID: "domain-2", Name: "api.example.net", CertificateType: domain.CertificateSingle}
workflow.Certificates = &workflowCertificateService{result: certificate.IssueResult{DomainID: "domain-2"}}
if _, err := workflow.IssueWithReport(context.Background(), "domain-2"); err != nil {
t.Fatalf("第二个域名部署失败:%v", err)
}
secondPath := deployer.targets[0].Server.CertificatePath
if firstPath != "/ssl/example.com/san/cert.pem" || secondPath != "/ssl/api.example.net/single/cert.pem" || firstPath == secondPath {
t.Fatalf("共享服务器的域名部署路径发生覆盖:%s %s", firstPath, secondPath)
}
}