完善初始化向导、通知配置与证书流程

This commit is contained in:
xuans committed 2026-08-29 11:52:31 +08:00
1 parent b2833b761d
commit f85ef10527
41 files changed
+3645 -1697

No files matched your search

+341
View File
@@ -0,0 +1,341 @@
package cli
import (
"context"
"database/sql"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/database"
)
// backupMySQL 将 MySQL 的表结构和数据导出为可在 MySQL 5.7/8.0 导入的 SQL 文件。
func backupMySQL(ctx context.Context, cfg config.Config, output string) error {
db, err := database.Open(ctx, cfg.Database)
if err != nil {
return fmt.Errorf("打开 MySQL 备份连接失败:%w", err)
}
defer db.Close()
temporaryPath := output + ".tmp"
file, err := os.OpenFile(temporaryPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return fmt.Errorf("创建 MySQL 备份文件失败:%w", err)
}
removeTemporary := true
defer func() {
_ = file.Close()
if removeTemporary {
_ = os.Remove(temporaryPath)
}
}()
if _, err := fmt.Fprintf(file, "-- Scert MySQL 数据备份\n-- 生成时间:%s\n\nSET FOREIGN_KEY_CHECKS=0;\n\n", time.Now().UTC().Format(time.RFC3339)); err != nil {
return fmt.Errorf("写入 MySQL 备份头失败:%w", err)
}
rows, err := db.DB.QueryContext(ctx, "SHOW TABLES")
if err != nil {
return fmt.Errorf("读取 MySQL 表列表失败:%w", err)
}
var tableNames []string
for rows.Next() {
var tableName string
if err := rows.Scan(&tableName); err != nil {
_ = rows.Close()
return fmt.Errorf("读取 MySQL 表名失败:%w", err)
}
tableNames = append(tableNames, tableName)
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return fmt.Errorf("遍历 MySQL 表列表失败:%w", err)
}
if err := rows.Close(); err != nil {
return fmt.Errorf("关闭 MySQL 表列表失败:%w", err)
}
for _, tableName := range tableNames {
if err := dumpMySQLTable(ctx, db.DB, file, tableName); err != nil {
return err
}
}
if _, err := fmt.Fprint(file, "SET FOREIGN_KEY_CHECKS=1;\n"); err != nil {
return fmt.Errorf("写入 MySQL 备份尾失败:%w", err)
}
if err := file.Close(); err != nil {
return fmt.Errorf("关闭 MySQL 备份文件失败:%w", err)
}
if err := os.Chmod(temporaryPath, 0o600); err != nil {
return fmt.Errorf("设置 MySQL 备份文件权限失败:%w", err)
}
if err := os.Rename(temporaryPath, output); err != nil {
return fmt.Errorf("保存 MySQL 备份文件失败:%w", err)
}
removeTemporary = false
return nil
}
// createMySQLRestoreBackup 在恢复前保留目标数据库快照,供失败时回滚使用。
// 快照目录不会在恢复成功后自动删除,便于管理员在需要时继续排查或手动恢复。
func createMySQLRestoreBackup(ctx context.Context, cfg config.Config) (string, error) {
backupRoot := filepath.Clean(strings.TrimSpace(cfg.Paths.Backup))
if backupRoot == "." || backupRoot == "" {
return "", fmt.Errorf("MySQL 恢复前备份目录不能为空")
}
if err := os.MkdirAll(backupRoot, 0o700); err != nil {
return "", fmt.Errorf("创建 MySQL 恢复前备份目录失败:%w", err)
}
info, err := os.Lstat(backupRoot)
if err != nil {
return "", fmt.Errorf("检查 MySQL 恢复前备份目录失败:%w", err)
}
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return "", fmt.Errorf("MySQL 恢复前备份目录必须是普通目录")
}
if err := os.Chmod(backupRoot, 0o700); err != nil {
return "", fmt.Errorf("设置 MySQL 恢复前备份目录权限失败:%w", err)
}
rollbackDirectory, err := os.MkdirTemp(backupRoot, "scert-before-restore-")
if err != nil {
return "", fmt.Errorf("创建 MySQL 恢复快照目录失败:%w", err)
}
rollbackPath := filepath.Join(rollbackDirectory, "scert.sql")
if err := backupMySQL(ctx, cfg, rollbackPath); err != nil {
return "", fmt.Errorf("创建 MySQL 恢复前快照失败:%w", err)
}
return rollbackPath, nil
}
func dumpMySQLTable(ctx context.Context, db *sql.DB, output *os.File, tableName string) error {
quotedTable := quoteMySQLIdentifier(tableName)
var name, createSQL string
if err := db.QueryRowContext(ctx, "SHOW CREATE TABLE "+quotedTable).Scan(&name, &createSQL); err != nil {
return fmt.Errorf("读取 MySQL 表结构失败(%s):%w", tableName, err)
}
if _, err := fmt.Fprintf(output, "DROP TABLE IF EXISTS %s;\n%s;\n\n", quotedTable, createSQL); err != nil {
return fmt.Errorf("写入 MySQL 表结构失败(%s):%w", tableName, err)
}
rows, err := db.QueryContext(ctx, "SELECT * FROM "+quotedTable)
if err != nil {
return fmt.Errorf("读取 MySQL 表数据失败(%s):%w", tableName, err)
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return fmt.Errorf("读取 MySQL 表字段失败(%s):%w", tableName, err)
}
for rows.Next() {
values := make([]any, len(columns))
pointers := make([]any, len(columns))
for index := range values {
pointers[index] = &values[index]
}
if err := rows.Scan(pointers...); err != nil {
return fmt.Errorf("读取 MySQL 表行失败(%s):%w", tableName, err)
}
literals := make([]string, len(values))
for index, value := range values {
literals[index] = mysqlSQLLiteral(value)
}
if _, err := fmt.Fprintf(output, "INSERT INTO %s (%s) VALUES (%s);\n", quotedTable, quoteMySQLColumns(columns), strings.Join(literals, ", ")); err != nil {
return fmt.Errorf("写入 MySQL 表数据失败(%s):%w", tableName, err)
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("遍历 MySQL 表数据失败(%s):%w", tableName, err)
}
_, err = fmt.Fprintln(output)
return err
}
func quoteMySQLIdentifier(value string) string {
return "`" + strings.ReplaceAll(value, "`", "``") + "`"
}
func quoteMySQLColumns(columns []string) string {
quoted := make([]string, len(columns))
for index, column := range columns {
quoted[index] = quoteMySQLIdentifier(column)
}
return strings.Join(quoted, ", ")
}
func mysqlSQLLiteral(value any) string {
switch typed := value.(type) {
case nil:
return "NULL"
case sql.RawBytes:
return "X'" + hex.EncodeToString(typed) + "'"
case []byte:
return "X'" + hex.EncodeToString(typed) + "'"
case string:
return mysqlStringLiteral(typed)
case time.Time:
return "'" + typed.UTC().Format("2006-01-02 15:04:05.999999") + "'"
case bool:
if typed {
return "1"
}
return "0"
case int64:
return strconv.FormatInt(typed, 10)
case uint64:
return strconv.FormatUint(typed, 10)
case float64:
return strconv.FormatFloat(typed, 'g', -1, 64)
case float32:
return strconv.FormatFloat(float64(typed), 'g', -1, 32)
default:
return mysqlStringLiteral(fmt.Sprint(typed))
}
}
func mysqlStringLiteral(value string) string {
var builder strings.Builder
builder.Grow(len(value) + 2)
builder.WriteByte('\'')
for index := 0; index < len(value); index++ {
switch value[index] {
case '\\':
builder.WriteString(`\\`)
case '\x00':
builder.WriteString(`\0`)
case '\n':
builder.WriteString(`\n`)
case '\r':
builder.WriteString(`\r`)
case '\x1a':
builder.WriteString(`\Z`)
case '\'':
builder.WriteString(`''`)
default:
builder.WriteByte(value[index])
}
}
builder.WriteByte('\'')
return builder.String()
}
// restoreMySQL 执行 Scert 生成的 MySQL SQL 备份。
func restoreMySQL(ctx context.Context, cfg config.Config, input string) error {
script, err := os.ReadFile(input)
if err != nil {
return fmt.Errorf("读取 MySQL 备份文件失败:%w", err)
}
db, err := database.Open(ctx, cfg.Database)
if err != nil {
return fmt.Errorf("打开 MySQL 恢复连接失败:%w", err)
}
defer db.Close()
for _, statement := range splitMySQLStatements(string(script)) {
if _, err := db.DB.ExecContext(ctx, statement); err != nil {
return fmt.Errorf("执行 MySQL 恢复语句失败:%w", err)
}
}
return nil
}
func splitMySQLStatements(script string) []string {
var statements []string
var statement strings.Builder
var quote byte
lineComment := false
blockComment := false
executableComment := false
escaped := false
flush := func() {
value := strings.TrimSpace(statement.String())
if value != "" {
statements = append(statements, value)
}
statement.Reset()
}
for index := 0; index < len(script); index++ {
current := script[index]
if lineComment {
if current == '\n' {
lineComment = false
statement.WriteByte('\n')
}
continue
}
if blockComment {
if current == '*' && index+1 < len(script) && script[index+1] == '/' {
blockComment = false
index++
statement.WriteByte(' ')
}
continue
}
if executableComment {
statement.WriteByte(current)
if current == '*' && index+1 < len(script) && script[index+1] == '/' {
statement.WriteByte(script[index+1])
index++
executableComment = false
}
continue
}
if quote != 0 {
statement.WriteByte(current)
if escaped {
escaped = false
continue
}
if current == '\\' {
escaped = true
continue
}
if current == quote {
if index+1 < len(script) && script[index+1] == quote {
statement.WriteByte(script[index+1])
index++
continue
}
quote = 0
}
continue
}
if current == '\'' || current == '"' || current == '`' {
quote = current
statement.WriteByte(current)
continue
}
if current == '#' {
lineComment = true
continue
}
if current == '-' && index+2 < len(script) && script[index+1] == '-' && (script[index+2] == ' ' || script[index+2] == '\t' || script[index+2] == '\n') {
lineComment = true
index++
continue
}
if current == '/' && index+1 < len(script) && script[index+1] == '*' {
if index+2 < len(script) && (script[index+2] == '!' || script[index+2] == '+') {
statement.WriteByte(current)
statement.WriteByte(script[index+1])
index++
executableComment = true
continue
}
blockComment = true
index++
continue
}
if current == ';' {
flush()
continue
}
statement.WriteByte(current)
}
flush()
return statements
}
+63
View File
@@ -0,0 +1,63 @@
package cli
import (
"database/sql"
"strings"
"testing"
)
func TestQuoteMySQLIdentifierEscapesBackticks(t *testing.T) {
if value := quoteMySQLIdentifier("a`b"); value != "`a``b`" {
t.Fatalf("MySQL 标识符转义不正确:%s", value)
}
}
func TestMySQLSQLLiteral(t *testing.T) {
cases := []struct {
name string
value any
want string
}{
{name: "null", value: nil, want: "NULL"},
{name: "string", value: "a'b\\c\n\x00\x1a", want: "'a''b\\\\c\\n\\0\\Z'"},
{name: "binary", value: []byte{0x01, 0xaf}, want: "X'01af'"},
{name: "raw bytes", value: sql.RawBytes{0x00, 0xff}, want: "X'00ff'"},
{name: "integer", value: int64(42), want: "42"},
{name: "boolean", value: true, want: "1"},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
if value := mysqlSQLLiteral(item.value); value != item.want {
t.Fatalf("SQL 字面量不正确:%s", value)
}
})
}
}
func TestQuoteMySQLColumns(t *testing.T) {
value := quoteMySQLColumns([]string{"id", "display_name"})
if value != "`id`, `display_name`" || strings.Contains(value, "'") {
t.Fatalf("MySQL 字段列表不正确:%s", value)
}
}
func TestSplitMySQLStatementsKeepsQuotedSemicolons(t *testing.T) {
script := "-- 注释\nSET FOREIGN_KEY_CHECKS=0;\nINSERT INTO `items` (`value`) VALUES ('a; b'), ('it''s');\n"
statements := splitMySQLStatements(script)
if len(statements) != 2 {
t.Fatalf("SQL 语句拆分数量不正确:%d %#v", len(statements), statements)
}
if strings.Contains(statements[0], "注释") || !strings.Contains(statements[1], "'a; b'") || !strings.Contains(statements[1], "'it''s'") {
t.Fatalf("SQL 语句拆分内容不正确:%#v", statements)
}
}
func TestSplitMySQLStatementsKeepsExecutableComments(t *testing.T) {
script := "CREATE TABLE `items` (`id` bigint) /*!50100 SET @value = 'a;b' */;\n"
statements := splitMySQLStatements(script)
if len(statements) != 1 {
t.Fatalf("带可执行注释的 SQL 语句拆分数量不正确:%d %#v", len(statements), statements)
}
if !strings.Contains(statements[0], "/*!50100 SET @value = 'a;b' */") {
t.Fatalf("MySQL 可执行注释不应被删除:%s", statements[0])
}
}
+53 -3
View File
@@ -270,7 +270,7 @@ func newBackupCommand() *cobra.Command {
var output string
command := &cobra.Command{
Use: "backup",
Short: "备份配置和 SQLite 数据库",
Short: "备份配置和数据库",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
@@ -294,6 +294,11 @@ func newBackupCommand() *cobra.Command {
return err
}
}
if cfg.Database.Driver == "mysql" {
if err := backupMySQL(cmd.Context(), cfg, filepath.Join(output, "scert.sql")); err != nil {
return err
}
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "备份已创建:%s\n", output)
return err
},
@@ -306,7 +311,7 @@ func newRestoreCommand() *cobra.Command {
var input string
command := &cobra.Command{
Use: "restore",
Short: "恢复 SQLite 数据库备份",
Short: "恢复配置和数据库备份",
RunE: func(cmd *cobra.Command, args []string) error {
input, err := validateRestoreInput(input)
if err != nil {
@@ -319,16 +324,24 @@ func newRestoreCommand() *cobra.Command {
}
currentPath := filepath.Clean(resolveConfigPath())
_, currentConfigErr := config.Load(currentPath)
currentConfig, currentConfigErr := config.Load(currentPath)
if currentConfigErr != nil && !errors.Is(currentConfigErr, os.ErrNotExist) {
return fmt.Errorf("读取当前配置失败:%w", currentConfigErr)
}
if currentConfigErr == nil && currentConfig.Database.Driver != cfg.Database.Driver {
return fmt.Errorf("备份数据库类型(%s)与当前配置数据库类型(%s)不一致,拒绝恢复", cfg.Database.Driver, currentConfig.Database.Driver)
}
if info, statErr := os.Stat(currentPath); statErr == nil && !info.Mode().IsRegular() {
return errors.New("当前配置路径不是普通文件")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return fmt.Errorf("检查当前配置失败:%w", statErr)
}
mysqlSource := filepath.Join(input, "scert.sql")
if cfg.Database.Driver == "mysql" && !isRegularFile(mysqlSource) {
return errors.New("MySQL 备份目录缺少有效的 scert.sql 文件")
}
databaseSource := filepath.Join(input, "scert.db")
databaseSourceInfo, databaseSourceErr := os.Stat(databaseSource)
databaseSourceExists := databaseSourceErr == nil
@@ -338,6 +351,9 @@ func newRestoreCommand() *cobra.Command {
if databaseSourceExists && !databaseSourceInfo.Mode().IsRegular() {
return errors.New("备份数据库不是普通文件")
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && !databaseSourceExists {
return errors.New("SQLite 备份目录缺少有效的 scert.db 文件")
}
if cfg.Database.Driver == "sqlite" && cfg.Database.DSN != ":memory:" && databaseSourceExists {
if samePath(databaseSource, cfg.Database.DSN) {
return errors.New("备份数据库与当前数据库路径相同")
@@ -368,6 +384,14 @@ func newRestoreCommand() *cobra.Command {
}
}
mysqlBackupPath := ""
if cfg.Database.Driver == "mysql" {
mysqlBackupPath, err = createMySQLRestoreBackup(cmd.Context(), cfg)
if err != nil {
return err
}
}
if err := cfg.Save(currentPath); err != nil {
return err
}
@@ -382,6 +406,20 @@ func newRestoreCommand() *cobra.Command {
return fmt.Errorf("恢复 SQLite 数据库失败:%w", err)
}
}
if cfg.Database.Driver == "mysql" {
if err := restoreMySQL(cmd.Context(), cfg, mysqlSource); err != nil {
restoreFailure := fmt.Errorf("恢复 MySQL 数据库失败:%w", err)
if mysqlBackupPath != "" {
if rollbackErr := restoreMySQL(cmd.Context(), cfg, mysqlBackupPath); rollbackErr != nil {
restoreFailure = fmt.Errorf("%w;MySQL 数据库回滚失败:%v", restoreFailure, rollbackErr)
}
}
if configBackupPath != "" {
_ = copyFile(configBackupPath, currentPath, 0o600)
}
return restoreFailure
}
}
_, err = fmt.Fprintf(cmd.OutOrStdout(), "恢复已完成:%s\n", input)
return err
},
@@ -483,6 +521,18 @@ func setConfigValue(cfg *config.Config, key, value string) error {
return fmt.Errorf("续期阈值格式无效:%w", err)
}
cfg.ACME.RenewalThresholdDays = parsed
case "acme.propagation_timeout_secs":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("DNS 传播等待时间格式无效:%w", err)
}
cfg.ACME.PropagationTimeoutSecs = parsed
case "acme.propagation_polling_interval_secs":
parsed, err := parseInt()
if err != nil {
return fmt.Errorf("DNS 传播检测间隔格式无效:%w", err)
}
cfg.ACME.PropagationPollingIntervalSecs = parsed
case "dns.provider":
cfg.DNS.Provider = value
case "dns.credential_ref":
+9
View File
@@ -50,6 +50,15 @@ func TestSetConfigValueUpdatesAndValidatesAllowedFields(t *testing.T) {
if cfg.Notification.HTTPLoginPath != "/api/login" {
t.Fatalf("HTTP 登录路径未更新:%s", cfg.Notification.HTTPLoginPath)
}
if err := setConfigValue(&cfg, "acme.propagation_timeout_secs", "1200"); err != nil {
t.Fatal(err)
}
if err := setConfigValue(&cfg, "acme.propagation_polling_interval_secs", "15"); err != nil {
t.Fatal(err)
}
if cfg.ACME.PropagationTimeoutSecs != 1200 || cfg.ACME.PropagationPollingIntervalSecs != 15 {
t.Fatalf("DNS 传播参数未更新:%+v", cfg.ACME)
}
if err := setConfigValue(&cfg, "admin.password_hash", "plain"); err == nil {
t.Fatal("不应允许直接修改密码摘要")
}
+128 -6
View File
@@ -22,8 +22,10 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/buildinfo"
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup"
)
@@ -159,15 +161,21 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
return err
}
}
cleanupSecret, err := prepareDNSCredentials(cmd.Context(), cfg, &input, cmd.OutOrStdout())
if err != nil {
return err
}
if err := setup.Apply(&cfg, input); err != nil {
cleanupSecret()
return err
}
firewallResult, err := saveSetupWithFirewall(cmd.Context(), cfg, path, firewallManager)
if err != nil {
cleanupSecret()
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "初始化配置已保存:%s\n", path)
fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已标记为验证通过;真实 provider 连通性测试和 Web 证书申请将在后续任务接入。\n")
fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已完成在线验证,凭据已加密保存;真实 Web 证书申请将在后续任务接入。\n")
fmt.Fprintf(cmd.OutOrStdout(), "本机防火墙:%s\n", firewallResult.Message)
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL())
return nil
@@ -195,8 +203,8 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
command.Flags().IntVar(&emailRetryCount, "email-retry-count", 3, "通知失败重试次数")
command.Flags().StringVar(&emailRetryIntervals, "email-retry-intervals", "30,120,600", "通知重试间隔(秒,逗号分隔)")
command.Flags().StringVar(&dnsProvider, "dns-provider", "", "DNS API 服务商标识")
command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用,不保存明文密钥")
command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过外部验证测试")
command.Flags().StringVar(&dnsCredentialRef, "dns-credential-ref", "", "DNS 凭据引用")
command.Flags().BoolVar(&dnsVerified, "dns-verified", false, "DNS API 是否已通过验证测试")
command.Flags().StringVar(&certificateRoot, "certificate-root", "", "证书部署根目录,默认使用系统目录")
command.Flags().StringVar(&webHostname, "web-hostname", "", "管理页面域名")
command.Flags().StringVar(&webPublicIP, "web-public-ip", "", "没有域名时使用的公网 IP")
@@ -267,15 +275,15 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
return err
}
value.EmailRecipients = splitValues(receiver)
value.DNSProvider, err = ask(reader, output, "DNS API 服务商 *", "")
value.DNSProvider, err = askDNSProvider(reader, output)
if err != nil {
return err
}
value.DNSCredentialRef, err = ask(reader, output, "DNS 凭据引用 *(不要输入明文密钥)", "")
value.DNSCredentials, err = askDNSCredentials(reader, output, value.DNSProvider)
if err != nil {
return err
}
value.DNSVerified, err = askYesNo(reader, output, "DNS API 是否已经完成验证测试?", false)
value.DNSTestDomain, err = ask(reader, output, "DNS 权限测试域名 *", "")
if err != nil {
return err
}
@@ -297,6 +305,120 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
return err
}
func askDNSCredentials(reader *bufio.Reader, output io.Writer, providerID string) (map[string]string, error) {
descriptor, err := dnsprovider.GetDescriptor(providerID)
if err != nil {
return nil, err
}
credentials := make(map[string]string, len(descriptor.CredentialFields))
fmt.Fprintln(output, "请输入 DNS API 凭据。输入内容会在当前配置过程中明文显示,提交后只保存加密内容。")
for _, field := range descriptor.CredentialFields {
label := field.Label
if field.Required {
label += " *"
}
value, err := ask(reader, output, label, "")
if err != nil {
return nil, err
}
if strings.TrimSpace(value) != "" {
credentials[field.Name] = value
}
}
return credentials, nil
}
func prepareDNSCredentials(ctx context.Context, cfg config.Config, input *setup.Input, output io.Writer) (func(), error) {
if input == nil {
return func() {}, errors.New("初始化输入不能为空")
}
if strings.TrimSpace(input.DNSCredentialRef) != "" {
return func() {}, nil
}
if len(input.DNSCredentials) == 0 {
return func() {}, errors.New("DNS 凭据不能为空")
}
if strings.TrimSpace(input.DNSTestDomain) == "" {
return func() {}, errors.New("DNS 权限测试域名不能为空")
}
store, err := secretstore.Open(cfg.Paths.Config)
if err != nil {
return func() {}, fmt.Errorf("初始化 DNS 凭据存储失败:%w", err)
}
manager := setup.NewDNSVerificationManager(
dnsprovider.NewTester(dnsprovider.NewLegoFactory()),
store,
)
return prepareDNSCredentialsWithManager(ctx, input, output, manager, store)
}
func prepareDNSCredentialsWithManager(ctx context.Context, input *setup.Input, output io.Writer, manager *setup.DNSVerificationManager, store *secretstore.Store) (func(), error) {
if input == nil {
return func() {}, errors.New("初始化输入不能为空")
}
if manager == nil || store == nil {
return func() {}, errors.New("DNS 凭据验证服务未初始化")
}
if strings.TrimSpace(input.DNSCredentialRef) != "" {
return func() {}, nil
}
if len(input.DNSCredentials) == 0 {
return func() {}, errors.New("DNS 凭据不能为空")
}
if strings.TrimSpace(input.DNSTestDomain) == "" {
return func() {}, errors.New("DNS 权限测试域名不能为空")
}
testContext, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
result, err := manager.Verify(testContext, setup.DNSVerificationInput{
ProviderID: input.DNSProvider,
TestDomain: input.DNSTestDomain,
Credentials: input.DNSCredentials,
})
if err != nil {
return func() {}, fmt.Errorf("DNS API 在线验证失败:%w", err)
}
input.DNSCredentialRef = result.CredentialRef
input.DNSVerified = true
input.DNSCredentials = nil
fmt.Fprintf(output, "DNS API 在线验证通过,凭据已加密保存,有效期至 %s。\n", result.ExpiresAt.Local().Format("2006-01-02 15:04:05"))
return func() {
cleanupContext, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cleanupCancel()
_ = store.Delete(cleanupContext, result.CredentialRef)
}, nil
}
func askDNSProvider(reader *bufio.Reader, output io.Writer) (string, error) {
providers := dnsprovider.Descriptors()
fmt.Fprintln(output, "请选择 DNS API 服务商:")
for index, provider := range providers {
status := ""
if !provider.Available {
status = "(暂未开放)"
}
fmt.Fprintf(output, "%d. %s%s\n", index+1, provider.Name, status)
}
for {
value, err := ask(reader, output, "请输入编号", "")
if err != nil {
return "", err
}
index, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || index < 1 || index > len(providers) {
fmt.Fprintln(output, "编号无效,请重新输入。")
continue
}
provider := providers[index-1]
if !provider.Available {
fmt.Fprintf(output, "%s 当前暂未开放,请选择其他服务商。\n", provider.Name)
continue
}
return provider.ID, nil
}
}
func ask(reader *bufio.Reader, output io.Writer, label, defaultValue string) (string, error) {
if defaultValue != "" {
fmt.Fprintf(output, "%s [%s]:", label, defaultValue)
+85
View File
@@ -1,6 +1,7 @@
package cli
import (
"bufio"
"bytes"
"context"
"errors"
@@ -12,7 +13,10 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/buildinfo"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"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/secretstore"
"git.pcux.cn/xuans/Scert/backend/internal/setup"
)
type cliFakeFirewallManager struct {
@@ -164,6 +168,36 @@ func TestInitCommandDoesNotExposeResetServicePort(t *testing.T) {
}
}
func TestAskDNSProviderUsesNumberedSelection(t *testing.T) {
var output bytes.Buffer
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("99\n2\n")), &output)
if err != nil {
t.Fatalf("DNS 服务商选择失败:%v", err)
}
if provider != "aliyun" {
t.Fatalf("编号 2 应选择阿里云 DNS,实际为:%s", provider)
}
if !strings.Contains(output.String(), "1. Cloudflare") || !strings.Contains(output.String(), "2. 阿里云 DNS") {
t.Fatalf("DNS 服务商列表未按编号显示:%s", output.String())
}
if !strings.Contains(output.String(), "编号无效,请重新输入。") {
t.Fatalf("无效编号未提示重新输入:%s", output.String())
}
}
func TestAskDNSProviderRejectsUnavailableSelection(t *testing.T) {
var output bytes.Buffer
provider, err := askDNSProvider(bufio.NewReader(strings.NewReader("4\n1\n")), &output)
if err != nil {
t.Fatalf("DNS 服务商选择失败:%v", err)
}
if provider != "cloudflare" {
t.Fatalf("重新选择后应返回 Cloudflare,实际为:%s", provider)
}
if !strings.Contains(output.String(), "当前暂未开放") {
t.Fatalf("选择未开放服务商时未给出提示:%s", output.String())
}
}
func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
baseDir := t.TempDir()
blockedParent := filepath.Join(baseDir, "blocked")
@@ -197,3 +231,54 @@ func TestSaveSetupWithFirewallReportsRollbackFailure(t *testing.T) {
t.Fatalf("防火墙回滚失败应返回明确错误:%v", err)
}
}
type cliFakeDNSCredentialTester struct {
credentials map[string]string
}
func (f *cliFakeDNSCredentialTester) Verify(_ context.Context, _ string, _ string, credentials map[string]string) error {
f.credentials = credentials
return nil
}
func TestPrepareDNSCredentialsEncryptsAndClearsInput(t *testing.T) {
configDir := t.TempDir()
store, err := secretstore.Open(configDir)
if err != nil {
t.Fatalf("打开敏感信息存储失败:%v", err)
}
tester := &cliFakeDNSCredentialTester{}
manager := setup.NewDNSVerificationManager(tester, store)
input := &setup.Input{
DNSProvider: dnsprovider.Cloudflare,
DNSCredentials: map[string]string{"api_token": "test-dns-token"},
DNSTestDomain: "example.com",
}
var output bytes.Buffer
cleanup, err := prepareDNSCredentialsWithManager(context.Background(), input, &output, manager, store)
if err != nil {
t.Fatalf("准备 DNS 凭据失败:%v", err)
}
if input.DNSCredentialRef == "" || !input.DNSVerified || input.DNSCredentials != nil {
t.Fatalf("DNS 凭据输入状态不正确:%+v", input)
}
if tester.credentials["api_token"] != "test-dns-token" {
t.Fatalf("在线验证未收到凭据:%v", tester.credentials)
}
content, err := os.ReadFile(filepath.Join(configDir, "secrets.json"))
if err != nil {
t.Fatalf("读取敏感信息文件失败:%v", err)
}
if strings.Contains(string(content), "test-dns-token") || strings.Contains(output.String(), "test-dns-token") {
t.Fatal("DNS 凭据不应以明文写入文件或输出")
}
value, err := store.Get(context.Background(), input.DNSCredentialRef)
if err != nil || value["api_token"] != "test-dns-token" {
t.Fatalf("加密凭据解密结果不正确:value=%v err=%v", value, err)
}
cleanup()
exists, err := store.Has(context.Background(), input.DNSCredentialRef)
if err != nil || exists {
t.Fatalf("保存失败清理后凭据引用仍存在:exists=%t err=%v", exists, err)
}
}