完善 Scert 前后端与部署支持
This commit is contained in:
1 parent
afdb947bea
commit
7f0af703ed
85 files changed
+7530
-800
No files matched your search
@@ -16,8 +16,8 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/app"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
)
|
||||
|
||||
func newCertificateCommand() *cobra.Command {
|
||||
@@ -203,7 +203,7 @@ func newLogsCommand() *cobra.Command {
|
||||
|
||||
func newConfigCommand() *cobra.Command {
|
||||
command := &cobra.Command{Use: "config", Short: "查看和修改服务配置"}
|
||||
command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigValidateCommand())
|
||||
command.AddCommand(newConfigShowCommand(), newConfigSetCommand(), newConfigSetSecretCommand(), newConfigValidateCommand())
|
||||
return command
|
||||
}
|
||||
|
||||
@@ -221,6 +221,60 @@ func newConfigShowCommand() *cobra.Command {
|
||||
}
|
||||
}
|
||||
|
||||
func newConfigSetSecretCommand() *cobra.Command {
|
||||
var key, value string
|
||||
command := &cobra.Command{
|
||||
Use: "set-secret",
|
||||
Short: "安全更新 SMTP 敏感凭据",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if key != "notification.smtp_password" {
|
||||
return fmt.Errorf("不支持更新的敏感配置项:%s", key)
|
||||
}
|
||||
if value == "" {
|
||||
var err error
|
||||
value, err = ask(bufio.NewReader(cmd.InOrStdin()), cmd.OutOrStdout(), "请输入新的 SMTP 密码或授权码", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if value == "" {
|
||||
return errors.New("SMTP 密码不能为空")
|
||||
}
|
||||
cfg, err := loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
username := strings.TrimSpace(cfg.Notification.SMTPUsername)
|
||||
if username == "" {
|
||||
return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名")
|
||||
}
|
||||
store, err := secretstore.Open(cfg.Paths.Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("初始化 SMTP 凭据存储失败:%w", err)
|
||||
}
|
||||
ref, err := newSMTPCredentialReference()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store.Put(cmd.Context(), ref, map[string]string{"username": username, "password": value}); err != nil {
|
||||
return fmt.Errorf("保存 SMTP 凭据失败:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPCredentialRef = ref
|
||||
if err := cfg.Save(resolveConfigPath()); err != nil {
|
||||
cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cleanupCancel()
|
||||
_ = store.Delete(cleanupContext, ref)
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(cmd.OutOrStdout(), "SMTP 凭据已加密更新。")
|
||||
return err
|
||||
},
|
||||
}
|
||||
command.Flags().StringVar(&key, "key", "", "敏感配置项名称")
|
||||
command.Flags().StringVar(&value, "value", "", "SMTP 密码;留空时交互输入")
|
||||
_ = command.MarkFlagRequired("key")
|
||||
return command
|
||||
}
|
||||
func newConfigValidateCommand() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "validate",
|
||||
@@ -551,6 +605,27 @@ func setConfigValue(cfg *config.Config, key, value string) error {
|
||||
return fmt.Errorf("SMTP 通知开关格式无效:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPEnabled = parsed
|
||||
|
||||
case "notification.smtp_host":
|
||||
cfg.Notification.SMTPHost = value
|
||||
case "notification.smtp_port":
|
||||
parsed, err := parseInt()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 端口格式无效:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPPort = parsed
|
||||
case "notification.smtp_username":
|
||||
cfg.Notification.SMTPUsername = value
|
||||
case "notification.smtp_mode":
|
||||
cfg.Notification.SMTPMode = value
|
||||
case "notification.smtp_allow_plaintext_auth":
|
||||
parsed, err := parseBool()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 明文认证开关格式无效:%w", err)
|
||||
}
|
||||
cfg.Notification.SMTPAllowPlaintextAuth = parsed
|
||||
case "notification.smtp_password":
|
||||
return errors.New("SMTP 密码属于敏感信息,请使用 scert config set-secret --key notification.smtp_password")
|
||||
case "notification.provider":
|
||||
cfg.Notification.Provider = value
|
||||
case "notification.endpoint":
|
||||
|
||||
@@ -3,6 +3,8 @@ package cli
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -72,7 +74,7 @@ func newRootCommand() *cobra.Command {
|
||||
&cobra.Command{Use: "version", Short: "显示版本信息", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("Scert %s\n", version) }},
|
||||
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newCertificateCommand(),
|
||||
newRenewCommand(), newDeployCommand(), newLogsCommand(), newConfigCommand(), newBackupCommand(), newRestoreCommand(),
|
||||
newServerCommand(), newSSHKeyCommand(),
|
||||
newServerCommand(), newSSHKeyCommand(), newServiceCommand(),
|
||||
)
|
||||
localizeHelpFlags(root)
|
||||
return root
|
||||
@@ -117,11 +119,12 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
var (
|
||||
adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string
|
||||
emailHTTPPath, emailHTTPLoginPath, emailHTTPAuthMode, emailHTTPCredentialRef, emailHTTPHeaders string
|
||||
emailSMTPHost, emailSMTPUsername, emailSMTPPassword, emailSMTPMode string
|
||||
emailEventMode, emailSenderName, emailSenderEmail, emailRetryIntervals string
|
||||
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
|
||||
webHostname, webPublicIP, httpsMode string
|
||||
serverPort, emailTimeoutSecs, emailRetryCount int
|
||||
emailHTTPEnabled, emailIncludeDeploymentDetails bool
|
||||
serverPort, emailTimeoutSecs, emailRetryCount, emailSMTPPort int
|
||||
emailHTTPEnabled, emailSMTPEnabled, emailSMTPAllowPlaintextAuth, emailIncludeDeploymentDetails bool
|
||||
emailIncludeCertificateSerial, emailIncludeManagementURL bool
|
||||
dnsVerified, webEnabled bool
|
||||
)
|
||||
@@ -143,8 +146,11 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
}
|
||||
input := setup.Input{
|
||||
AdminUsername: adminUsername, AdminEmail: adminEmail, AdminPassword: adminPassword, ServerPort: serverPort,
|
||||
EmailHTTPEnabled: emailHTTPEnabled,
|
||||
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
|
||||
EmailHTTPEnabled: emailHTTPEnabled, EmailSMTPEnabled: emailSMTPEnabled,
|
||||
EmailSMTPHost: emailSMTPHost, EmailSMTPPort: emailSMTPPort, EmailSMTPUsername: emailSMTPUsername,
|
||||
EmailSMTPPassword: emailSMTPPassword,
|
||||
EmailSMTPMode: emailSMTPMode, EmailSMTPAllowPlaintextAuth: emailSMTPAllowPlaintextAuth,
|
||||
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
|
||||
EmailHTTPPath: emailHTTPPath, EmailHTTPLoginPath: emailHTTPLoginPath, EmailHTTPAuthMode: emailHTTPAuthMode,
|
||||
EmailHTTPCredentialRef: emailHTTPCredentialRef, EmailHTTPHeaders: emailHeaders,
|
||||
EmailEventMode: emailEventMode, EmailIncludeDeploymentDetails: emailIncludeDeploymentDetails,
|
||||
@@ -161,10 +167,19 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
return err
|
||||
}
|
||||
}
|
||||
cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
|
||||
cleanupDNS, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cleanupSMTP, err := prepareSMTPCredentials(cmd.Context(), cfg, &input)
|
||||
if err != nil {
|
||||
cleanupDNS()
|
||||
return err
|
||||
}
|
||||
cleanupSecret := func() {
|
||||
cleanupSMTP()
|
||||
cleanupDNS()
|
||||
}
|
||||
if err := setup.Apply(&cfg, input); err != nil {
|
||||
cleanupSecret()
|
||||
return err
|
||||
@@ -185,6 +200,13 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
|
||||
command.Flags().StringVar(&adminPassword, "admin-password", "", "超级管理员密码(仅建议临时使用参数,优先交互输入)")
|
||||
command.Flags().IntVar(&serverPort, "server-port", 8080, "Scert 主服务端口")
|
||||
command.Flags().BoolVar(&emailHTTPEnabled, "email-http-enabled", false, "是否启用 HTTP 邮件通知")
|
||||
command.Flags().BoolVar(&emailSMTPEnabled, "email-smtp-enabled", false, "是否启用 SMTP 邮件通知")
|
||||
command.Flags().StringVar(&emailSMTPHost, "email-smtp-host", "", "SMTP 服务器主机")
|
||||
command.Flags().IntVar(&emailSMTPPort, "email-smtp-port", 587, "SMTP 服务器端口")
|
||||
command.Flags().StringVar(&emailSMTPUsername, "email-smtp-username", "", "SMTP 用户名")
|
||||
command.Flags().StringVar(&emailSMTPPassword, "email-smtp-password", "", "SMTP 密码(仅建议临时使用参数,优先交互输入)")
|
||||
command.Flags().StringVar(&emailSMTPMode, "email-smtp-mode", "starttls", "SMTP 连接模式:plain、starttls、implicit_tls")
|
||||
command.Flags().BoolVar(&emailSMTPAllowPlaintextAuth, "email-smtp-allow-plaintext-auth", false, "是否允许 SMTP 明文连接认证")
|
||||
command.Flags().StringVar(&emailHTTPPath, "email-http-path", "/api/email/send", "HTTP 邮件通知请求路径")
|
||||
command.Flags().StringVar(&emailHTTPLoginPath, "email-http-login-path", "/api/login", "HTTP 会话认证登录请求路径")
|
||||
command.Flags().StringVar(&emailHTTPAuthMode, "email-http-auth-mode", "none", "HTTP 邮件通知认证方式:none、bearer、hmac_sha256、session")
|
||||
@@ -262,14 +284,52 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
|
||||
return err
|
||||
}
|
||||
value.ServerPort = port
|
||||
value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "")
|
||||
value.EmailHTTPEnabled, err = askYesNo(reader, output, "是否启用 HTTP 邮件通知?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailEndpoint, err = ask(reader, output, "第三方邮箱 API 地址", "")
|
||||
if value.EmailHTTPEnabled {
|
||||
value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailEndpoint, err = ask(reader, output, "第三方邮箱 API 地址", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
value.EmailSMTPEnabled, err = askYesNo(reader, output, "是否启用 SMTP 邮件通知?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value.EmailSMTPEnabled {
|
||||
value.EmailSMTPHost, err = ask(reader, output, "SMTP 服务器主机 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPPort, err = askInt(reader, output, "SMTP 服务器端口 *", 587)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPUsername, err = ask(reader, output, "SMTP 用户名 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPPassword, err = ask(reader, output, "SMTP 密码或授权码 *", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.EmailSMTPMode, err = ask(reader, output, "SMTP 连接模式(plain/starttls/implicit_tls)", "starttls")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value.EmailSMTPMode == "plain" {
|
||||
value.EmailSMTPAllowPlaintextAuth, err = askYesNo(reader, output, "是否允许 SMTP 明文认证?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
receiver, err := ask(reader, output, "通知收件人(逗号分隔)", "")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -328,6 +388,55 @@ func askDNSCredentials(reader *bufio.Reader, output io.Writer, providerID string
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func prepareSMTPCredentials(ctx context.Context, cfg config.Config, input *setup.Input) (func(), error) {
|
||||
if input == nil {
|
||||
return func() {}, errors.New("初始化输入不能为空")
|
||||
}
|
||||
if !input.EmailSMTPEnabled {
|
||||
return func() {}, nil
|
||||
}
|
||||
if strings.TrimSpace(input.EmailSMTPCredentialRef) != "" {
|
||||
return func() {}, nil
|
||||
}
|
||||
if strings.TrimSpace(input.EmailSMTPUsername) == "" {
|
||||
return func() {}, errors.New("启用 SMTP 通知后必须填写 SMTP 用户名")
|
||||
}
|
||||
if input.EmailSMTPPassword == "" {
|
||||
return func() {}, errors.New("启用 SMTP 通知后必须填写 SMTP 密码")
|
||||
}
|
||||
if cfg.Paths.Config == "" {
|
||||
return func() {}, errors.New("SMTP 敏感凭据存储目录不能为空")
|
||||
}
|
||||
store, err := secretstore.Open(cfg.Paths.Config)
|
||||
if err != nil {
|
||||
return func() {}, fmt.Errorf("初始化 SMTP 凭据存储失败:%w", err)
|
||||
}
|
||||
reference, err := newSMTPCredentialReference()
|
||||
if err != nil {
|
||||
return func() {}, err
|
||||
}
|
||||
if err := store.Put(ctx, reference, map[string]string{
|
||||
"username": strings.TrimSpace(input.EmailSMTPUsername),
|
||||
"password": input.EmailSMTPPassword,
|
||||
}); err != nil {
|
||||
return func() {}, fmt.Errorf("保存 SMTP 凭据失败:%w", err)
|
||||
}
|
||||
input.EmailSMTPCredentialRef = reference
|
||||
return func() {
|
||||
cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cleanupCancel()
|
||||
_ = store.Delete(cleanupContext, reference)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newSMTPCredentialReference() (string, error) {
|
||||
buffer := make([]byte, 18)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", fmt.Errorf("生成 SMTP 凭据引用失败:%w", err)
|
||||
}
|
||||
return "secret://notification/smtp/" + hex.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func prepareDNSCredentials(ctx context.Context, cfg config.Config, input *setup.Input, output io.Writer) (func(), error) {
|
||||
if input == nil {
|
||||
return func() {}, errors.New("初始化输入不能为空")
|
||||
|
||||
@@ -187,7 +187,7 @@ func TestAskDNSProviderUsesNumberedSelection(t *testing.T) {
|
||||
|
||||
func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("4\n1\n")), &output)
|
||||
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("9\n1\n")), &output)
|
||||
if err != nil {
|
||||
t.Fatalf("DNS 服务商选择失败:%v", err)
|
||||
}
|
||||
@@ -198,6 +198,7 @@ func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) {
|
||||
t.Fatalf("选择未开放服务商时未给出提示:%s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
blockedParent := filepath.Join(baseDir, "blocked")
|
||||
@@ -236,9 +237,9 @@ type cliFakeDNSCredentialTester struct {
|
||||
credentials map[string]string
|
||||
}
|
||||
|
||||
func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) error {
|
||||
func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) (setup.DNSVerificationReport, error) {
|
||||
f.credentials = credentials
|
||||
return nil
|
||||
return setup.DNSVerificationReport{}, nil
|
||||
}
|
||||
|
||||
func TestPrepareDNSCredentialsEncryptsAndClearsInput(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/servicehost"
|
||||
)
|
||||
|
||||
func newServiceCommand() *cobra.Command {
|
||||
var name string
|
||||
var displayName string
|
||||
var description string
|
||||
var executable string
|
||||
var serviceConfig string
|
||||
var workDir string
|
||||
|
||||
command := &cobra.Command{
|
||||
Use: "service",
|
||||
Short: "管理系统服务",
|
||||
}
|
||||
install := &cobra.Command{
|
||||
Use: "install",
|
||||
Short: "注册 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
executablePath, directory, configPath, err := servicePaths(executable, workDir, serviceConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return servicehost.Install(cmd.Context(), servicehost.Options{
|
||||
Name: name, DisplayName: displayName, Description: description,
|
||||
Executable: executablePath, ConfigPath: configPath, WorkDir: directory,
|
||||
})
|
||||
},
|
||||
}
|
||||
uninstall := &cobra.Command{
|
||||
Use: "uninstall",
|
||||
Short: "取消注册 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return servicehost.Uninstall(cmd.Context(), name)
|
||||
},
|
||||
}
|
||||
start := &cobra.Command{
|
||||
Use: "start",
|
||||
Short: "启动 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return servicehost.Start(cmd.Context(), name)
|
||||
},
|
||||
}
|
||||
stop := &cobra.Command{
|
||||
Use: "stop",
|
||||
Short: "停止 Scert 系统服务",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return servicehost.Stop(cmd.Context(), name)
|
||||
},
|
||||
}
|
||||
for _, child := range []*cobra.Command{install, uninstall, start, stop} {
|
||||
command.AddCommand(child)
|
||||
}
|
||||
command.PersistentFlags().StringVar(&name, "name", "Scert", "系统服务名称")
|
||||
install.Flags().StringVar(&displayName, "display-name", "Scert SSL 证书管理服务", "系统服务显示名称")
|
||||
install.Flags().StringVar(&description, "description", "Scert SSL 证书管理服务", "系统服务描述")
|
||||
install.Flags().StringVar(&executable, "executable", "", "服务程序路径,默认使用当前 scert 程序")
|
||||
install.Flags().StringVar(&serviceConfig, "service-config", "", "服务配置文件路径,默认使用当前配置")
|
||||
install.Flags().StringVar(&workDir, "work-dir", "", "服务工作目录,默认使用程序目录")
|
||||
return command
|
||||
}
|
||||
|
||||
func servicePaths(executable, workDir, serviceConfig string) (string, string, string, error) {
|
||||
if executable == "" {
|
||||
current, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("读取当前程序路径失败:%w", err)
|
||||
}
|
||||
executable = current
|
||||
}
|
||||
executable, err := filepath.Abs(executable)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("解析服务程序路径失败:%w", err)
|
||||
}
|
||||
if workDir == "" {
|
||||
workDir = filepath.Dir(executable)
|
||||
}
|
||||
workDir, err = filepath.Abs(workDir)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("解析服务工作目录失败:%w", err)
|
||||
}
|
||||
if serviceConfig == "" {
|
||||
serviceConfig = resolveConfigPath()
|
||||
}
|
||||
serviceConfig, err = filepath.Abs(serviceConfig)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("解析服务配置路径失败:%w", err)
|
||||
}
|
||||
return executable, workDir, serviceConfig, nil
|
||||
}
|
||||
|
||||
var _ = context.Background
|
||||
Reference in new issue
Block a user