完善初始化向导、通知配置与证书流程
This commit is contained in:
1 parent
b2833b761d
commit
f85ef10527
41 files changed
+3645
-1697
No files matched your search
@@ -27,6 +27,10 @@ import (
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/sshkey"
|
||||
)
|
||||
|
||||
type setupSecretWriter interface {
|
||||
Put(context.Context, string, map[string]string) error
|
||||
}
|
||||
|
||||
type Dependencies struct {
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
@@ -35,6 +39,7 @@ type Dependencies struct {
|
||||
Servers repository.ServerRepository
|
||||
SSHKeys *sshkey.Service
|
||||
SetupDNS setupDNSVerifier
|
||||
Secrets setupSecretWriter
|
||||
Firewall firewall.Manager
|
||||
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
IssueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
|
||||
@@ -56,6 +61,7 @@ type Server struct {
|
||||
servers repository.ServerRepository
|
||||
sshKeys *sshkey.Service
|
||||
setupDNS setupDNSVerifier
|
||||
secrets setupSecretWriter
|
||||
firewall firewall.Manager
|
||||
issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
issueSetupCertificate func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
|
||||
@@ -84,7 +90,7 @@ func New(deps Dependencies) *Server {
|
||||
router.Use(gin.Recovery())
|
||||
server := &Server{
|
||||
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger,
|
||||
repository: deps.Repository, setupDNS: deps.SetupDNS, firewall: deps.Firewall, router: router,
|
||||
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
|
||||
servers: deps.Servers,
|
||||
sshKeys: deps.SSHKeys,
|
||||
issueCertificate: deps.IssueCertificate,
|
||||
|
||||
@@ -2,6 +2,8 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@@ -27,37 +29,40 @@ type setupDNSVerifier interface {
|
||||
}
|
||||
|
||||
type setupRequest struct {
|
||||
AdminUsername string `json:"admin_username"`
|
||||
AdminEmail string `json:"admin_email"`
|
||||
AdminPassword string `json:"admin_password"`
|
||||
ServerPort int `json:"server_port"`
|
||||
EmailHTTPEnabled *bool `json:"email_http_enabled"`
|
||||
EmailProvider string `json:"email_provider"`
|
||||
EmailEndpoint string `json:"email_endpoint"`
|
||||
EmailHTTPPath string `json:"email_http_path"`
|
||||
EmailHTTPLoginPath string `json:"email_http_login_path"`
|
||||
EmailHTTPAuthMode string `json:"email_http_auth_mode"`
|
||||
EmailHTTPCredentialRef string `json:"email_http_credential_ref"`
|
||||
EmailHTTPHeaders map[string]string `json:"email_http_headers"`
|
||||
EmailEventMode string `json:"email_event_mode"`
|
||||
EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"`
|
||||
EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"`
|
||||
EmailIncludeManagementURL bool `json:"email_include_management_url"`
|
||||
EmailSenderName string `json:"email_sender_name"`
|
||||
EmailSenderEmail string `json:"email_sender_email"`
|
||||
Recipients []string `json:"recipients"`
|
||||
EmailTimeoutSecs int `json:"email_timeout_secs"`
|
||||
EmailRetryCount int `json:"email_retry_count"`
|
||||
EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"`
|
||||
DNSProvider string `json:"dns_provider"`
|
||||
DNSCredentialRef string `json:"dns_credential_ref"`
|
||||
DNSVerificationToken string `json:"dns_verification_token"`
|
||||
DNSTestDomain string `json:"dns_test_domain"`
|
||||
CertificateRoot string `json:"certificate_root"`
|
||||
WebHostname string `json:"web_hostname"`
|
||||
WebPublicIP string `json:"web_public_ip"`
|
||||
WebEnabled *bool `json:"web_enabled"`
|
||||
HTTPSMode string `json:"https_mode"`
|
||||
AdminUsername string `json:"admin_username"`
|
||||
AdminEmail string `json:"admin_email"`
|
||||
AdminPassword string `json:"admin_password"`
|
||||
ServerPort int `json:"server_port"`
|
||||
EmailHTTPEnabled *bool `json:"email_http_enabled"`
|
||||
EmailProvider string `json:"email_provider"`
|
||||
EmailEndpoint string `json:"email_endpoint"`
|
||||
EmailHTTPPath string `json:"email_http_path"`
|
||||
EmailHTTPLoginPath string `json:"email_http_login_path"`
|
||||
EmailHTTPAuthMode string `json:"email_http_auth_mode"`
|
||||
EmailHTTPCredentialRef string `json:"email_http_credential_ref"`
|
||||
EmailHTTPCredentials map[string]string `json:"email_http_credentials"`
|
||||
EmailHTTPHeaders map[string]string `json:"email_http_headers"`
|
||||
EmailEventMode string `json:"email_event_mode"`
|
||||
EmailIncludeDeploymentDetails bool `json:"email_include_deployment_details"`
|
||||
EmailIncludeCertificateSerial bool `json:"email_include_certificate_serial"`
|
||||
EmailIncludeManagementURL bool `json:"email_include_management_url"`
|
||||
EmailSenderName string `json:"email_sender_name"`
|
||||
EmailSenderEmail string `json:"email_sender_email"`
|
||||
Recipients []string `json:"recipients"`
|
||||
EmailTimeoutSecs int `json:"email_timeout_secs"`
|
||||
EmailRetryCount int `json:"email_retry_count"`
|
||||
EmailRetryIntervalsSecs []int `json:"email_retry_intervals_secs"`
|
||||
DNSProvider string `json:"dns_provider"`
|
||||
DNSCredentialRef string `json:"dns_credential_ref"`
|
||||
DNSVerificationToken string `json:"dns_verification_token"`
|
||||
DNSTestDomain string `json:"dns_test_domain"`
|
||||
PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
|
||||
PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
|
||||
CertificateRoot string `json:"certificate_root"`
|
||||
WebHostname string `json:"web_hostname"`
|
||||
WebPublicIP string `json:"web_public_ip"`
|
||||
WebEnabled *bool `json:"web_enabled"`
|
||||
HTTPSMode string `json:"https_mode"`
|
||||
}
|
||||
|
||||
type dnsTestRequest struct {
|
||||
@@ -91,19 +96,21 @@ func (s *Server) setupStatus(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"initialized": cfg.SetupReady,
|
||||
"phase": phase,
|
||||
"blockers": blockers,
|
||||
"server_port": cfg.Server.Port,
|
||||
"reset_url": cfg.ResetURL(),
|
||||
"https_mode": cfg.Server.HTTPSMode,
|
||||
"web_enabled": cfg.Web.Enabled,
|
||||
"web_hostname": cfg.Web.Hostname,
|
||||
"web_public_ip": cfg.Web.PublicIP,
|
||||
"certificate_root": cfg.Paths.Certificate,
|
||||
"dns_provider": cfg.DNS.Provider,
|
||||
"dns_verification_state": cfg.DNS.VerificationState,
|
||||
"dns_test_available": s.setupDNS != nil,
|
||||
"initialized": cfg.SetupReady,
|
||||
"phase": phase,
|
||||
"blockers": blockers,
|
||||
"server_port": cfg.Server.Port,
|
||||
"reset_url": cfg.ResetURL(),
|
||||
"https_mode": cfg.Server.HTTPSMode,
|
||||
"web_enabled": cfg.Web.Enabled,
|
||||
"web_hostname": cfg.Web.Hostname,
|
||||
"web_public_ip": cfg.Web.PublicIP,
|
||||
"certificate_root": cfg.Paths.Certificate,
|
||||
"dns_provider": cfg.DNS.Provider,
|
||||
"dns_verification_state": cfg.DNS.VerificationState,
|
||||
"dns_test_available": s.setupDNS != nil,
|
||||
"propagation_timeout_secs": cfg.ACME.PropagationTimeoutSecs,
|
||||
"propagation_polling_interval_secs": cfg.ACME.PropagationPollingIntervalSecs,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -190,38 +197,64 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
if request.EmailHTTPEnabled != nil {
|
||||
emailHTTPEnabled = *request.EmailHTTPEnabled
|
||||
}
|
||||
emailCredentialRef := strings.TrimSpace(request.EmailHTTPCredentialRef)
|
||||
var notificationCredentials map[string]string
|
||||
var credentialErr error
|
||||
if emailHTTPEnabled && strings.ToLower(strings.TrimSpace(request.EmailHTTPAuthMode)) != "none" {
|
||||
if len(request.EmailHTTPCredentials) > 0 {
|
||||
notificationCredentials, credentialErr = normalizeNotificationCredentials(request.EmailHTTPAuthMode, request.EmailHTTPCredentials)
|
||||
if credentialErr != nil {
|
||||
s.writeError(c, http.StatusBadRequest, credentialErr.Error(), nil)
|
||||
return
|
||||
}
|
||||
if s.secrets == nil {
|
||||
s.writeError(c, http.StatusServiceUnavailable, "HTTP 通知敏感凭据存储尚未初始化", nil)
|
||||
return
|
||||
}
|
||||
emailCredentialRef, credentialErr = newNotificationCredentialReference()
|
||||
if credentialErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "生成 HTTP 通知凭据引用失败", credentialErr)
|
||||
return
|
||||
}
|
||||
} else if emailCredentialRef == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用", nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
updated := s.config
|
||||
err := setup.Apply(&updated, setup.Input{
|
||||
AdminUsername: request.AdminUsername,
|
||||
AdminEmail: request.AdminEmail,
|
||||
AdminPassword: request.AdminPassword,
|
||||
ServerPort: request.ServerPort,
|
||||
EmailHTTPEnabled: emailHTTPEnabled,
|
||||
EmailProvider: request.EmailProvider,
|
||||
EmailEndpoint: request.EmailEndpoint,
|
||||
EmailHTTPPath: request.EmailHTTPPath,
|
||||
EmailHTTPLoginPath: request.EmailHTTPLoginPath,
|
||||
EmailHTTPAuthMode: request.EmailHTTPAuthMode,
|
||||
EmailHTTPCredentialRef: request.EmailHTTPCredentialRef,
|
||||
EmailHTTPHeaders: request.EmailHTTPHeaders,
|
||||
EmailEventMode: request.EmailEventMode,
|
||||
EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails,
|
||||
EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial,
|
||||
EmailIncludeManagementURL: request.EmailIncludeManagementURL,
|
||||
EmailSenderName: request.EmailSenderName,
|
||||
EmailSenderEmail: request.EmailSenderEmail,
|
||||
EmailRecipients: request.Recipients,
|
||||
EmailTimeoutSecs: request.EmailTimeoutSecs,
|
||||
EmailRetryCount: request.EmailRetryCount,
|
||||
EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs,
|
||||
DNSProvider: request.DNSProvider,
|
||||
DNSCredentialRef: request.DNSCredentialRef,
|
||||
DNSVerified: true,
|
||||
CertificateRoot: request.CertificateRoot,
|
||||
WebHostname: request.WebHostname,
|
||||
WebPublicIP: request.WebPublicIP,
|
||||
WebEnabled: webEnabled,
|
||||
HTTPSMode: request.HTTPSMode,
|
||||
AdminUsername: request.AdminUsername,
|
||||
AdminEmail: request.AdminEmail,
|
||||
AdminPassword: request.AdminPassword,
|
||||
ServerPort: request.ServerPort,
|
||||
EmailHTTPEnabled: emailHTTPEnabled,
|
||||
EmailProvider: request.EmailProvider,
|
||||
EmailEndpoint: request.EmailEndpoint,
|
||||
EmailHTTPPath: request.EmailHTTPPath,
|
||||
EmailHTTPLoginPath: request.EmailHTTPLoginPath,
|
||||
EmailHTTPAuthMode: request.EmailHTTPAuthMode,
|
||||
EmailHTTPCredentialRef: emailCredentialRef,
|
||||
EmailHTTPHeaders: request.EmailHTTPHeaders,
|
||||
EmailEventMode: request.EmailEventMode,
|
||||
EmailIncludeDeploymentDetails: request.EmailIncludeDeploymentDetails,
|
||||
EmailIncludeCertificateSerial: request.EmailIncludeCertificateSerial,
|
||||
EmailIncludeManagementURL: request.EmailIncludeManagementURL,
|
||||
EmailSenderName: request.EmailSenderName,
|
||||
EmailSenderEmail: request.EmailSenderEmail,
|
||||
EmailRecipients: request.Recipients,
|
||||
EmailTimeoutSecs: request.EmailTimeoutSecs,
|
||||
EmailRetryCount: request.EmailRetryCount,
|
||||
EmailRetryIntervalsSecs: request.EmailRetryIntervalsSecs,
|
||||
DNSProvider: request.DNSProvider,
|
||||
DNSCredentialRef: request.DNSCredentialRef,
|
||||
DNSVerified: true,
|
||||
PropagationTimeoutSecs: request.PropagationTimeoutSecs,
|
||||
PropagationPollingIntervalSecs: request.PropagationPollingIntervalSecs,
|
||||
CertificateRoot: request.CertificateRoot,
|
||||
WebHostname: request.WebHostname,
|
||||
WebPublicIP: request.WebPublicIP,
|
||||
WebEnabled: webEnabled,
|
||||
HTTPSMode: request.HTTPSMode,
|
||||
})
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||
@@ -265,6 +298,15 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
}
|
||||
updated.Server.TLSCert = savedCertificate.FullChainPath
|
||||
updated.Server.TLSKey = savedCertificate.PrivateKeyPath
|
||||
if len(notificationCredentials) > 0 {
|
||||
if err := s.secrets.Put(c.Request.Context(), emailCredentialRef, notificationCredentials); err != nil {
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存 HTTP 通知凭据失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "保存 HTTP 通知凭据失败,初始化尚未完成", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
updated.SetupReady = true
|
||||
if err := updated.Validate(); err != nil {
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
@@ -387,3 +429,49 @@ func isLoopbackRequest(request *http.Request) bool {
|
||||
ip := net.ParseIP(strings.TrimSpace(host))
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
func newNotificationCredentialReference() (string, error) {
|
||||
buffer := make([]byte, 18)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "secret://notification/" + base64.RawURLEncoding.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func normalizeNotificationCredentials(authMode string, values map[string]string) (map[string]string, error) {
|
||||
result := make(map[string]string, len(values))
|
||||
for key, value := range values {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil, fmt.Errorf("HTTP 通知凭据不能为空")
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(authMode)) {
|
||||
case "bearer":
|
||||
if strings.TrimSpace(result["token"]) == "" && strings.TrimSpace(result["access_token"]) == "" {
|
||||
return nil, fmt.Errorf("Bearer Token 凭据必须包含 token 或 access_token")
|
||||
}
|
||||
case "hmac_sha256":
|
||||
if strings.TrimSpace(result["secret"]) == "" && strings.TrimSpace(result["hmac_secret"]) == "" && strings.TrimSpace(result["key"]) == "" && strings.TrimSpace(result["token"]) == "" {
|
||||
return nil, fmt.Errorf("HMAC-SHA256 凭据必须包含签名密钥")
|
||||
}
|
||||
case "session":
|
||||
account := result["account"]
|
||||
if account == "" {
|
||||
account = result["username"]
|
||||
}
|
||||
if account == "" {
|
||||
account = result["identifier"]
|
||||
}
|
||||
if strings.TrimSpace(account) == "" || result["password"] == "" {
|
||||
return nil, fmt.Errorf("会话认证凭据必须包含账号和密码")
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("HTTP 通知认证方式无效")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -28,6 +28,22 @@ type fakeSetupDNSVerifier struct {
|
||||
consumed bool
|
||||
}
|
||||
|
||||
type fakeSetupSecretWriter struct {
|
||||
values map[string]map[string]string
|
||||
}
|
||||
|
||||
func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value map[string]string) error {
|
||||
if f.values == nil {
|
||||
f.values = make(map[string]map[string]string)
|
||||
}
|
||||
copyValue := make(map[string]string, len(value))
|
||||
for key, item := range value {
|
||||
copyValue[key] = item
|
||||
}
|
||||
f.values[reference] = copyValue
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeFirewallManager struct {
|
||||
result firewall.Result
|
||||
openErr error
|
||||
@@ -186,6 +202,8 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
"dns_credential_ref":"secret://dns/cloudflare/default",
|
||||
"dns_verification_token":"verified-token",
|
||||
"dns_test_domain":"scert.example.test",
|
||||
"propagation_timeout_secs":1200,
|
||||
"propagation_polling_interval_secs":15,
|
||||
"certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `",
|
||||
"web_hostname":"scert.example.test",
|
||||
"web_enabled":true,
|
||||
@@ -229,6 +247,9 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
if len(saved.Notification.Recipients) != 1 {
|
||||
t.Fatalf("通知收件人未去重:%v", saved.Notification.Recipients)
|
||||
}
|
||||
if saved.ACME.PropagationTimeoutSecs != 1200 || saved.ACME.PropagationPollingIntervalSecs != 15 {
|
||||
t.Fatalf("Web 初始化未保存 DNS 传播等待配置:timeout=%d interval=%d", saved.ACME.PropagationTimeoutSecs, saved.ACME.PropagationPollingIntervalSecs)
|
||||
}
|
||||
|
||||
repeat := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
|
||||
repeat.RemoteAddr = "127.0.0.1:53001"
|
||||
@@ -240,6 +261,65 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupApplyEncryptsNotificationCredentialsAndPersistsReference(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
cfg := config.Default(baseDir)
|
||||
configPath := filepath.Join(baseDir, "config", "scert.json")
|
||||
verifier := &fakeSetupDNSVerifier{}
|
||||
secrets := &fakeSetupSecretWriter{}
|
||||
server := New(Dependencies{
|
||||
Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{},
|
||||
SetupDNS: verifier, Secrets: secrets,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"server_port":8443,
|
||||
"email_http_enabled":true,
|
||||
"email_provider":"mail-api",
|
||||
"email_endpoint":"https://mail.example.test/send",
|
||||
"email_http_auth_mode":"bearer",
|
||||
"email_http_credentials":{"token":"plain-token-value"},
|
||||
"recipients":["ops@example.test"],
|
||||
"dns_provider":"cloudflare",
|
||||
"dns_credential_ref":"secret://dns/cloudflare/default",
|
||||
"dns_verification_token":"verified-token",
|
||||
"dns_test_domain":"scert.example.test",
|
||||
"certificate_root":"` + filepath.ToSlash(filepath.Join(baseDir, "ssl")) + `",
|
||||
"web_hostname":"scert.example.test",
|
||||
"web_enabled":true,
|
||||
"https_mode":"direct"
|
||||
}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("提交带 HTTP 通知凭据的初始化配置失败:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取初始化配置失败:%v", err)
|
||||
}
|
||||
if strings.Contains(string(data), "plain-token-value") || strings.Contains(string(data), "email_http_credentials") {
|
||||
t.Fatal("普通配置文件不应保存 HTTP 通知明文凭据")
|
||||
}
|
||||
var saved config.Config
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
t.Fatalf("解析初始化配置失败:%v", err)
|
||||
}
|
||||
if !strings.HasPrefix(saved.Notification.HTTPCredentialRef, "secret://notification/") {
|
||||
t.Fatalf("初始化配置应保存通知凭据引用:%q", saved.Notification.HTTPCredentialRef)
|
||||
}
|
||||
stored, ok := secrets.values[saved.Notification.HTTPCredentialRef]
|
||||
if !ok || stored["token"] != "plain-token-value" {
|
||||
t.Fatalf("通知凭据未写入敏感信息存储:%v", secrets.values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
verifier := &fakeSetupDNSVerifier{checkErr: errors.New("DNS 验证令牌无效或已经过期,请重新测试")}
|
||||
@@ -254,6 +334,63 @@ func TestSetupApplyRejectsUnverifiedDNSConfiguration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeNotificationCredentials(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mode string
|
||||
values map[string]string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "bearer", mode: "bearer", values: map[string]string{"token": "token-value"}},
|
||||
{name: "hmac", mode: "hmac_sha256", values: map[string]string{"secret": "secret-value"}},
|
||||
{name: "session", mode: "session", values: map[string]string{"account": "test", "password": "password-value"}},
|
||||
{name: "missing bearer token", mode: "bearer", values: map[string]string{"name": "test"}, wantErr: true},
|
||||
{name: "missing session password", mode: "session", values: map[string]string{"account": "test"}, wantErr: true},
|
||||
{name: "unknown mode", mode: "unknown", values: map[string]string{"token": "test"}, wantErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := normalizeNotificationCredentials(test.mode, test.values)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("凭据校验结果不正确:error=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupApplyRejectsMissingNotificationCredentials(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
verifier := &fakeSetupDNSVerifier{}
|
||||
server := New(Dependencies{
|
||||
Config: cfg, ConfigPath: filepath.Join(t.TempDir(), "scert.json"),
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
})
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"server_port":8443,
|
||||
"email_http_enabled":true,
|
||||
"email_endpoint":"https://mail.example.test",
|
||||
"email_http_auth_mode":"bearer",
|
||||
"dns_provider":"cloudflare",
|
||||
"dns_credential_ref":"secret://dns/cloudflare/test",
|
||||
"dns_verification_token":"verified-token",
|
||||
"dns_test_domain":"example.test",
|
||||
"certificate_root":"/ssl",
|
||||
"web_hostname":"scert.example.test",
|
||||
"https_mode":"direct"
|
||||
}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "明文凭据或已有凭据引用") {
|
||||
t.Fatalf("缺少 HTTP 通知凭据时应被拒绝:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupApplyRejectsOversizedRequest(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
server := New(Dependencies{
|
||||
|
||||
@@ -80,6 +80,12 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
}
|
||||
_ = s.tasks.UpdateTask(context.Background(), task.ID, status, "certificate_issue", message, &now, &finished)
|
||||
_ = s.tasks.FinishAttempt(context.Background(), attempt.ID, status, message, &finished)
|
||||
task.Status = status
|
||||
task.Stage = "certificate_issue"
|
||||
task.Message = message
|
||||
task.StartedAt = &now
|
||||
task.FinishedAt = &finished
|
||||
task.UpdatedAt = finished
|
||||
if s.audit != nil {
|
||||
auditStatus := status
|
||||
if issueErr != nil {
|
||||
@@ -105,12 +111,6 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
c.JSON(http.StatusBadGateway, response)
|
||||
return
|
||||
}
|
||||
task.Status = status
|
||||
task.Stage = "certificate_issue"
|
||||
task.Message = message
|
||||
task.StartedAt = &now
|
||||
task.FinishedAt = &finished
|
||||
task.UpdatedAt = finished
|
||||
response["task"] = task
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -110,6 +111,26 @@ func TestTaskAPIReturnsFailureAndKeepsTaskTrace(t *testing.T) {
|
||||
if response.Code != http.StatusBadGateway || !strings.Contains(response.Body.String(), "模拟证书申请失败") {
|
||||
t.Fatalf("失败任务响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Task struct {
|
||||
Status string `json:"status"`
|
||||
Stage string `json:"stage"`
|
||||
Message string `json:"message"`
|
||||
FinishedAt string `json:"finished_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
} `json:"task"`
|
||||
TaskStatus string `json:"task_status"`
|
||||
FinishedAt string `json:"finished_at"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("失败任务响应不是有效 JSON:%v;响应:%s", err, response.Body.String())
|
||||
}
|
||||
if payload.Task.Status != "failed" || payload.Task.Stage != "certificate_issue" || payload.Task.Message != "模拟证书申请失败" {
|
||||
t.Fatalf("失败任务嵌套状态不一致:%+v", payload.Task)
|
||||
}
|
||||
if payload.TaskStatus != "failed" || payload.FinishedAt == "" || payload.Task.FinishedAt == "" || payload.Task.UpdatedAt == "" {
|
||||
t.Fatalf("失败任务顶层状态或时间字段不完整:%+v", payload)
|
||||
}
|
||||
items, err := taskRepo.ListTasks(context.Background(), "", 10)
|
||||
if err != nil || len(items) != 1 || items[0].Status != "failed" {
|
||||
t.Fatalf("失败任务状态错误:%+v %v", items, err)
|
||||
|
||||
Reference in new issue
Block a user