完善证书管理与初始化流程
This commit is contained in:
1 parent
07636abe44
commit
c74372284a
84 files changed
+10151
-3502
No files matched your search
@@ -0,0 +1,22 @@
|
||||
package deployment
|
||||
|
||||
import "context"
|
||||
|
||||
type CommandResult struct {
|
||||
Output []byte
|
||||
ExitCode int
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
MkdirAll(ctx context.Context, path string) error
|
||||
Exists(ctx context.Context, path string) (bool, error)
|
||||
Upload(ctx context.Context, path string, data []byte, mode uint32) error
|
||||
Rename(ctx context.Context, source, target string) error
|
||||
Remove(ctx context.Context, path string) error
|
||||
Run(ctx context.Context, command []string) (CommandResult, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
type ClientFactory interface {
|
||||
Connect(ctx context.Context, server Server) (Client, error)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type WebServer string
|
||||
|
||||
const (
|
||||
WebServerNginx WebServer = "nginx"
|
||||
WebServerCaddy WebServer = "caddy"
|
||||
WebServerApache WebServer = "apache"
|
||||
WebServerCustom WebServer = "custom"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultCertificatePath = "/ssl/{域名}/{证书类型}/cert.pem"
|
||||
DefaultCertificateChainPath = "/ssl/{域名}/{证书类型}/fullchain.pem"
|
||||
DefaultPrivateKeyPath = "/ssl/{域名}/{证书类型}/key.pem"
|
||||
)
|
||||
|
||||
var serverPathPlaceholderPattern = regexp.MustCompile(`\{[^{}]+\}`)
|
||||
|
||||
type Server struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
PrivateKeyRef string `json:"private_key_ref"`
|
||||
HostKeyFingerprint string `json:"host_key_fingerprint"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
CertificateChainPath string `json:"certificate_chain_path"`
|
||||
WebServer WebServer `json:"web_server"`
|
||||
ReloadCommand []string `json:"reload_command,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s Server) Normalize() Server {
|
||||
s.ID = strings.TrimSpace(s.ID)
|
||||
s.Name = strings.TrimSpace(s.Name)
|
||||
s.Address = strings.TrimSpace(s.Address)
|
||||
s.Username = strings.TrimSpace(s.Username)
|
||||
s.PrivateKeyRef = strings.TrimSpace(s.PrivateKeyRef)
|
||||
s.HostKeyFingerprint = strings.TrimSpace(s.HostKeyFingerprint)
|
||||
s.CertificatePath = strings.TrimSpace(s.CertificatePath)
|
||||
s.PrivateKeyPath = strings.TrimSpace(s.PrivateKeyPath)
|
||||
s.CertificateChainPath = strings.TrimSpace(s.CertificateChainPath)
|
||||
if s.CertificatePath == "" {
|
||||
s.CertificatePath = DefaultCertificatePath
|
||||
}
|
||||
if s.CertificateChainPath == "" {
|
||||
s.CertificateChainPath = DefaultCertificateChainPath
|
||||
}
|
||||
if s.PrivateKeyPath == "" {
|
||||
s.PrivateKeyPath = DefaultPrivateKeyPath
|
||||
}
|
||||
s.WebServer = WebServer(strings.ToLower(strings.TrimSpace(string(s.WebServer))))
|
||||
if s.Port == 0 {
|
||||
s.Port = 22
|
||||
}
|
||||
if len(s.ReloadCommand) == 0 {
|
||||
s.ReloadCommand = DefaultReloadCommand(s.WebServer)
|
||||
}
|
||||
for index := range s.ReloadCommand {
|
||||
s.ReloadCommand[index] = strings.TrimSpace(s.ReloadCommand[index])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func ResolveServerPaths(server Server, domainName, certificateType string) (Server, error) {
|
||||
server = server.Normalize()
|
||||
domainDirectory, err := normalizeDomainDirectory(domainName)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
certificateType = strings.ToLower(strings.TrimSpace(certificateType))
|
||||
switch certificateType {
|
||||
case "single", "wildcard", "san":
|
||||
default:
|
||||
return Server{}, fmt.Errorf("证书类型无法用于远程路径:%s", certificateType)
|
||||
}
|
||||
replacer := strings.NewReplacer(
|
||||
"{域名}", domainDirectory,
|
||||
"{domain}", domainDirectory,
|
||||
"{证书类型}", certificateType,
|
||||
"{certificate_type}", certificateType,
|
||||
)
|
||||
server.CertificatePath, err = resolveServerPathTemplate("远程证书路径", server.CertificatePath, replacer)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
server.CertificateChainPath, err = resolveServerPathTemplate("远程完整证书链路径", server.CertificateChainPath, replacer)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
server.PrivateKeyPath, err = resolveServerPathTemplate("远程私钥路径", server.PrivateKeyPath, replacer)
|
||||
if err != nil {
|
||||
return Server{}, err
|
||||
}
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func normalizeDomainDirectory(value string) (string, error) {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
value = strings.TrimPrefix(value, "*.")
|
||||
if value == "" || value == "." || value == ".." || strings.ContainsAny(value, "/\\\x00\r\n") {
|
||||
return "", fmt.Errorf("域名无法用于远程路径:%s", value)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func resolveServerPathTemplate(label, value string, replacer *strings.Replacer) (string, error) {
|
||||
resolved := replacer.Replace(strings.TrimSpace(value))
|
||||
if placeholder := serverPathPlaceholderPattern.FindString(resolved); placeholder != "" {
|
||||
return "", fmt.Errorf("%s包含不支持的占位符:%s", label, placeholder)
|
||||
}
|
||||
cleaned := RemotePath(resolved)
|
||||
if cleaned == "" || cleaned == "." {
|
||||
return "", fmt.Errorf("%s无效", label)
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
func (s Server) Validate() error {
|
||||
s = s.Normalize()
|
||||
if s.ID == "" {
|
||||
return errors.New("服务器 ID 不能为空")
|
||||
}
|
||||
if s.Name == "" {
|
||||
return errors.New("服务器名称不能为空")
|
||||
}
|
||||
if s.Address == "" || net.ParseIP(s.Address) == nil && strings.ContainsAny(s.Address, " /\\") {
|
||||
return errors.New("服务器地址无效")
|
||||
}
|
||||
if s.Port < 1 || s.Port > 65535 {
|
||||
return errors.New("SSH 端口无效")
|
||||
}
|
||||
if s.Username == "" {
|
||||
return errors.New("SSH 用户不能为空")
|
||||
}
|
||||
if s.PrivateKeyRef == "" {
|
||||
return errors.New("SSH 私钥引用不能为空")
|
||||
}
|
||||
if s.HostKeyFingerprint == "" {
|
||||
return errors.New("SSH 主机指纹不能为空")
|
||||
}
|
||||
if s.CertificatePath == "" || s.PrivateKeyPath == "" || s.CertificateChainPath == "" {
|
||||
return errors.New("远程证书路径不能为空")
|
||||
}
|
||||
if _, err := ResolveServerPaths(s, "example.com", "single"); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.WebServer != WebServerNginx && s.WebServer != WebServerCaddy && s.WebServer != WebServerApache && s.WebServer != WebServerCustom {
|
||||
return fmt.Errorf("网站服务类型无效:%s", s.WebServer)
|
||||
}
|
||||
if len(s.ReloadCommand) == 0 || s.ReloadCommand[0] == "" {
|
||||
return errors.New("reload 命令不能为空")
|
||||
}
|
||||
for _, argument := range s.ReloadCommand {
|
||||
if argument == "" || strings.ContainsAny(argument, "\x00\r\n") {
|
||||
return errors.New("reload 命令参数无效")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DefaultReloadCommand(webServer WebServer) []string {
|
||||
switch WebServer(strings.ToLower(strings.TrimSpace(string(webServer)))) {
|
||||
case WebServerNginx:
|
||||
return []string{"nginx", "-s", "reload"}
|
||||
case WebServerCaddy:
|
||||
return []string{"caddy", "reload"}
|
||||
case WebServerApache:
|
||||
return []string{"apachectl", "-k", "graceful"}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func RemotePath(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
return ""
|
||||
}
|
||||
return path.Clean(strings.ReplaceAll(value, "\\", "/"))
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package deployment
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestServerUsesDefaultReloadCommand(t *testing.T) {
|
||||
server := testServer("one").Normalize()
|
||||
if err := server.Validate(); err != nil {
|
||||
t.Fatalf("服务器配置校验失败:%v", err)
|
||||
}
|
||||
if len(server.ReloadCommand) != 3 || server.ReloadCommand[0] != "nginx" {
|
||||
t.Fatalf("Nginx 默认 reload 命令错误:%v", server.ReloadCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerUsesDefaultCertificatePathTemplates(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.CertificatePath = ""
|
||||
server.CertificateChainPath = ""
|
||||
server.PrivateKeyPath = ""
|
||||
server = server.Normalize()
|
||||
if server.CertificatePath != DefaultCertificatePath || server.CertificateChainPath != DefaultCertificateChainPath || server.PrivateKeyPath != DefaultPrivateKeyPath {
|
||||
t.Fatalf("远程证书默认路径模板错误:%+v", server)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveServerPathsByCertificateType(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
domainName string
|
||||
certificateType string
|
||||
expectedRoot string
|
||||
}{
|
||||
{name: "单域名", domainName: "example.com", certificateType: "single", expectedRoot: "/ssl/example.com/single"},
|
||||
{name: "泛域名", domainName: "*.example.com", certificateType: "wildcard", expectedRoot: "/ssl/example.com/wildcard"},
|
||||
{name: "SAN", domainName: "example.com", certificateType: "san", expectedRoot: "/ssl/example.com/san"},
|
||||
}
|
||||
for _, item := range tests {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.CertificatePath = ""
|
||||
server.CertificateChainPath = ""
|
||||
server.PrivateKeyPath = ""
|
||||
resolved, err := ResolveServerPaths(server, item.domainName, item.certificateType)
|
||||
if err != nil {
|
||||
t.Fatalf("解析远程证书路径失败:%v", err)
|
||||
}
|
||||
if resolved.CertificatePath != item.expectedRoot+"/cert.pem" || resolved.CertificateChainPath != item.expectedRoot+"/fullchain.pem" || resolved.PrivateKeyPath != item.expectedRoot+"/key.pem" {
|
||||
t.Fatalf("远程证书路径解析错误:%+v", resolved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveServerPathsKeepsCustomPathAndRejectsUnknownPlaceholder(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.CertificatePath = "/custom/{domain}/{certificate_type}/certificate.crt"
|
||||
resolved, err := ResolveServerPaths(server, "example.com", "single")
|
||||
if err != nil {
|
||||
t.Fatalf("解析自定义远程证书路径失败:%v", err)
|
||||
}
|
||||
if resolved.CertificatePath != "/custom/example.com/single/certificate.crt" {
|
||||
t.Fatalf("自定义远程证书路径被错误处理:%s", resolved.CertificatePath)
|
||||
}
|
||||
server.CertificatePath = "/ssl/{未知占位符}/cert.pem"
|
||||
if _, err := ResolveServerPaths(server, "example.com", "single"); err == nil {
|
||||
t.Fatal("包含未知占位符的远程证书路径应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerRejectsPasswordStyleOrUnsafeConfiguration(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.PrivateKeyRef = ""
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("未配置 SSH 私钥引用时应拒绝服务器配置")
|
||||
}
|
||||
server = testServer("one")
|
||||
server.ReloadCommand = []string{"nginx\nrm", "-s", "reload"}
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("reload 参数包含换行时应拒绝服务器配置")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Target struct {
|
||||
Server Server
|
||||
}
|
||||
|
||||
type Artifact struct {
|
||||
Certificate []byte
|
||||
FullChain []byte
|
||||
PrivateKey []byte
|
||||
}
|
||||
|
||||
type SavedFiles struct {
|
||||
CertificatePath string
|
||||
FullChainPath string
|
||||
PrivateKeyPath string
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
ServerID string `json:"server_id"`
|
||||
Server string `json:"server"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
BackupID string `json:"backup_id,omitempty"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Total int `json:"total"`
|
||||
Success int `json:"success"`
|
||||
Failed int `json:"failed"`
|
||||
Status string `json:"status"`
|
||||
Results []Result `json:"results"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
factory ClientFactory
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewService(factory ClientFactory) *Service {
|
||||
return &Service{factory: factory, now: time.Now}
|
||||
}
|
||||
|
||||
func (s *Service) Deploy(ctx context.Context, targets []Target, artifact Artifact) Report {
|
||||
report := Report{Total: len(targets), Results: make([]Result, 0, len(targets))}
|
||||
if s == nil || s.factory == nil {
|
||||
report.Status = "failed"
|
||||
report.Failed = len(targets)
|
||||
for _, target := range targets {
|
||||
report.Results = append(report.Results, Result{ServerID: target.Server.ID, Server: target.Server.Name, Status: "failed", Message: "部署服务未初始化"})
|
||||
}
|
||||
return report
|
||||
}
|
||||
if err := validateArtifact(artifact); err != nil {
|
||||
report.Status = "failed"
|
||||
report.Failed = len(targets)
|
||||
for _, target := range targets {
|
||||
report.Results = append(report.Results, Result{ServerID: target.Server.ID, Server: target.Server.Name, Status: "failed", Message: err.Error()})
|
||||
}
|
||||
return report
|
||||
}
|
||||
for _, target := range targets {
|
||||
result := s.deployOne(ctx, target.Server, artifact)
|
||||
report.Results = append(report.Results, result)
|
||||
if result.Status == "success" {
|
||||
report.Success++
|
||||
} else {
|
||||
report.Failed++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case report.Failed == 0:
|
||||
report.Status = "success"
|
||||
case report.Success == 0:
|
||||
report.Status = "failed"
|
||||
default:
|
||||
report.Status = "partial"
|
||||
}
|
||||
return report
|
||||
}
|
||||
|
||||
func (s *Service) DeploySaved(ctx context.Context, targets []Target, saved SavedFiles) (Report, error) {
|
||||
certificateData, err := os.ReadFile(saved.CertificatePath)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("读取证书文件失败:%w", err)
|
||||
}
|
||||
fullChainData, err := os.ReadFile(saved.FullChainPath)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("读取完整证书链失败:%w", err)
|
||||
}
|
||||
privateKeyData, err := os.ReadFile(saved.PrivateKeyPath)
|
||||
if err != nil {
|
||||
return Report{}, fmt.Errorf("读取私钥文件失败:%w", err)
|
||||
}
|
||||
return s.Deploy(ctx, targets, Artifact{Certificate: certificateData, FullChain: fullChainData, PrivateKey: privateKeyData}), nil
|
||||
}
|
||||
|
||||
func (s *Service) deployOne(ctx context.Context, server Server, artifact Artifact) Result {
|
||||
server = server.Normalize()
|
||||
result := Result{ServerID: server.ID, Server: server.Name, Status: "failed"}
|
||||
if err := server.Validate(); err != nil {
|
||||
result.Message = err.Error()
|
||||
return result
|
||||
}
|
||||
client, err := s.factory.Connect(ctx, server)
|
||||
if err != nil {
|
||||
result.Message = fmt.Sprintf("连接服务器失败:%v", err)
|
||||
return result
|
||||
}
|
||||
defer client.Close()
|
||||
paths := []remoteFile{
|
||||
{path: RemotePath(server.CertificatePath), data: artifact.Certificate, mode: 0o644},
|
||||
{path: RemotePath(server.CertificateChainPath), data: artifact.FullChain, mode: 0o644},
|
||||
{path: RemotePath(server.PrivateKeyPath), data: artifact.PrivateKey, mode: 0o600},
|
||||
}
|
||||
for _, file := range paths {
|
||||
if file.path == "" || file.path == "." {
|
||||
result.Message = "远程证书路径无效"
|
||||
return result
|
||||
}
|
||||
}
|
||||
backupID := s.backupID()
|
||||
type backup struct{ original, saved string }
|
||||
backups := make([]backup, 0, len(paths))
|
||||
temporary := make([]string, 0, len(paths))
|
||||
installed := make([]string, 0, len(paths))
|
||||
rollback := func() {
|
||||
for _, path := range temporary {
|
||||
_ = client.Remove(context.Background(), path)
|
||||
}
|
||||
for _, path := range installed {
|
||||
_ = client.Remove(context.Background(), path)
|
||||
}
|
||||
for index := len(backups) - 1; index >= 0; index-- {
|
||||
item := backups[index]
|
||||
_ = client.Rename(context.Background(), item.saved, item.original)
|
||||
}
|
||||
}
|
||||
for _, file := range paths {
|
||||
if err := client.MkdirAll(ctx, parentPath(file.path)); err != nil {
|
||||
result.Message = fmt.Sprintf("创建远程目录失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
exists, err := client.Exists(ctx, file.path)
|
||||
if err != nil {
|
||||
result.Message = fmt.Sprintf("检查远程文件失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
if exists {
|
||||
backupPath := file.path + ".scert-backup-" + backupID
|
||||
if err := client.Rename(ctx, file.path, backupPath); err != nil {
|
||||
result.Message = fmt.Sprintf("备份远程证书失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
backups = append(backups, backup{original: file.path, saved: backupPath})
|
||||
}
|
||||
temporaryPath := file.path + ".scert-tmp-" + backupID
|
||||
if err := client.Upload(ctx, temporaryPath, file.data, file.mode); err != nil {
|
||||
result.Message = fmt.Sprintf("上传远程证书失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
temporary = append(temporary, temporaryPath)
|
||||
if err := client.Rename(ctx, temporaryPath, file.path); err != nil {
|
||||
result.Message = fmt.Sprintf("替换远程证书失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
temporary = temporary[:len(temporary)-1]
|
||||
installed = append(installed, file.path)
|
||||
}
|
||||
commandResult, err := client.Run(ctx, server.ReloadCommand)
|
||||
if err != nil || commandResult.ExitCode != 0 {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("退出码 %d", commandResult.ExitCode)
|
||||
}
|
||||
result.Message = fmt.Sprintf("reload 失败:%v", err)
|
||||
rollback()
|
||||
return result
|
||||
}
|
||||
result.Status = "success"
|
||||
result.Message = "证书部署并 reload 成功"
|
||||
result.BackupID = backupID
|
||||
return result
|
||||
}
|
||||
|
||||
type remoteFile struct {
|
||||
path string
|
||||
data []byte
|
||||
mode uint32
|
||||
}
|
||||
|
||||
func validateArtifact(artifact Artifact) error {
|
||||
if len(artifact.Certificate) == 0 || len(artifact.FullChain) == 0 || len(artifact.PrivateKey) == 0 {
|
||||
return errors.New("证书部署文件不完整")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) backupID() string {
|
||||
var random [6]byte
|
||||
_, _ = rand.Read(random[:])
|
||||
now := time.Now
|
||||
if s.now != nil {
|
||||
now = s.now
|
||||
}
|
||||
return now().UTC().Format("20060102-150405.000000000") + "-" + hex.EncodeToString(random[:])
|
||||
}
|
||||
|
||||
func parentPath(path string) string {
|
||||
index := strings.LastIndexAny(path, "/\\")
|
||||
if index < 1 {
|
||||
return "."
|
||||
}
|
||||
return path[:index]
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type memoryFile struct {
|
||||
data []byte
|
||||
mode uint32
|
||||
}
|
||||
|
||||
type memoryClient struct {
|
||||
files map[string]memoryFile
|
||||
command []string
|
||||
runResult CommandResult
|
||||
runErr error
|
||||
uploadError string
|
||||
}
|
||||
|
||||
func newMemoryClient() *memoryClient {
|
||||
return &memoryClient{files: map[string]memoryFile{}, runResult: CommandResult{ExitCode: 0}}
|
||||
}
|
||||
|
||||
func (c *memoryClient) MkdirAll(context.Context, string) error { return nil }
|
||||
|
||||
func (c *memoryClient) Exists(_ context.Context, path string) (bool, error) {
|
||||
_, ok := c.files[path]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Upload(_ context.Context, path string, data []byte, mode uint32) error {
|
||||
if c.uploadError != "" && strings.Contains(path, c.uploadError) {
|
||||
return errors.New("模拟上传失败")
|
||||
}
|
||||
c.files[path] = memoryFile{data: append([]byte(nil), data...), mode: mode}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Rename(_ context.Context, source, target string) error {
|
||||
value, ok := c.files[source]
|
||||
if !ok {
|
||||
return errors.New("源文件不存在")
|
||||
}
|
||||
delete(c.files, source)
|
||||
c.files[target] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Remove(_ context.Context, path string) error {
|
||||
delete(c.files, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryClient) Run(_ context.Context, command []string) (CommandResult, error) {
|
||||
c.command = append([]string(nil), command...)
|
||||
return c.runResult, c.runErr
|
||||
}
|
||||
|
||||
func (c *memoryClient) Close() error { return nil }
|
||||
|
||||
type memoryFactory struct {
|
||||
clients map[string]*memoryClient
|
||||
errors map[string]error
|
||||
}
|
||||
|
||||
func (f memoryFactory) Connect(_ context.Context, server Server) (Client, error) {
|
||||
if err := f.errors[server.ID]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.clients[server.ID], nil
|
||||
}
|
||||
|
||||
func TestDeployReplacesFilesAndKeepsBackup(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
client.files[server.CertificateChainPath] = memoryFile{data: []byte("old-chain"), mode: 0o644}
|
||||
client.files[server.PrivateKeyPath] = memoryFile{data: []byte("old-key"), mode: 0o600}
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{server.ID: client}})
|
||||
service.now = func() time.Time { return time.Date(2026, 8, 27, 1, 2, 3, 4, time.UTC) }
|
||||
report := service.Deploy(context.Background(), []Target{{Server: server}}, testArtifact())
|
||||
if report.Status != "success" || report.Success != 1 {
|
||||
t.Fatalf("部署结果错误:%+v", report)
|
||||
}
|
||||
if string(client.files[server.CertificatePath].data) != "new-cert" || client.files[server.PrivateKeyPath].mode != 0o600 {
|
||||
t.Fatalf("远程证书内容或权限错误:%+v", client.files)
|
||||
}
|
||||
if len(client.command) != 3 || client.command[0] != "nginx" {
|
||||
t.Fatalf("reload 命令错误:%v", client.command)
|
||||
}
|
||||
backupCount := 0
|
||||
for path := range client.files {
|
||||
if strings.Contains(path, ".scert-backup-") {
|
||||
backupCount++
|
||||
}
|
||||
}
|
||||
if backupCount != 3 {
|
||||
t.Fatalf("成功部署后应保留三份远程备份:%d", backupCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployRollsBackWhenReloadFails(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
client.runResult.ExitCode = 1
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{server.ID: client}})
|
||||
report := service.Deploy(context.Background(), []Target{{Server: server}}, testArtifact())
|
||||
if report.Status != "failed" || report.Failed != 1 {
|
||||
t.Fatalf("reload 失败结果错误:%+v", report)
|
||||
}
|
||||
if string(client.files[server.CertificatePath].data) != "old-cert" {
|
||||
t.Fatalf("reload 失败后旧证书未恢复:%+v", client.files)
|
||||
}
|
||||
if _, ok := client.files[server.PrivateKeyPath]; ok {
|
||||
t.Fatal("原本不存在的私钥文件应在回滚时删除")
|
||||
}
|
||||
for path := range client.files {
|
||||
if strings.Contains(path, ".scert-tmp-") || strings.Contains(path, ".scert-backup-") {
|
||||
t.Fatalf("回滚后不应残留临时文件或备份文件:%s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployReportsPartialSuccess(t *testing.T) {
|
||||
first := newMemoryClient()
|
||||
second := newMemoryClient()
|
||||
second.uploadError = "fullchain.pem"
|
||||
firstServer := testServer("first")
|
||||
secondServer := testServer("second")
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{"first": first, "second": second}})
|
||||
report := service.Deploy(context.Background(), []Target{{Server: firstServer}, {Server: secondServer}}, testArtifact())
|
||||
if report.Status != "partial" || report.Success != 1 || report.Failed != 1 {
|
||||
t.Fatalf("部分成功汇总错误:%+v", report)
|
||||
}
|
||||
}
|
||||
|
||||
func testServer(id string) Server {
|
||||
return Server{
|
||||
ID: id, Name: id, Address: "192.0.2.10", Port: 22, Username: "deploy",
|
||||
PrivateKeyRef: "secret://ssh/" + id, HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/etc/scert/cert.pem", CertificateChainPath: "/etc/scert/fullchain.pem",
|
||||
PrivateKeyPath: "/etc/scert/key.pem", WebServer: WebServerNginx,
|
||||
}
|
||||
}
|
||||
|
||||
func testArtifact() Artifact {
|
||||
return Artifact{Certificate: []byte("new-cert"), FullChain: []byte("new-chain"), PrivateKey: []byte("new-key")}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type SecretReader interface {
|
||||
Get(ctx context.Context, reference string) (map[string]string, error)
|
||||
}
|
||||
|
||||
type SSHFactory struct {
|
||||
Secrets SecretReader
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (f SSHFactory) Connect(ctx context.Context, server Server) (Client, error) {
|
||||
server = server.Normalize()
|
||||
if err := server.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.Secrets == nil {
|
||||
return nil, errors.New("SSH 敏感信息存储未初始化")
|
||||
}
|
||||
secrets, err := f.Secrets.Get(ctx, server.PrivateKeyRef)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 SSH 私钥失败:%w", err)
|
||||
}
|
||||
privateKey := strings.TrimSpace(secrets["private_key"])
|
||||
if privateKey == "" {
|
||||
return nil, errors.New("SSH 私钥内容不能为空")
|
||||
}
|
||||
var signer ssh.Signer
|
||||
passphrase := secrets["passphrase"]
|
||||
if passphrase != "" {
|
||||
signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(privateKey), []byte(passphrase))
|
||||
} else {
|
||||
signer, err = ssh.ParsePrivateKey([]byte(privateKey))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.New("解析 SSH 私钥失败:私钥格式或口令无效")
|
||||
}
|
||||
timeout := f.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 15 * time.Second
|
||||
}
|
||||
address := net.JoinHostPort(server.Address, fmt.Sprintf("%d", server.Port))
|
||||
dialer := net.Dialer{Timeout: timeout}
|
||||
connection, err := dialer.DialContext(ctx, "tcp", address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("连接 SSH 服务器失败:%w", err)
|
||||
}
|
||||
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
fingerprint := ssh.FingerprintSHA256(key)
|
||||
if fingerprint != server.HostKeyFingerprint {
|
||||
return fmt.Errorf("SSH 主机指纹不匹配:服务器 %s 返回 %s", server.Name, fingerprint)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config := &ssh.ClientConfig{
|
||||
User: server.Username, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
|
||||
HostKeyCallback: hostKeyCallback, Timeout: timeout,
|
||||
}
|
||||
clientConn, channels, requests, err := ssh.NewClientConn(connection, address, config)
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("SSH 握手失败:%w", err)
|
||||
}
|
||||
sshClient := ssh.NewClient(clientConn, channels, requests)
|
||||
sftpClient, err := sftp.NewClient(sshClient)
|
||||
if err != nil {
|
||||
_ = sshClient.Close()
|
||||
return nil, fmt.Errorf("创建 SFTP 客户端失败:%w", err)
|
||||
}
|
||||
return &sshClientAdapter{ssh: sshClient, sftp: sftpClient}, nil
|
||||
}
|
||||
|
||||
type sshClientAdapter struct {
|
||||
ssh *ssh.Client
|
||||
sftp *sftp.Client
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) MkdirAll(ctx context.Context, path string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.sftp.MkdirAll(path)
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Exists(ctx context.Context, path string) (bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err := c.sftp.Stat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Upload(ctx context.Context, path string, data []byte, mode uint32) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := c.sftp.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
closeFile := func() error { return file.Close() }
|
||||
if _, err := file.Write(data); err != nil {
|
||||
_ = closeFile()
|
||||
return err
|
||||
}
|
||||
if err := file.Chmod(os.FileMode(mode)); err != nil {
|
||||
_ = closeFile()
|
||||
return err
|
||||
}
|
||||
return closeFile()
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Rename(ctx context.Context, source, target string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.sftp.Rename(source, target)
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Remove(ctx context.Context, path string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
err := c.sftp.Remove(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Run(ctx context.Context, command []string) (CommandResult, error) {
|
||||
if len(command) == 0 {
|
||||
return CommandResult{}, errors.New("远程命令不能为空")
|
||||
}
|
||||
if err := validateCommand(command); err != nil {
|
||||
return CommandResult{}, err
|
||||
}
|
||||
session, err := c.ssh.NewSession()
|
||||
if err != nil {
|
||||
return CommandResult{}, err
|
||||
}
|
||||
defer session.Close()
|
||||
output, err := session.CombinedOutput(joinShellArgs(command))
|
||||
if err != nil {
|
||||
var exitError *ssh.ExitError
|
||||
if errors.As(err, &exitError) {
|
||||
return CommandResult{Output: output, ExitCode: exitError.ExitStatus()}, nil
|
||||
}
|
||||
return CommandResult{Output: output, ExitCode: -1}, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return CommandResult{Output: output, ExitCode: -1}, err
|
||||
}
|
||||
return CommandResult{Output: output}, nil
|
||||
}
|
||||
|
||||
func (c *sshClientAdapter) Close() error {
|
||||
var first error
|
||||
if c.sftp != nil {
|
||||
if err := c.sftp.Close(); err != nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
if c.ssh != nil {
|
||||
if err := c.ssh.Close(); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
func validateCommand(command []string) error {
|
||||
for _, token := range command {
|
||||
if strings.TrimSpace(token) == "" || strings.ContainsAny(token, "\x00\r\n") {
|
||||
return errors.New("远程命令参数无效")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func joinShellArgs(command []string) string {
|
||||
quoted := make([]string, len(command))
|
||||
for index, token := range command {
|
||||
quoted[index] = "'" + strings.ReplaceAll(token, "'", "'\\''") + "'"
|
||||
}
|
||||
return strings.Join(quoted, " ")
|
||||
}
|
||||
|
||||
var _ io.Closer = (*sshClientAdapter)(nil)
|
||||
@@ -0,0 +1,68 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/pem"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type staticSecretReader map[string]map[string]string
|
||||
|
||||
func (s staticSecretReader) Get(_ context.Context, reference string) (map[string]string, error) {
|
||||
return s[reference], nil
|
||||
}
|
||||
|
||||
func TestSSHFactoryParsesEncryptedPrivateKeyBeforeDialing(t *testing.T) {
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate test private key: %v", err)
|
||||
}
|
||||
block, err := ssh.MarshalPrivateKeyWithPassphrase(key, "scert-deployment-test", []byte("deployment-passphrase"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encrypt test private key: %v", err)
|
||||
}
|
||||
privateKey := string(pem.EncodeToMemory(block))
|
||||
server := Server{
|
||||
ID: "server-test", Name: "test server", Address: "127.0.0.1", Port: 1,
|
||||
Username: "deploy", PrivateKeyRef: "secret://ssh/test", HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/tmp/cert.pem", PrivateKeyPath: "/tmp/key.pem",
|
||||
CertificateChainPath: "/tmp/fullchain.pem", WebServer: WebServerNginx,
|
||||
}
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{server.PrivateKeyRef: {"private_key": privateKey, "passphrase": "deployment-passphrase"}},
|
||||
Timeout: 100 * time.Millisecond,
|
||||
}
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "\u8fde\u63a5 SSH \u670d\u52a1\u5668\u5931\u8d25") {
|
||||
t.Fatalf("encrypted private key should parse before the expected dial failure: %v", err)
|
||||
}
|
||||
factory.Secrets = staticSecretReader{server.PrivateKeyRef: {"private_key": privateKey, "passphrase": "wrong-passphrase"}}
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "\u89e3\u6790 SSH \u79c1\u94a5\u5931\u8d25") {
|
||||
t.Fatalf("wrong passphrase should be rejected before dialing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCommandRejectsShellControlLines(t *testing.T) {
|
||||
for _, command := range [][]string{
|
||||
{"nginx", "-s", "reload\nrm -rf /"},
|
||||
{"nginx", "", "reload"},
|
||||
{"nginx", "-s", "reload\x00"},
|
||||
} {
|
||||
if err := validateCommand(command); err == nil {
|
||||
t.Fatalf("不安全远程命令未被拒绝:%q", command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinShellArgsQuotesArguments(t *testing.T) {
|
||||
command := []string{"nginx", "-c", "/etc/nginx/my config.conf", "reload'check"}
|
||||
joined := joinShellArgs(command)
|
||||
if !strings.Contains(joined, "'/etc/nginx/my config.conf'") || !strings.Contains(joined, "'reload'\\''check'") {
|
||||
t.Fatalf("远程命令参数未正确转义:%s", joined)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user