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

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

+27 -28
View File
@@ -68,7 +68,7 @@ func newRootCommand() *cobra.Command {
root.PersistentFlags().StringVar(&baseDir, "base-dir", "", "Windows 默认安装根目录")
root.AddCommand(
&cobra.Command{Use: "version", Short: "显示版本信息", Run: func(cmd *cobra.Command, args []string) { cmd.Printf("Scert %s\n", version) }},
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(),
newInitCommand(), newStatusCommand(), newServeCommand(), newDomainCommand(), newServerCommand(), newSSHKeyCommand(),
)
localizeHelpFlags(root)
return root
@@ -111,11 +111,11 @@ func newInitCommand() *cobra.Command {
func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command {
var (
adminUsername, adminPassword, emailProvider, emailEndpoint string
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
webHostname, webPublicIP, httpsMode string
serverPort, resetServicePort int
dnsVerified, webEnabled bool
adminUsername, adminEmail, adminPassword, emailProvider, emailEndpoint string
recipients, dnsProvider, dnsCredentialRef, certificateRoot string
webHostname, webPublicIP, httpsMode string
serverPort int
dnsVerified, webEnabled bool
)
command := &cobra.Command{Use: "init", Short: "交互式初始化配置", RunE: func(cmd *cobra.Command, args []string) error {
path := resolveConfigPath()
@@ -126,8 +126,8 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
}
cfg := config.Default(baseDir)
input := setup.Input{
AdminUsername: adminUsername, AdminPassword: adminPassword, ServerPort: serverPort,
ResetServicePort: resetServicePort, EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
AdminUsername: adminUsername, AdminEmail: adminEmail, AdminPassword: adminPassword, ServerPort: serverPort,
EmailProvider: emailProvider, EmailEndpoint: emailEndpoint,
EmailRecipients: splitValues(recipients), DNSProvider: dnsProvider, DNSCredentialRef: dnsCredentialRef,
DNSVerified: dnsVerified, CertificateRoot: certificateRoot, WebHostname: webHostname,
WebPublicIP: webPublicIP, WebEnabled: webEnabled, HTTPSMode: httpsMode,
@@ -147,13 +147,13 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
fmt.Fprintf(cmd.OutOrStdout(), "初始化配置已保存:%s\n", path)
fmt.Fprintf(cmd.OutOrStdout(), "DNS API 已标记为验证通过;真实 provider 连通性测试和 Web 证书申请将在后续任务接入。\n")
fmt.Fprintf(cmd.OutOrStdout(), "本机防火墙:%s\n", firewallResult.Message)
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d;密码重置服务仅监听本机 %s:%d,不创建对外入站规则。\n", cfg.Server.Port, cfg.Admin.ResetServiceHost, cfg.Admin.ResetServicePort)
fmt.Fprintf(cmd.OutOrStdout(), "请确认云安全组已放行主服务端口 %d。Scert-admin 默认关闭;需要重置密码时启动后访问:%s\n", cfg.Server.Port, cfg.ResetURL())
return nil
}}
command.Flags().StringVar(&adminUsername, "admin-username", "", "超级管理员用户名")
command.Flags().StringVar(&adminEmail, "admin-email", "", "超级管理员绑定邮箱")
command.Flags().StringVar(&adminPassword, "admin-password", "", "超级管理员密码(仅建议临时使用参数,优先交互输入)")
command.Flags().IntVar(&serverPort, "server-port", 8080, "Scert 主服务端口")
command.Flags().IntVar(&resetServicePort, "reset-service-port", 8091, "Scert-admin 密码重置端口")
command.Flags().StringVar(&emailProvider, "email-provider", "", "第三方邮箱服务标识")
command.Flags().StringVar(&emailEndpoint, "email-endpoint", "", "第三方邮箱 API 地址")
command.Flags().StringVar(&recipients, "recipients", "", "通知收件人,多个地址用逗号分隔")
@@ -161,9 +161,9 @@ func newInitCommandWithFirewall(firewallManager firewall.Manager) *cobra.Command
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", "", "Web 管理页面域名")
command.Flags().StringVar(&webHostname, "web-hostname", "", "管理页面域名")
command.Flags().StringVar(&webPublicIP, "web-public-ip", "", "没有域名时使用的公网 IP")
command.Flags().BoolVar(&webEnabled, "web-enabled", true, "是否开启 Web 管理页面")
command.Flags().BoolVar(&webEnabled, "web-enabled", true, "是否开启管理页面")
command.Flags().StringVar(&httpsMode, "https-mode", "direct", "HTTPS 模式:direct、proxy")
return command
}
@@ -204,6 +204,10 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
if err != nil {
return err
}
value.AdminEmail, err = ask(reader, output, "超级管理员绑定邮箱 *", "")
if err != nil {
return err
}
value.AdminPassword, err = ask(reader, output, "超级管理员密码 *", "")
if err != nil {
return err
@@ -213,11 +217,6 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
return err
}
value.ServerPort = port
port, err = askInt(reader, output, "Scert-admin 密码重置端口 *", cfg.Admin.ResetServicePort)
if err != nil {
return err
}
value.ResetServicePort = port
value.EmailProvider, err = ask(reader, output, "第三方邮箱服务标识", "")
if err != nil {
return err
@@ -247,17 +246,17 @@ func readInteractiveInit(input io.Reader, output io.Writer, value *setup.Input,
if err != nil {
return err
}
value.WebHostname, err = ask(reader, output, "Web 管理页面域名(无域名可留空)", "")
value.WebHostname, err = ask(reader, output, "管理页面域名(无域名可留空)", "")
if err != nil {
return err
}
if value.WebHostname == "" {
value.WebPublicIP, err = ask(reader, output, "Web 管理页面公网 IP", "")
value.WebPublicIP, err = ask(reader, output, "管理页面公网 IP", "")
if err != nil {
return err
}
}
value.WebEnabled, err = askYesNo(reader, output, "是否开启 Web 管理页面?", true)
value.WebEnabled, err = askYesNo(reader, output, "是否开启管理页面?", true)
return err
}
@@ -327,11 +326,11 @@ func newStatusCommand() *cobra.Command {
}
func commandStatus(cfg config.Config) map[string]any {
return map[string]any{"service": "scert", "version": buildinfo.Version, "config_version": cfg.Version, "setup_ready": cfg.SetupReady, "https_mode": cfg.Server.HTTPSMode, "database_driver": cfg.Database.Driver, "server_port": cfg.Server.Port, "reset_service_port": cfg.Admin.ResetServicePort, "web_enabled": cfg.Web.Enabled, "web_hostname": cfg.Web.Hostname, "web_public_ip": cfg.Web.PublicIP, "dns_verification_state": cfg.DNS.VerificationState}
return map[string]any{"service": "scert", "version": buildinfo.Version, "config_version": cfg.Version, "setup_ready": cfg.SetupReady, "https_mode": cfg.Server.HTTPSMode, "database_driver": cfg.Database.Driver, "server_port": cfg.Server.Port, "reset_url": cfg.ResetURL(), "web_enabled": cfg.Web.Enabled, "web_hostname": cfg.Web.Hostname, "web_public_ip": cfg.Web.PublicIP, "dns_verification_state": cfg.DNS.VerificationState}
}
func newServeCommand() *cobra.Command {
return &cobra.Command{Use: "serve", Short: "启动 Web 服务", RunE: func(cmd *cobra.Command, args []string) error {
return &cobra.Command{Use: "serve", Short: "启动网站服务", RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
@@ -341,7 +340,7 @@ func newServeCommand() *cobra.Command {
fmt.Fprintln(cmd.OutOrStdout(), "系统尚未初始化,临时服务仅监听本机;请完成初始化后重启服务。")
}
if cfg.SetupReady && !cfg.Web.Enabled {
return fmt.Errorf("Web 管理页面已关闭")
return fmt.Errorf("管理页面已关闭")
}
service, err := app.NewWithConfigPath(cmd.Context(), cfg, resolveConfigPath())
if err != nil {
@@ -369,7 +368,7 @@ func newServeCommand() *cobra.Command {
func newDomainCommand() *cobra.Command {
command := &cobra.Command{Use: "domain", Short: "管理托管域名"}
command.AddCommand(newDomainListCommand(), newDomainAddCommand(), newDomainEditCommand(), newDomainDeleteCommand(), newDomainIssueCommand(), newDomainImportCommand())
command.AddCommand(newDomainListCommand(), newDomainAddCommand(), newDomainEditCommand(), newDomainDeleteCommand(), newDomainIssueCommand(), newDomainImportCommand(), newDomainServersCommand())
return command
}
@@ -385,10 +384,10 @@ func newDomainIssueCommand() *cobra.Command {
return err
}
defer service.Close()
if service.Certificates == nil {
if service.Workflow == nil {
return fmt.Errorf("证书申请服务未初始化")
}
result, err := service.Certificates.Issue(cmd.Context(), id)
result, err := service.Workflow.IssueWithReport(cmd.Context(), id)
if err != nil {
return err
}
@@ -411,10 +410,10 @@ func newDomainImportCommand() *cobra.Command {
return err
}
defer service.Close()
if service.Certificates == nil {
if service.Workflow == nil {
return fmt.Errorf("证书导入服务未初始化")
}
result, err := service.Certificates.Import(cmd.Context(), certificate.ImportRequest{
result, err := service.Workflow.Import(cmd.Context(), certificate.ImportRequest{
DomainID: id, Certificate: certificatePath, PrivateKey: privateKeyPath, IssuerBundle: issuerPath,
})
if err != nil {
+60 -1
View File
@@ -11,6 +11,7 @@ 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/firewall"
)
@@ -77,6 +78,58 @@ func TestHelpSupportsSubcommand(t *testing.T) {
}
}
func TestHelpIncludesServerManagementCommands(t *testing.T) {
root := newRootCommand()
var output bytes.Buffer
root.SetOut(&output)
root.SetErr(&output)
root.SetArgs([]string{"help", "server"})
if err := root.Execute(); err != nil {
t.Fatalf("查看服务器管理帮助失败:%v", err)
}
text := output.String()
for _, expected := range []string{"管理部署服务器", "添加部署服务器", "编辑部署服务器", "删除部署服务器"} {
if !strings.Contains(text, expected) {
t.Fatalf("服务器管理帮助缺少 %q:%s", expected, text)
}
}
}
func TestServerCommandUsesDefaultCertificatePathTemplates(t *testing.T) {
command := newServerAddCommand()
tests := map[string]string{
"certificate-path": deployment.DefaultCertificatePath,
"chain-path": deployment.DefaultCertificateChainPath,
"private-key-path": deployment.DefaultPrivateKeyPath,
}
for name, expected := range tests {
flag := command.Flag(name)
if flag == nil || flag.DefValue != expected {
t.Fatalf("服务器命令参数 %s 的默认值错误:%v", name, flag)
}
if len(flag.Annotations) != 0 {
t.Fatalf("服务器路径参数 %s 不应强制填写:%v", name, flag.Annotations)
}
}
}
func TestHelpIncludesSSHKeyManagementCommands(t *testing.T) {
root := newRootCommand()
var output bytes.Buffer
root.SetOut(&output)
root.SetErr(&output)
root.SetArgs([]string{"help", "ssh-key"})
if err := root.Execute(); err != nil {
t.Fatalf("查看 SSH 私钥管理帮助失败:%v", err)
}
text := output.String()
for _, expected := range []string{"管理 SSH 部署私钥", "安全录入 SSH 私钥", "删除未被服务器使用的 SSH 私钥"} {
if !strings.Contains(text, expected) {
t.Fatalf("SSH 私钥管理帮助缺少 %q:%s", expected, text)
}
}
}
func TestCommandStatusUsesApplicationVersion(t *testing.T) {
cfg := config.Default(t.TempDir())
status := commandStatus(cfg)
@@ -88,7 +141,6 @@ func TestCommandStatusUsesApplicationVersion(t *testing.T) {
func TestSaveSetupWithFirewallOpensOnlyMainPort(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.Server.Port = 8443
cfg.Admin.ResetServicePort = 8091
manager := &cliFakeFirewallManager{result: firewall.Result{
Backend: "windows", RuleName: "Scert Web TCP 8443", Created: true, Message: "已创建测试规则",
}}
@@ -105,6 +157,13 @@ func TestSaveSetupWithFirewallOpensOnlyMainPort(t *testing.T) {
}
}
func TestInitCommandDoesNotExposeResetServicePort(t *testing.T) {
command := newInitCommandWithFirewall(&cliFakeFirewallManager{})
if command.Flag("reset-service-port") != nil {
t.Fatal("初始化命令不应再提供独立密码重置端口")
}
}
func TestSaveSetupWithFirewallRollsBackNewRuleOnSaveFailure(t *testing.T) {
baseDir := t.TempDir()
blockedParent := filepath.Join(baseDir, "blocked")
+225
View File
@@ -0,0 +1,225 @@
package cli
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"git.pcux.cn/xuans/Scert/backend/internal/app"
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
func newServerCommand() *cobra.Command {
command := &cobra.Command{Use: "server", Short: "管理部署服务器"}
command.AddCommand(newServerListCommand(), newServerShowCommand(), newServerAddCommand(), newServerEditCommand(), newServerDeleteCommand())
return command
}
func newServerListCommand() *cobra.Command {
return &cobra.Command{Use: "list", Short: "查看部署服务器列表", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
items, err := service.Servers.ListServers(cmd.Context())
if err != nil {
return err
}
return printJSON(cmd, items)
}}
}
func newServerShowCommand() *cobra.Command {
var id string
command := &cobra.Command{Use: "show", Short: "查看部署服务器详情", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
item, err := service.Servers.GetServerByID(cmd.Context(), id)
if err != nil {
return err
}
return printJSON(cmd, item)
}}
command.Flags().StringVar(&id, "id", "", "服务器 ID")
_ = command.MarkFlagRequired("id")
return command
}
func newServerAddCommand() *cobra.Command {
var value serverFlags
command := &cobra.Command{Use: "add", Short: "添加部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
item := value.server()
item.ID = domain.NewID()
if _, err := service.SSHKeys.ValidateReference(cmd.Context(), item.PrivateKeyRef); err != nil {
return fmt.Errorf("SSH 私钥引用无效:%w", err)
}
if err := service.Servers.CreateServer(cmd.Context(), item); err != nil {
return err
}
return printJSON(cmd, item.Normalize())
}}
value.bind(command)
return command
}
func newServerEditCommand() *cobra.Command {
var id string
var value serverFlags
command := &cobra.Command{Use: "edit", Short: "编辑部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
existing, err := service.Servers.GetServerByID(cmd.Context(), id)
if err != nil {
return err
}
item := value.server()
item.ID = existing.ID
item.CreatedAt = existing.CreatedAt
if _, err := service.SSHKeys.ValidateReference(cmd.Context(), item.PrivateKeyRef); err != nil {
return fmt.Errorf("SSH 私钥引用无效:%w", err)
}
if err := service.Servers.UpdateServer(cmd.Context(), item); err != nil {
return err
}
return printJSON(cmd, item.Normalize())
}}
command.Flags().StringVar(&id, "id", "", "服务器 ID")
_ = command.MarkFlagRequired("id")
value.bind(command)
return command
}
func newServerDeleteCommand() *cobra.Command {
var id string
command := &cobra.Command{Use: "delete", Short: "删除部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
if err := service.Servers.DeleteServer(cmd.Context(), id); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "部署服务器已删除:%s\n", id)
return nil
}}
command.Flags().StringVar(&id, "id", "", "服务器 ID")
_ = command.MarkFlagRequired("id")
return command
}
func newDomainServersCommand() *cobra.Command {
command := &cobra.Command{Use: "servers", Short: "管理域名关联的部署服务器"}
command.AddCommand(newDomainServersListCommand(), newDomainServersSetCommand())
return command
}
func newDomainServersListCommand() *cobra.Command {
var domainID string
command := &cobra.Command{Use: "list", Short: "查看域名关联的部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
if _, err := service.Repository.GetByID(cmd.Context(), domainID); err != nil {
return err
}
items, err := service.Servers.ListServersByDomainID(cmd.Context(), domainID)
if err != nil {
return err
}
return printJSON(cmd, items)
}}
command.Flags().StringVar(&domainID, "domain-id", "", "域名 ID")
_ = command.MarkFlagRequired("domain-id")
return command
}
func newDomainServersSetCommand() *cobra.Command {
var domainID string
var serverIDs []string
command := &cobra.Command{Use: "set", Short: "替换域名关联的部署服务器", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
if _, err := service.Repository.GetByID(cmd.Context(), domainID); err != nil {
return err
}
if err := service.Servers.ReplaceDomainServers(cmd.Context(), domainID, serverIDs); err != nil {
return err
}
items, err := service.Servers.ListServersByDomainID(cmd.Context(), domainID)
if err != nil {
return err
}
return printJSON(cmd, items)
}}
command.Flags().StringVar(&domainID, "domain-id", "", "域名 ID")
command.Flags().StringSliceVar(&serverIDs, "server-ids", nil, "服务器 ID 列表;留空表示清除全部关联")
_ = command.MarkFlagRequired("domain-id")
return command
}
type serverFlags struct {
name, address, username, privateKeyRef, fingerprint string
certificatePath, privateKeyPath, chainPath, webServer string
reloadCommand []string
port int
}
func (f *serverFlags) bind(command *cobra.Command) {
command.Flags().StringVar(&f.name, "name", "", "服务器名称")
command.Flags().StringVar(&f.address, "address", "", "服务器地址")
command.Flags().IntVar(&f.port, "port", 22, "SSH 端口")
command.Flags().StringVar(&f.username, "username", "", "SSH 用户")
command.Flags().StringVar(&f.privateKeyRef, "private-key-ref", "", "SSH 私钥的敏感信息引用")
command.Flags().StringVar(&f.fingerprint, "host-key-fingerprint", "", "SSH 主机 SHA256 指纹")
command.Flags().StringVar(&f.certificatePath, "certificate-path", deployment.DefaultCertificatePath, "远程证书文件路径模板")
command.Flags().StringVar(&f.privateKeyPath, "private-key-path", deployment.DefaultPrivateKeyPath, "远程私钥文件路径模板")
command.Flags().StringVar(&f.chainPath, "chain-path", deployment.DefaultCertificateChainPath, "远程完整证书链路径模板")
command.Flags().StringVar(&f.webServer, "web-server", string(deployment.WebServerNginx), "Web 服务类型:nginx、caddy、apache、custom")
command.Flags().StringSliceVar(&f.reloadCommand, "reload-command", nil, "自定义 reload 命令及参数")
for _, name := range []string{"name", "address", "username", "private-key-ref", "host-key-fingerprint"} {
_ = command.MarkFlagRequired(name)
}
}
func (f serverFlags) server() deployment.Server {
command := make([]string, 0, len(f.reloadCommand))
for _, value := range f.reloadCommand {
if value = strings.TrimSpace(value); value != "" {
command = append(command, value)
}
}
return deployment.Server{
Name: f.name, Address: f.address, Port: f.port, Username: f.username,
PrivateKeyRef: f.privateKeyRef, HostKeyFingerprint: f.fingerprint,
CertificatePath: f.certificatePath, PrivateKeyPath: f.privateKeyPath,
CertificateChainPath: f.chainPath, WebServer: deployment.WebServer(f.webServer), ReloadCommand: command,
}
}
func openApplication(cmd *cobra.Command) (*app.App, error) {
cfg, err := loadConfig()
if err != nil {
return nil, err
}
return app.New(cmd.Context(), cfg)
}
+118
View File
@@ -0,0 +1,118 @@
package cli
import (
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/spf13/cobra"
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
)
func newSSHKeyCommand() *cobra.Command {
command := &cobra.Command{Use: "ssh-key", Short: "管理 SSH 部署私钥"}
command.AddCommand(newSSHKeyListCommand(), newSSHKeyAddCommand(), newSSHKeyDeleteCommand())
return command
}
func newSSHKeyListCommand() *cobra.Command {
return &cobra.Command{Use: "list", Short: "查看 SSH 私钥元数据", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
items, err := service.SSHKeys.List(cmd.Context())
if err != nil {
return err
}
return printJSON(cmd, items)
}}
}
func newSSHKeyAddCommand() *cobra.Command {
var name, filePath, passphraseFile string
command := &cobra.Command{Use: "add", Short: "从文件安全录入 SSH 私钥", RunE: func(cmd *cobra.Command, args []string) error {
privateKey, err := readLimitedFile(filePath, sshkey.MaxPrivateKeyBytes)
if err != nil {
return fmt.Errorf("读取 SSH 私钥文件失败:%w", err)
}
passphrase := ""
if strings.TrimSpace(passphraseFile) != "" {
content, err := readLimitedFile(passphraseFile, 4096)
if err != nil {
return fmt.Errorf("读取 SSH 私钥口令文件失败:%w", err)
}
passphrase = strings.TrimRight(content, "\r\n")
}
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
item, err := service.SSHKeys.Create(cmd.Context(), name, privateKey, passphrase)
if err != nil {
return err
}
return printJSON(cmd, item)
}}
command.Flags().StringVar(&name, "name", "", "SSH 私钥名称")
command.Flags().StringVar(&filePath, "file", "", "SSH 私钥文件路径")
command.Flags().StringVar(&passphraseFile, "passphrase-file", "", "可选的私钥口令文件路径")
_ = command.MarkFlagRequired("name")
_ = command.MarkFlagRequired("file")
return command
}
func newSSHKeyDeleteCommand() *cobra.Command {
var id string
command := &cobra.Command{Use: "delete", Short: "删除未被服务器使用的 SSH 私钥", RunE: func(cmd *cobra.Command, args []string) error {
service, err := openApplication(cmd)
if err != nil {
return err
}
defer service.Close()
reference, err := service.SSHKeys.Reference(id)
if err != nil {
return err
}
used, err := service.Servers.IsPrivateKeyRefUsed(cmd.Context(), reference)
if err != nil {
return err
}
if used {
return errors.New("SSH 私钥仍被部署服务器使用,不能删除")
}
if err := service.SSHKeys.Delete(cmd.Context(), id); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "SSH 私钥已删除:%s\n", id)
return nil
}}
command.Flags().StringVar(&id, "id", "", "SSH 私钥 ID")
_ = command.MarkFlagRequired("id")
return command
}
func readLimitedFile(path string, limit int) (string, error) {
path = strings.TrimSpace(path)
if path == "" {
return "", errors.New("文件路径不能为空")
}
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
content, err := io.ReadAll(io.LimitReader(file, int64(limit)+1))
if err != nil {
return "", err
}
if len(content) > limit {
return "", fmt.Errorf("文件不能超过 %d 字节", limit)
}
return string(content), nil
}