完善 Scert 前后端与部署支持
This commit is contained in:
1 parent
afdb947bea
commit
7f0af703ed
85 files changed
+7530
-800
No files matched your search
@@ -0,0 +1,37 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
func (s *Server) restoreCertificateVersion(c *gin.Context) {
|
||||
if s.restoreVersion == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书恢复接口尚未配置", errors.New("证书恢复流程未配置"))
|
||||
return
|
||||
}
|
||||
version := strings.TrimSpace(c.Param("version"))
|
||||
result, err := s.restoreVersion(c.Request.Context(), strings.TrimSpace(c.Param("id")), version)
|
||||
if err != nil {
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "failed",
|
||||
Message: "恢复证书历史版本失败:" + err.Error(),
|
||||
})
|
||||
}
|
||||
s.writeError(c, certificateErrorStatus(err), "恢复证书历史版本失败", err)
|
||||
return
|
||||
}
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "success",
|
||||
Message: "已恢复证书历史版本:" + version,
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
type restoreCertificateReader struct {
|
||||
versions []certificate.SavedResource
|
||||
}
|
||||
|
||||
func (r restoreCertificateReader) Current(context.Context, string) (certificate.IssueResult, error) {
|
||||
return certificate.IssueResult{}, nil
|
||||
}
|
||||
|
||||
func (r restoreCertificateReader) ListVersions(context.Context, string) ([]certificate.SavedResource, error) {
|
||||
return r.versions, nil
|
||||
}
|
||||
|
||||
type restoreAuditRepository struct {
|
||||
items []repository.AuditLog
|
||||
}
|
||||
|
||||
func (r *restoreAuditRepository) CreateAuditLog(_ context.Context, item repository.AuditLog) error {
|
||||
r.items = append(r.items, item)
|
||||
return nil
|
||||
}
|
||||
|
||||
func newRestoreAPITestServer(t *testing.T, restore func(context.Context, string, string) (certificate.IssueResult, error)) (*Server, *restoreAuditRepository) {
|
||||
t.Helper()
|
||||
audit := &restoreAuditRepository{}
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
Repository: &stubDomainRepository{},
|
||||
CurrentCertificate: restoreCertificateReader{},
|
||||
RestoreCertificateVersion: restore,
|
||||
Audit: audit,
|
||||
})
|
||||
server.authSessions["test-session"] = authSession{
|
||||
Username: "admin",
|
||||
Role: "super_admin",
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
}
|
||||
return server, audit
|
||||
}
|
||||
|
||||
func TestRestoreCertificateVersionAPIRecordsSuccessAudit(t *testing.T) {
|
||||
called := false
|
||||
server, audit := newRestoreAPITestServer(t, func(_ context.Context, domainID, version string) (certificate.IssueResult, error) {
|
||||
called = true
|
||||
if domainID != "domain-1" || version != "20260830-120000" {
|
||||
t.Fatalf("unexpected restore request: %s %s", domainID, version)
|
||||
}
|
||||
return certificate.IssueResult{DomainID: domainID, Saved: certificate.SavedResource{Version: version}}, nil
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/versions/20260830-120000/restore", nil)
|
||||
request.AddCookie(&http.Cookie{Name: authCookieName, Value: "test-session"})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "20260830-120000") {
|
||||
t.Fatalf("unexpected success response: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if !called {
|
||||
t.Fatal("restore callback was not called")
|
||||
}
|
||||
if len(audit.items) != 1 || audit.items[0].Status != "success" || audit.items[0].Action != "certificate_version_restore" {
|
||||
t.Fatalf("success audit was not recorded: %+v", audit.items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreCertificateVersionAPIRecordsFailureAudit(t *testing.T) {
|
||||
server, audit := newRestoreAPITestServer(t, func(context.Context, string, string) (certificate.IssueResult, error) {
|
||||
return certificate.IssueResult{}, errors.New("simulated restore failure")
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/versions/bad/restore", nil)
|
||||
request.AddCookie(&http.Cookie{Name: authCookieName, Value: "test-session"})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("unexpected failure response: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if len(audit.items) != 1 || audit.items[0].Status != "failed" || audit.items[0].Action != "certificate_version_restore" {
|
||||
t.Fatalf("failure audit was not recorded: %+v", audit.items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListCertificateVersionsAPIRequiresAuthentication(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
Repository: &stubDomainRepository{},
|
||||
CurrentCertificate: restoreCertificateReader{versions: []certificate.SavedResource{{Domain: "example.com", Version: "v1"}}},
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/domains/domain-1/certificate/versions", nil)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated version request should be rejected: %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
var _ repository.DomainRepository = (*stubDomainRepository)(nil)
|
||||
var _ = domain.Domain{}
|
||||
@@ -0,0 +1,89 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
pathpkg "path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// frontend 为浏览器提供前端静态文件,并为 Vue 的 history 路由回退到 index.html。
|
||||
func (s *Server) frontend(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
s.configMu.RLock()
|
||||
enabled := s.config.Web.Enabled
|
||||
s.configMu.RUnlock()
|
||||
if !enabled || strings.TrimSpace(s.frontendDir) == "" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
requestPath := pathpkg.Clean("/" + strings.TrimPrefix(c.Request.URL.Path, "/"))
|
||||
if requestPath == "." || requestPath == "/" {
|
||||
requestPath = "/"
|
||||
}
|
||||
if isCoreRequestPath(requestPath) {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
staticDir, err := filepath.Abs(s.frontendDir)
|
||||
if err != nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
relativePath := strings.TrimPrefix(requestPath, "/")
|
||||
candidate := filepath.Join(staticDir, filepath.FromSlash(relativePath))
|
||||
if !isWithinDirectory(staticDir, candidate) {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if info, statErr := os.Stat(candidate); statErr == nil && info.Mode().IsRegular() {
|
||||
serveFrontendFile(c, candidate)
|
||||
return
|
||||
}
|
||||
|
||||
if requestPath != "/" && filepath.Ext(requestPath) != "" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
indexPath := filepath.Join(staticDir, "index.html")
|
||||
if info, statErr := os.Stat(indexPath); statErr != nil || !info.Mode().IsRegular() {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
serveFrontendFile(c, indexPath)
|
||||
}
|
||||
|
||||
func serveFrontendFile(c *gin.Context, path string) {
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
if filepath.Base(path) != "index.html" {
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
http.ServeFile(c.Writer, c.Request, path)
|
||||
}
|
||||
|
||||
func isCoreRequestPath(path string) bool {
|
||||
return path == "/api" ||
|
||||
strings.HasPrefix(path, "/api/") ||
|
||||
path == "/healthz" ||
|
||||
path == "/reset" ||
|
||||
strings.HasPrefix(path, "/reset/")
|
||||
}
|
||||
|
||||
func isWithinDirectory(directory, candidate string) bool {
|
||||
relative, err := filepath.Rel(directory, candidate)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestFrontendServesAssetsAndHistoryRoutes(t *testing.T) {
|
||||
staticDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(staticDir, "index.html"), []byte("<html>Scert</html>"), 0o644); err != nil {
|
||||
t.Fatalf("写入前端入口失败:%v", err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(staticDir, "assets"), 0o755); err != nil {
|
||||
t.Fatalf("创建静态资源目录失败:%v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(staticDir, "assets", "app.js"), []byte("console.log('ok')"), 0o644); err != nil {
|
||||
t.Fatalf("写入静态资源失败:%v", err)
|
||||
}
|
||||
|
||||
cfg := config.Default(t.TempDir())
|
||||
server := New(Dependencies{Config: cfg, FrontendDir: staticDir})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
wantStatus int
|
||||
wantBody string
|
||||
}{
|
||||
{name: "root", method: http.MethodGet, path: "/", wantStatus: http.StatusOK, wantBody: "Scert"},
|
||||
{name: "history route", method: http.MethodGet, path: "/login", wantStatus: http.StatusOK, wantBody: "Scert"},
|
||||
{name: "asset", method: http.MethodGet, path: "/assets/app.js", wantStatus: http.StatusOK, wantBody: "console.log"},
|
||||
{name: "missing asset", method: http.MethodGet, path: "/assets/missing.js", wantStatus: http.StatusNotFound},
|
||||
{name: "unknown api", method: http.MethodGet, path: "/api/unknown", wantStatus: http.StatusNotFound},
|
||||
{name: "post fallback", method: http.MethodPost, path: "/login", wantStatus: http.StatusNotFound},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(test.method, test.path, nil)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != test.wantStatus {
|
||||
t.Fatalf("状态码 = %d,期望 %d,响应:%s", response.Code, test.wantStatus, response.Body.String())
|
||||
}
|
||||
if test.wantBody != "" && !strings.Contains(response.Body.String(), test.wantBody) {
|
||||
t.Fatalf("响应未包含 %q:%s", test.wantBody, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrontendRespectsWebEnabled(t *testing.T) {
|
||||
staticDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(staticDir, "index.html"), []byte("Scert"), 0o644); err != nil {
|
||||
t.Fatalf("写入前端入口失败:%v", err)
|
||||
}
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Web.Enabled = false
|
||||
server := New(Dependencies{Config: cfg, FrontendDir: staticDir})
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("关闭 Web 后根路径应返回 404:%d", response.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (s *Server) runRenewalNow(c *gin.Context) {
|
||||
if s.runRenewal == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "续期服务未配置", errors.New("续期工作流未配置"))
|
||||
return
|
||||
}
|
||||
report, err := s.runRenewal(c.Request.Context())
|
||||
response := gin.H{"report": report}
|
||||
if err != nil {
|
||||
response["error"] = err.Error()
|
||||
c.JSON(http.StatusConflict, response)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
@@ -246,6 +246,6 @@ func (s *Server) recordResetAudit(c *gin.Context, status, message string) {
|
||||
}
|
||||
|
||||
var resetTemplate = template.Must(template.New("reset").Parse(`<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>Scert 超级管理员密码重置</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f7fb;color:#172033;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}.card{width:min(520px,calc(100% - 40px));padding:34px;border:1px solid #dce5f1;border-radius:20px;background:#fff;box-shadow:0 18px 60px rgba(31,50,87,.12)}h1{margin:0 0 14px;font-size:26px}p{margin:8px 0;color:#52637b;line-height:1.7}label{display:block;margin-top:16px;font-weight:700}input{box-sizing:border-box;width:100%;margin-top:8px;padding:12px;border:1px solid #c8d4e3;border-radius:10px;font:inherit}.button{width:100%;margin-top:22px;padding:12px;border:0;border-radius:10px;background:#2167d5;color:#fff;font:inherit;font-weight:700;cursor:pointer}.notice{margin-top:18px;padding:14px 16px;border-radius:12px;background:#edf5ff;color:#285a99;font-weight:700}.error{background:#fff1f0;color:#a12b22}</style></head><body><main class="card"><h1>超级管理员密码重置</h1><p>本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。</p>{{if .Message}}<div class="notice {{if not .Success}}error{{end}}">{{.Message}}</div>{{end}}<form method="post" action="/reset" autocomplete="off"><input type="hidden" name="csrf_token" value="{{.CSRFToken}}"><label for="reset-code">一次性校验码</label><input id="reset-code" name="reset_code" required maxlength="32" autocomplete="one-time-code"><label for="new-password">新密码</label><input id="new-password" name="new_password" required minlength="8" maxlength="128" type="password" autocomplete="new-password"><label for="confirm-password">确认新密码</label><input id="confirm-password" name="confirm_password" required minlength="8" maxlength="128" type="password" autocomplete="new-password"><button class="button" type="submit">确认重置密码</button></form></main></body></html>`))
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>Scert 超级管理员密码重置</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f7fb;color:#172033;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}.card{width:min(520px,calc(100% - 40px));padding:34px;border:1px solid #dce5f1;border-radius:20px;background:#fff;box-shadow:0 18px 60px rgba(31,50,87,.12)}h1{margin:0 0 14px;font-size:26px}p{margin:8px 0;color:#52637b;line-height:1.7}label{display:block;margin-top:16px;font-weight:700}input{box-sizing:border-box;width:100%;margin-top:8px;padding:12px;border:1px solid #c8d4e3;border-radius:10px;font:inherit}.button{width:100%;margin-top:22px;padding:12px;border:0;border-radius:10px;background:#2167d5;color:#fff;font:inherit;font-weight:700;cursor:pointer}.notice{margin-top:18px;padding:14px 16px;border-radius:12px;background:#edf5ff;color:#285a99;font-weight:700}.error{background:#fff1f0;color:#a12b22}</style></head><body><main class="card"><h1>超级管理员密码重置</h1><p>本入口由 Scert-admin 临时开启,仅允许使用一次性校验码重置密码。</p>{{if .Message}}<div class="notice {{if not .Success}}error{{end}}">{{.Message}}</div>{{end}}<form method="post" action="/reset" autocomplete="off"><input type="hidden" name="csrf_token" value="{{.CSRFToken}}"><label for="reset-code">一次性校验码</label><input id="reset-code" name="reset_code" required maxlength="32" autocomplete="one-time-code"><label for="new-password">新密码</label><input id="new-password" name="new_password" required minlength="8" maxlength="12" type="password" autocomplete="new-password"><label for="confirm-password">确认新密码</label><input id="confirm-password" name="confirm_password" required minlength="8" maxlength="12" type="password" autocomplete="new-password"><button class="button" type="submit">确认重置密码</button></form></main></body></html>`))
|
||||
|
||||
var resetSuccessTemplate = template.Must(template.New("reset-success").Parse(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Scert 密码重置完成</title></head><body><main><h1>密码重置完成</h1><p>{{.Message}}</p></main></body></html>`))
|
||||
@@ -29,33 +29,39 @@ import (
|
||||
|
||||
type setupSecretWriter interface {
|
||||
Put(context.Context, string, map[string]string) error
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type Dependencies struct {
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
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)
|
||||
RollbackSetupCertificate func(context.Context, certificate.SavedResource) error
|
||||
ImportCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error)
|
||||
DeployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
CurrentCertificate certificateReader
|
||||
ResetStatePath string
|
||||
Audit repository.AuditRepository
|
||||
Tasks repository.TaskRepository
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
FrontendDir string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
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)
|
||||
RollbackSetupCertificate func(context.Context, certificate.SavedResource) error
|
||||
ImportCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error)
|
||||
DeployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
RestoreCertificateVersion func(context.Context, string, string) (certificate.IssueResult, error)
|
||||
|
||||
RunRenewal func(context.Context) (certificate.RenewalReport, error)
|
||||
CurrentCertificate certificateReader
|
||||
ResetStatePath string
|
||||
Audit repository.AuditRepository
|
||||
Tasks repository.TaskRepository
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
configMu sync.RWMutex
|
||||
config config.Config
|
||||
configPath string
|
||||
frontendDir string
|
||||
logger *logging.Logger
|
||||
repository repository.DomainRepository
|
||||
servers repository.ServerRepository
|
||||
@@ -68,28 +74,35 @@ type Server struct {
|
||||
rollbackSetupCertificate func(context.Context, certificate.SavedResource) error
|
||||
importCertificate func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error)
|
||||
deployCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
currentCertificate certificateReader
|
||||
resetStatePath string
|
||||
audit repository.AuditRepository
|
||||
tasks repository.TaskRepository
|
||||
resetMu sync.Mutex
|
||||
resetClosedHash string
|
||||
resetLimiter *resetRateLimiter
|
||||
authSessions map[string]authSession
|
||||
authMu sync.RWMutex
|
||||
loginAttempts map[string]loginAttempt
|
||||
loginMu sync.Mutex
|
||||
now func() time.Time
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
restoreVersion func(context.Context, string, string) (certificate.IssueResult, error)
|
||||
|
||||
runRenewal func(context.Context) (certificate.RenewalReport, error)
|
||||
currentCertificate certificateReader
|
||||
resetStatePath string
|
||||
audit repository.AuditRepository
|
||||
tasks repository.TaskRepository
|
||||
resetMu sync.Mutex
|
||||
resetClosedHash string
|
||||
resetLimiter *resetRateLimiter
|
||||
authSessions map[string]authSession
|
||||
authMu sync.RWMutex
|
||||
loginAttempts map[string]loginAttempt
|
||||
loginMu sync.Mutex
|
||||
now func() time.Time
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
}
|
||||
|
||||
func New(deps Dependencies) *Server {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
router := gin.New()
|
||||
router.Use(gin.Recovery())
|
||||
frontendDir := strings.TrimSpace(deps.FrontendDir)
|
||||
if frontendDir == "" {
|
||||
frontendDir = filepath.Join(deps.Config.Paths.Install, "web")
|
||||
}
|
||||
server := &Server{
|
||||
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger,
|
||||
config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger,
|
||||
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
|
||||
servers: deps.Servers,
|
||||
sshKeys: deps.SSHKeys,
|
||||
@@ -98,6 +111,8 @@ func New(deps Dependencies) *Server {
|
||||
rollbackSetupCertificate: deps.RollbackSetupCertificate,
|
||||
importCertificate: deps.ImportCertificate,
|
||||
deployCertificate: deps.DeployCertificate,
|
||||
restoreVersion: deps.RestoreCertificateVersion,
|
||||
runRenewal: deps.RunRenewal,
|
||||
currentCertificate: deps.CurrentCertificate,
|
||||
resetStatePath: deps.ResetStatePath,
|
||||
audit: deps.Audit,
|
||||
@@ -133,12 +148,16 @@ func (s *Server) registerRoutes() {
|
||||
adminAPI.GET("/tasks/:id", s.getTask)
|
||||
adminAPI.GET("/tasks/:id/attempts", s.listTaskAttempts)
|
||||
adminAPI.GET("/audit-logs", s.listAuditLogs)
|
||||
adminAPI.GET("/settings", s.getSettings)
|
||||
adminAPI.PUT("/settings", s.updateSettings)
|
||||
adminAPI.POST("/renewal/run", s.runRenewalNow)
|
||||
adminAPI.GET("/certificates", s.listCertificates)
|
||||
adminAPI.GET("/certificates/:id", s.getCertificate)
|
||||
adminAPI.POST("/domains/:id/certificate/import", s.importCertificateFiles)
|
||||
adminAPI.POST("/domains/:id/certificate/validate", s.validateCertificate)
|
||||
adminAPI.POST("/domains/:id/deploy", s.deployCertificateCurrent)
|
||||
adminAPI.GET("/domains/:id/certificate/versions", s.listCertificateVersions)
|
||||
adminAPI.POST("/domains/:id/certificate/versions/:version/restore", s.restoreCertificateVersion)
|
||||
adminAPI.GET("/domains/:id/servers", s.listDomainServers)
|
||||
adminAPI.PUT("/domains/:id/servers", s.replaceDomainServers)
|
||||
adminAPI.GET("/servers", s.listServers)
|
||||
@@ -149,6 +168,7 @@ func (s *Server) registerRoutes() {
|
||||
adminAPI.GET("/ssh-keys", s.listSSHKeys)
|
||||
adminAPI.POST("/ssh-keys", s.createSSHKey)
|
||||
adminAPI.DELETE("/ssh-keys/:id", s.deleteSSHKey)
|
||||
s.router.NoRoute(s.frontend)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
|
||||
@@ -134,8 +134,8 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) {
|
||||
form := url.Values{
|
||||
"csrf_token": {cookie.Value},
|
||||
"reset_code": {session.Code},
|
||||
"new_password": {"NewPassword123"},
|
||||
"confirm_password": {"NewPassword123"},
|
||||
"new_password": {"NewPass1234"},
|
||||
"confirm_password": {"NewPass1234"},
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
@@ -157,7 +157,7 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("读取重置后的配置失败:%v", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil {
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPass1234")) != nil {
|
||||
t.Fatal("新密码摘要无法验证新密码")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("OldPassword123")) == nil {
|
||||
@@ -191,7 +191,7 @@ func TestResetRejectsCrossSiteAndLimitsFailures(t *testing.T) {
|
||||
get := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "http://scert.example.test/reset", nil))
|
||||
cookie := get.Result().Cookies()[0]
|
||||
base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPassword123"}, "confirm_password": {"NewPassword123"}}
|
||||
base := url.Values{"csrf_token": {cookie.Value}, "reset_code": {session.Code}, "new_password": {"NewPass1234"}, "confirm_password": {"NewPass1234"}}
|
||||
for i := 0; i < 5; i++ {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://scert.example.test/reset", strings.NewReader(base.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
@@ -296,7 +296,7 @@ func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) {
|
||||
}
|
||||
fixture.server.configPath = blockedPath
|
||||
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234")
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
request.Header.Set("Origin", "https://scert.example.test")
|
||||
@@ -329,7 +329,7 @@ func TestResetConfigSaveFailureKeepsSessionAndPassword(t *testing.T) {
|
||||
|
||||
func TestResetRejectsOversizedRequestBody(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234")
|
||||
form.Set("padding", strings.Repeat("x", resetMaxBodyBytes))
|
||||
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
@@ -365,7 +365,7 @@ func TestResetCSRFCookieHasRestrictedAttributes(t *testing.T) {
|
||||
|
||||
func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) {
|
||||
fixture := newResetTestFixture(t)
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPassword123")
|
||||
form := resetForm(fixture.session.Code, fixture.cookie.Value, "NewPass1234")
|
||||
start := make(chan struct{})
|
||||
responses := make(chan int, 2)
|
||||
var waitGroup sync.WaitGroup
|
||||
@@ -410,7 +410,7 @@ func TestResetConcurrentSubmissionsAllowOnlyOneSuccess(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("读取并发提交后的配置失败:%v", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPassword123")) != nil {
|
||||
if bcrypt.CompareHashAndPassword([]byte(loaded.Admin.PasswordHash), []byte("NewPass1234")) != nil {
|
||||
t.Fatal("并发提交后的密码摘要无法验证新密码")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
type settingsView struct {
|
||||
Server settingsServerView `json:"server"`
|
||||
Web settingsWebView `json:"web"`
|
||||
Paths settingsPathsView `json:"paths"`
|
||||
ACME settingsACMEView `json:"acme"`
|
||||
DNS settingsDNSView `json:"dns"`
|
||||
Notification settingsNotificationView `json:"notification"`
|
||||
}
|
||||
|
||||
type settingsServerView struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
HTTPSMode string `json:"https_mode"`
|
||||
}
|
||||
|
||||
type settingsWebView struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Hostname string `json:"hostname"`
|
||||
PublicIP string `json:"public_ip"`
|
||||
}
|
||||
|
||||
type settingsPathsView struct {
|
||||
Certificate string `json:"certificate"`
|
||||
}
|
||||
|
||||
type settingsACMEView struct {
|
||||
CA string `json:"ca"`
|
||||
Environment string `json:"environment"`
|
||||
AccountEmail string `json:"account_email"`
|
||||
RenewalThresholdDays int `json:"renewal_threshold_days"`
|
||||
PropagationTimeoutSecs int `json:"propagation_timeout_secs"`
|
||||
PropagationPollingIntervalSecs int `json:"propagation_polling_interval_secs"`
|
||||
}
|
||||
|
||||
type settingsDNSView struct {
|
||||
Provider string `json:"provider"`
|
||||
VerificationState string `json:"verification_state"`
|
||||
}
|
||||
|
||||
type settingsNotificationView struct {
|
||||
HTTPEnabled bool `json:"http_enabled"`
|
||||
SMTPEnabled bool `json:"smtp_enabled"`
|
||||
SMTPHost string `json:"smtp_host"`
|
||||
SMTPPort int `json:"smtp_port"`
|
||||
SMTPUsername string `json:"smtp_username"`
|
||||
SMTPMode string `json:"smtp_mode"`
|
||||
SMTPAllowPlaintextAuth bool `json:"smtp_allow_plaintext_auth"`
|
||||
SMTPCredentialConfigured bool `json:"smtp_credential_configured"`
|
||||
Provider string `json:"provider"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
HTTPPath string `json:"http_path"`
|
||||
HTTPLoginPath string `json:"http_login_path"`
|
||||
HTTPAuthMode string `json:"http_auth_mode"`
|
||||
HTTPCredentialConfigured bool `json:"http_credential_configured"`
|
||||
EventMode string `json:"event_mode"`
|
||||
IncludeDeploymentDetails bool `json:"include_deployment_details"`
|
||||
IncludeCertificateSerial bool `json:"include_certificate_serial"`
|
||||
IncludeManagementURL bool `json:"include_management_url"`
|
||||
SenderName string `json:"sender_name"`
|
||||
SenderEmail string `json:"sender_email"`
|
||||
Recipients []string `json:"recipients"`
|
||||
TimeoutSecs int `json:"timeout_secs"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
RetryIntervalsSecs []int `json:"retry_intervals_secs"`
|
||||
}
|
||||
|
||||
type settingsRequest struct {
|
||||
Server *settingsServerRequest `json:"server"`
|
||||
Web *settingsWebRequest `json:"web"`
|
||||
Paths *settingsPathsRequest `json:"paths"`
|
||||
ACME *settingsACMERequest `json:"acme"`
|
||||
DNS *settingsDNSRequest `json:"dns"`
|
||||
Notification *settingsNotificationRequest `json:"notification"`
|
||||
}
|
||||
|
||||
type settingsServerRequest struct {
|
||||
Host *string `json:"host"`
|
||||
Port *int `json:"port"`
|
||||
HTTPSMode *string `json:"https_mode"`
|
||||
}
|
||||
|
||||
type settingsWebRequest struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Hostname *string `json:"hostname"`
|
||||
PublicIP *string `json:"public_ip"`
|
||||
}
|
||||
|
||||
type settingsPathsRequest struct {
|
||||
Certificate *string `json:"certificate"`
|
||||
}
|
||||
|
||||
type settingsACMERequest struct {
|
||||
CA *string `json:"ca"`
|
||||
Environment *string `json:"environment"`
|
||||
AccountEmail *string `json:"account_email"`
|
||||
RenewalThresholdDays *int `json:"renewal_threshold_days"`
|
||||
PropagationTimeoutSecs *int `json:"propagation_timeout_secs"`
|
||||
PropagationPollingIntervalSecs *int `json:"propagation_polling_interval_secs"`
|
||||
}
|
||||
|
||||
type settingsDNSRequest struct {
|
||||
Provider *string `json:"provider"`
|
||||
}
|
||||
|
||||
type settingsNotificationRequest struct {
|
||||
HTTPEnabled *bool `json:"http_enabled"`
|
||||
SMTPEnabled *bool `json:"smtp_enabled"`
|
||||
SMTPHost *string `json:"smtp_host"`
|
||||
SMTPPort *int `json:"smtp_port"`
|
||||
SMTPUsername *string `json:"smtp_username"`
|
||||
SMTPPassword *string `json:"smtp_password"`
|
||||
SMTPMode *string `json:"smtp_mode"`
|
||||
SMTPAllowPlaintextAuth *bool `json:"smtp_allow_plaintext_auth"`
|
||||
HTTPCredentials map[string]string `json:"http_credentials"`
|
||||
Provider *string `json:"provider"`
|
||||
Endpoint *string `json:"endpoint"`
|
||||
HTTPPath *string `json:"http_path"`
|
||||
HTTPLoginPath *string `json:"http_login_path"`
|
||||
HTTPAuthMode *string `json:"http_auth_mode"`
|
||||
EventMode *string `json:"event_mode"`
|
||||
IncludeDeploymentDetails *bool `json:"include_deployment_details"`
|
||||
IncludeCertificateSerial *bool `json:"include_certificate_serial"`
|
||||
IncludeManagementURL *bool `json:"include_management_url"`
|
||||
SenderName *string `json:"sender_name"`
|
||||
SenderEmail *string `json:"sender_email"`
|
||||
Recipients *[]string `json:"recipients"`
|
||||
TimeoutSecs *int `json:"timeout_secs"`
|
||||
RetryCount *int `json:"retry_count"`
|
||||
RetryIntervalsSecs *[]int `json:"retry_intervals_secs"`
|
||||
}
|
||||
|
||||
func (s *Server) getSettings(c *gin.Context) {
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
c.JSON(http.StatusOK, settingsViewFromConfig(cfg))
|
||||
}
|
||||
|
||||
func (s *Server) updateSettings(c *gin.Context) {
|
||||
if strings.TrimSpace(s.configPath) == "" {
|
||||
s.writeError(c, http.StatusInternalServerError, "配置文件路径未配置", errors.New("配置文件路径为空"))
|
||||
return
|
||||
}
|
||||
var request settingsRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "设置请求格式不正确", err)
|
||||
return
|
||||
}
|
||||
|
||||
s.configMu.Lock()
|
||||
previous := s.config
|
||||
updated := s.config
|
||||
applySettingsRequest(&updated, request)
|
||||
updated.Normalize()
|
||||
if err := s.saveSettingsNotificationCredentials(c.Request.Context(), &updated, request); err != nil {
|
||||
s.configMu.Unlock()
|
||||
s.writeError(c, http.StatusBadRequest, "保存通知凭据失败", err)
|
||||
return
|
||||
}
|
||||
if err := updated.Validate(); err != nil {
|
||||
s.configMu.Unlock()
|
||||
s.writeError(c, http.StatusBadRequest, "设置内容校验失败", err)
|
||||
return
|
||||
}
|
||||
if err := updated.Save(s.configPath); err != nil {
|
||||
s.configMu.Unlock()
|
||||
s.writeError(c, http.StatusInternalServerError, "保存设置失败", err)
|
||||
return
|
||||
}
|
||||
restartRequired := previous.Server.Host != updated.Server.Host ||
|
||||
previous.Server.Port != updated.Server.Port ||
|
||||
previous.Server.HTTPSMode != updated.Server.HTTPSMode ||
|
||||
previous.Paths.Certificate != updated.Paths.Certificate ||
|
||||
!reflect.DeepEqual(previous.ACME, updated.ACME) ||
|
||||
!reflect.DeepEqual(previous.DNS, updated.DNS) ||
|
||||
!reflect.DeepEqual(previous.Notification, updated.Notification)
|
||||
message := "设置已保存"
|
||||
if restartRequired {
|
||||
message = "设置已保存;服务监听地址、端口或 HTTPS 模式已变更,请重启 Scert 服务"
|
||||
}
|
||||
s.config = updated
|
||||
s.configMu.Unlock()
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"settings": settingsViewFromConfig(updated),
|
||||
"restart_required": restartRequired,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
func settingsViewFromConfig(cfg config.Config) settingsView {
|
||||
return settingsView{
|
||||
Server: settingsServerView{Host: cfg.Server.Host, Port: cfg.Server.Port, HTTPSMode: cfg.Server.HTTPSMode},
|
||||
Web: settingsWebView{Enabled: cfg.Web.Enabled, Hostname: cfg.Web.Hostname, PublicIP: cfg.Web.PublicIP},
|
||||
Paths: settingsPathsView{Certificate: cfg.Paths.Certificate},
|
||||
ACME: settingsACMEView{CA: cfg.ACME.CA, Environment: cfg.ACME.Environment, AccountEmail: cfg.ACME.AccountEmail, RenewalThresholdDays: cfg.ACME.RenewalThresholdDays, PropagationTimeoutSecs: cfg.ACME.PropagationTimeoutSecs, PropagationPollingIntervalSecs: cfg.ACME.PropagationPollingIntervalSecs},
|
||||
DNS: settingsDNSView{Provider: cfg.DNS.Provider, VerificationState: cfg.DNS.VerificationState},
|
||||
Notification: settingsNotificationView{
|
||||
HTTPEnabled: cfg.Notification.HTTPEnabled, SMTPEnabled: cfg.Notification.SMTPEnabled, Provider: cfg.Notification.Provider,
|
||||
SMTPHost: cfg.Notification.SMTPHost, SMTPPort: cfg.Notification.SMTPPort, SMTPUsername: cfg.Notification.SMTPUsername,
|
||||
SMTPMode: cfg.Notification.SMTPMode, SMTPAllowPlaintextAuth: cfg.Notification.SMTPAllowPlaintextAuth,
|
||||
SMTPCredentialConfigured: strings.TrimSpace(cfg.Notification.SMTPCredentialRef) != "",
|
||||
Endpoint: cfg.Notification.Endpoint, HTTPPath: cfg.Notification.HTTPPath, HTTPLoginPath: cfg.Notification.HTTPLoginPath,
|
||||
HTTPAuthMode: cfg.Notification.HTTPAuthMode, HTTPCredentialConfigured: strings.TrimSpace(cfg.Notification.HTTPCredentialRef) != "",
|
||||
EventMode: cfg.Notification.EventMode, IncludeDeploymentDetails: cfg.Notification.IncludeDeploymentDetails,
|
||||
IncludeCertificateSerial: cfg.Notification.IncludeCertificateSerial, IncludeManagementURL: cfg.Notification.IncludeManagementURL,
|
||||
SenderName: cfg.Notification.SenderName, SenderEmail: cfg.Notification.SenderEmail,
|
||||
Recipients: append([]string(nil), cfg.Notification.Recipients...), TimeoutSecs: cfg.Notification.TimeoutSecs,
|
||||
RetryCount: cfg.Notification.RetryCount, RetryIntervalsSecs: append([]int(nil), cfg.Notification.RetryIntervalsSecs...),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func applySettingsRequest(cfg *config.Config, request settingsRequest) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if request.Server != nil {
|
||||
if request.Server.Host != nil {
|
||||
cfg.Server.Host = strings.TrimSpace(*request.Server.Host)
|
||||
}
|
||||
if request.Server.Port != nil {
|
||||
cfg.Server.Port = *request.Server.Port
|
||||
}
|
||||
if request.Server.HTTPSMode != nil {
|
||||
cfg.Server.HTTPSMode = strings.TrimSpace(*request.Server.HTTPSMode)
|
||||
}
|
||||
}
|
||||
if request.Web != nil {
|
||||
if request.Web.Enabled != nil {
|
||||
cfg.Web.Enabled = *request.Web.Enabled
|
||||
}
|
||||
if request.Web.Hostname != nil {
|
||||
cfg.Web.Hostname = strings.TrimSpace(*request.Web.Hostname)
|
||||
}
|
||||
if request.Web.PublicIP != nil {
|
||||
cfg.Web.PublicIP = strings.TrimSpace(*request.Web.PublicIP)
|
||||
}
|
||||
}
|
||||
if request.Paths != nil && request.Paths.Certificate != nil {
|
||||
cfg.Paths.Certificate = strings.TrimSpace(*request.Paths.Certificate)
|
||||
}
|
||||
if request.ACME != nil {
|
||||
if request.ACME.CA != nil {
|
||||
cfg.ACME.CA = strings.TrimSpace(*request.ACME.CA)
|
||||
}
|
||||
if request.ACME.Environment != nil {
|
||||
cfg.ACME.Environment = strings.TrimSpace(*request.ACME.Environment)
|
||||
}
|
||||
if request.ACME.AccountEmail != nil {
|
||||
cfg.ACME.AccountEmail = strings.TrimSpace(*request.ACME.AccountEmail)
|
||||
}
|
||||
if request.ACME.RenewalThresholdDays != nil {
|
||||
cfg.ACME.RenewalThresholdDays = *request.ACME.RenewalThresholdDays
|
||||
}
|
||||
if request.ACME.PropagationTimeoutSecs != nil {
|
||||
cfg.ACME.PropagationTimeoutSecs = *request.ACME.PropagationTimeoutSecs
|
||||
}
|
||||
if request.ACME.PropagationPollingIntervalSecs != nil {
|
||||
cfg.ACME.PropagationPollingIntervalSecs = *request.ACME.PropagationPollingIntervalSecs
|
||||
}
|
||||
}
|
||||
if request.DNS != nil && request.DNS.Provider != nil {
|
||||
cfg.DNS.Provider = strings.TrimSpace(*request.DNS.Provider)
|
||||
}
|
||||
if request.Notification != nil {
|
||||
item := request.Notification
|
||||
if item.HTTPEnabled != nil {
|
||||
cfg.Notification.HTTPEnabled = *item.HTTPEnabled
|
||||
}
|
||||
if item.SMTPEnabled != nil {
|
||||
cfg.Notification.SMTPEnabled = *item.SMTPEnabled
|
||||
}
|
||||
if item.SMTPHost != nil {
|
||||
cfg.Notification.SMTPHost = strings.TrimSpace(*item.SMTPHost)
|
||||
}
|
||||
if item.SMTPPort != nil {
|
||||
cfg.Notification.SMTPPort = *item.SMTPPort
|
||||
}
|
||||
if item.SMTPUsername != nil {
|
||||
cfg.Notification.SMTPUsername = strings.TrimSpace(*item.SMTPUsername)
|
||||
}
|
||||
if item.SMTPMode != nil {
|
||||
cfg.Notification.SMTPMode = strings.TrimSpace(*item.SMTPMode)
|
||||
}
|
||||
if item.SMTPAllowPlaintextAuth != nil {
|
||||
cfg.Notification.SMTPAllowPlaintextAuth = *item.SMTPAllowPlaintextAuth
|
||||
}
|
||||
if item.Provider != nil {
|
||||
cfg.Notification.Provider = strings.TrimSpace(*item.Provider)
|
||||
}
|
||||
if item.Endpoint != nil {
|
||||
cfg.Notification.Endpoint = strings.TrimSpace(*item.Endpoint)
|
||||
}
|
||||
if item.HTTPPath != nil {
|
||||
cfg.Notification.HTTPPath = strings.TrimSpace(*item.HTTPPath)
|
||||
}
|
||||
if item.HTTPLoginPath != nil {
|
||||
cfg.Notification.HTTPLoginPath = strings.TrimSpace(*item.HTTPLoginPath)
|
||||
}
|
||||
if item.HTTPAuthMode != nil {
|
||||
cfg.Notification.HTTPAuthMode = strings.TrimSpace(*item.HTTPAuthMode)
|
||||
}
|
||||
if item.EventMode != nil {
|
||||
cfg.Notification.EventMode = strings.TrimSpace(*item.EventMode)
|
||||
}
|
||||
if item.IncludeDeploymentDetails != nil {
|
||||
cfg.Notification.IncludeDeploymentDetails = *item.IncludeDeploymentDetails
|
||||
}
|
||||
if item.IncludeCertificateSerial != nil {
|
||||
cfg.Notification.IncludeCertificateSerial = *item.IncludeCertificateSerial
|
||||
}
|
||||
if item.IncludeManagementURL != nil {
|
||||
cfg.Notification.IncludeManagementURL = *item.IncludeManagementURL
|
||||
}
|
||||
if item.SenderName != nil {
|
||||
cfg.Notification.SenderName = strings.TrimSpace(*item.SenderName)
|
||||
}
|
||||
if item.SenderEmail != nil {
|
||||
cfg.Notification.SenderEmail = strings.TrimSpace(*item.SenderEmail)
|
||||
}
|
||||
if item.Recipients != nil {
|
||||
cfg.Notification.Recipients = append([]string(nil), (*item.Recipients)...)
|
||||
}
|
||||
if item.TimeoutSecs != nil {
|
||||
cfg.Notification.TimeoutSecs = *item.TimeoutSecs
|
||||
}
|
||||
if item.RetryCount != nil {
|
||||
cfg.Notification.RetryCount = *item.RetryCount
|
||||
}
|
||||
if item.RetryIntervalsSecs != nil {
|
||||
cfg.Notification.RetryIntervalsSecs = append([]int(nil), (*item.RetryIntervalsSecs)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestSettingsAPIRequiresAuthentication(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
server := New(Dependencies{Config: cfg})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/settings", nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("未登录访问设置接口应返回 401,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsAPIUpdatesSafeFieldsWithoutReturningSecrets(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
cfg.Database.DSN = "mysql://secret-user:secret-password@localhost/scert"
|
||||
configPath := dir + "\\config\\scert.json"
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||
"server": {"port": 5443},
|
||||
"web": {"hostname": "admin.example.test"},
|
||||
"acme": {"renewal_threshold_days": 10}
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("更新设置应成功,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, secret := range []string{"password_hash", "secret-password", "credential_ref", "tls_key", "mysql://"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("响应不应包含敏感字段 %q:%s", secret, body)
|
||||
}
|
||||
}
|
||||
var payload struct {
|
||||
Settings settingsView `json:"settings"`
|
||||
RestartRequired bool `json:"restart_required"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("解析设置响应失败:%v", err)
|
||||
}
|
||||
if !payload.RestartRequired || payload.Settings.Server.Port != 5443 || payload.Settings.Web.Hostname != "admin.example.test" || payload.Settings.ACME.RenewalThresholdDays != 10 {
|
||||
t.Fatalf("设置响应内容不正确:%+v", payload.Settings)
|
||||
}
|
||||
if !strings.Contains(payload.Message, "请重启 Scert 服务") {
|
||||
t.Fatalf("监听参数变更后应明确提示重启服务:%s", payload.Message)
|
||||
}
|
||||
saved, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取保存后的配置失败:%v", err)
|
||||
}
|
||||
if saved.Admin.PasswordHash != cfg.Admin.PasswordHash || saved.Database.DSN != cfg.Database.DSN {
|
||||
t.Fatal("更新设置不应覆盖管理员密码或数据库 DSN")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsAPIWebAddressChangeDoesNotRequireRestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
configPath := dir + "\\config\\scert.json"
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||
"web": {"hostname": "admin.example.test", "public_ip": "203.0.113.10"}
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("更新 Web 访问地址应成功,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
RestartRequired bool `json:"restart_required"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("解析设置响应失败:%v", err)
|
||||
}
|
||||
if payload.RestartRequired {
|
||||
t.Fatal("仅修改 Web 域名或公网 IP 不应要求重启服务")
|
||||
}
|
||||
if payload.Message != "设置已保存" {
|
||||
t.Fatalf("无需重启时应返回简洁保存提示:%s", payload.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsAPIReturnsChineseNotificationCredentialError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default(dir)
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
configPath := dir + "\\config\\scert.json"
|
||||
if err := cfg.Save(configPath); err != nil {
|
||||
t.Fatalf("保存测试配置失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{Config: cfg, ConfigPath: configPath})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||
"notification": {"smtp_password": "secret-password"}
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("敏感凭据存储未配置时应返回 400,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
if !strings.Contains(response.Body.String(), "保存通知凭据失败") {
|
||||
t.Fatalf("响应应包含中文通知凭据错误说明:%s", response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "???") {
|
||||
t.Fatalf("响应不应包含问号乱码:%s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewalAPIUsesConfiguredRunner(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
cfg.DNS.VerificationState = "verified"
|
||||
cfg.Web.Hostname = "scert.example.test"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.test"
|
||||
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||
called := false
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
RunRenewal: func(context.Context) (certificate.RenewalReport, error) {
|
||||
called = true
|
||||
return certificate.RenewalReport{Checked: 2, Selected: 1, Succeeded: 1}, nil
|
||||
},
|
||||
})
|
||||
cookie := loginForSettingsTest(t, server)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/renewal/run", nil)
|
||||
request.AddCookie(cookie)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !called || !strings.Contains(response.Body.String(), `"selected":1`) {
|
||||
t.Fatalf("续期接口调用结果不正确:%d %s;called=%v", response.Code, response.Body.String(), called)
|
||||
}
|
||||
}
|
||||
|
||||
func loginForSettingsTest(t *testing.T, server *Server) *http.Cookie {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"admin","password":"Password123"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("管理员登录失败:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
cookies := response.Result().Cookies()
|
||||
if len(cookies) == 0 {
|
||||
t.Fatal("登录响应未返回会话 Cookie")
|
||||
}
|
||||
return cookies[0]
|
||||
}
|
||||
|
||||
func mustTestPasswordHash(t *testing.T, password string) string {
|
||||
t.Helper()
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
return string(hash)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
// saveSettingsNotificationCredentials 将页面提交的通知密码写入加密存储,配置文件只保存引用。
|
||||
func (s *Server) saveSettingsNotificationCredentials(ctx context.Context, cfg *config.Config, request settingsRequest) error {
|
||||
if cfg == nil || request.Notification == nil {
|
||||
return nil
|
||||
}
|
||||
item := request.Notification
|
||||
if len(item.HTTPCredentials) > 0 {
|
||||
if s.secrets == nil {
|
||||
return errors.New("HTTP 通知敏感凭据存储尚未初始化")
|
||||
}
|
||||
values, err := normalizeNotificationCredentials(cfg.Notification.HTTPAuthMode, item.HTTPCredentials)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref, err := newNotificationCredentialReference()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Notification.HTTPCredentialRef = ref
|
||||
}
|
||||
if item.SMTPPassword == nil || *item.SMTPPassword == "" {
|
||||
return nil
|
||||
}
|
||||
if s.secrets == nil {
|
||||
return errors.New("SMTP 通知敏感凭据存储尚未初始化")
|
||||
}
|
||||
username := strings.TrimSpace(cfg.Notification.SMTPUsername)
|
||||
if username == "" {
|
||||
return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名")
|
||||
}
|
||||
ref, err := newNotificationCredentialReference()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
values := map[string]string{"username": username, "password": *item.SMTPPassword}
|
||||
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Notification.SMTPCredentialRef = ref
|
||||
return nil
|
||||
}
|
||||
@@ -34,6 +34,13 @@ type setupRequest struct {
|
||||
AdminPassword string `json:"admin_password"`
|
||||
ServerPort int `json:"server_port"`
|
||||
EmailHTTPEnabled *bool `json:"email_http_enabled"`
|
||||
EmailSMTPEnabled *bool `json:"email_smtp_enabled"`
|
||||
EmailSMTPHost string `json:"email_smtp_host"`
|
||||
EmailSMTPPort int `json:"email_smtp_port"`
|
||||
EmailSMTPUsername string `json:"email_smtp_username"`
|
||||
EmailSMTPPassword string `json:"email_smtp_password"`
|
||||
EmailSMTPMode string `json:"email_smtp_mode"`
|
||||
EmailSMTPAllowPlaintextAuth bool `json:"email_smtp_allow_plaintext_auth"`
|
||||
EmailProvider string `json:"email_provider"`
|
||||
EmailEndpoint string `json:"email_endpoint"`
|
||||
EmailHTTPPath string `json:"email_http_path"`
|
||||
@@ -145,10 +152,15 @@ func (s *Server) testSetupDNS(c *gin.Context) {
|
||||
s.writeError(c, http.StatusNotImplemented, "该 DNS 服务商在线验证适配器尚未开放", nil)
|
||||
return
|
||||
}
|
||||
report := result.TestReport
|
||||
var verificationErr *setup.DNSVerificationError
|
||||
if errors.As(err, &verificationErr) {
|
||||
report = verificationErr.Report
|
||||
}
|
||||
if s.logger != nil {
|
||||
s.logger.Error("DNS API 在线验证失败", "provider", request.ProviderID, "test_domain", request.TestDomain)
|
||||
}
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "DNS API 在线验证失败,请检查凭据、测试域名和 DNS 权限"})
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "DNS API 在线验证失败,请检查凭据、测试域名和 DNS 权限", "test_report": report})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -156,6 +168,7 @@ func (s *Server) testSetupDNS(c *gin.Context) {
|
||||
"credential_ref": result.CredentialRef,
|
||||
"verification_token": result.VerificationToken,
|
||||
"expires_at": result.ExpiresAt,
|
||||
"test_report": result.TestReport,
|
||||
"message": "DNS API 在线验证通过,凭据已加密保存。",
|
||||
})
|
||||
}
|
||||
@@ -197,7 +210,37 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
if request.EmailHTTPEnabled != nil {
|
||||
emailHTTPEnabled = *request.EmailHTTPEnabled
|
||||
}
|
||||
emailSMTPEnabled := false
|
||||
if request.EmailSMTPEnabled != nil {
|
||||
emailSMTPEnabled = *request.EmailSMTPEnabled
|
||||
}
|
||||
createdCredentialRefs := make([]string, 0, 2)
|
||||
emailCredentialRef := strings.TrimSpace(request.EmailHTTPCredentialRef)
|
||||
smtpCredentialRef := ""
|
||||
if emailSMTPEnabled {
|
||||
smtpCredentialRef = strings.TrimSpace(s.config.Notification.SMTPCredentialRef)
|
||||
if strings.TrimSpace(request.EmailSMTPPassword) != "" {
|
||||
if strings.TrimSpace(request.EmailSMTPUsername) == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "填写 SMTP 密码前必须配置 SMTP 用户名", nil)
|
||||
return
|
||||
}
|
||||
if s.secrets == nil {
|
||||
s.writeError(c, http.StatusServiceUnavailable, "SMTP 通知敏感凭据存储尚未初始化", nil)
|
||||
return
|
||||
}
|
||||
var smtpErr error
|
||||
smtpCredentialRef, smtpErr = newNotificationCredentialReference()
|
||||
if smtpErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "生成 SMTP 通知凭据引用失败", smtpErr)
|
||||
return
|
||||
}
|
||||
createdCredentialRefs = append(createdCredentialRefs, smtpCredentialRef)
|
||||
}
|
||||
if smtpCredentialRef == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "启用 SMTP 通知后必须填写 SMTP 密码或使用已有凭据", nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
var notificationCredentials map[string]string
|
||||
var credentialErr error
|
||||
if emailHTTPEnabled && strings.ToLower(strings.TrimSpace(request.EmailHTTPAuthMode)) != "none" {
|
||||
@@ -216,6 +259,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
s.writeError(c, http.StatusInternalServerError, "生成 HTTP 通知凭据引用失败", credentialErr)
|
||||
return
|
||||
}
|
||||
createdCredentialRefs = append(createdCredentialRefs, emailCredentialRef)
|
||||
} else if emailCredentialRef == "" {
|
||||
s.writeError(c, http.StatusBadRequest, "启用 HTTP 通知认证后必须填写明文凭据或已有凭据引用", nil)
|
||||
return
|
||||
@@ -228,6 +272,13 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
AdminPassword: request.AdminPassword,
|
||||
ServerPort: request.ServerPort,
|
||||
EmailHTTPEnabled: emailHTTPEnabled,
|
||||
EmailSMTPEnabled: emailSMTPEnabled,
|
||||
EmailSMTPHost: request.EmailSMTPHost,
|
||||
EmailSMTPPort: request.EmailSMTPPort,
|
||||
EmailSMTPUsername: request.EmailSMTPUsername,
|
||||
EmailSMTPCredentialRef: smtpCredentialRef,
|
||||
EmailSMTPMode: request.EmailSMTPMode,
|
||||
EmailSMTPAllowPlaintextAuth: request.EmailSMTPAllowPlaintextAuth,
|
||||
EmailProvider: request.EmailProvider,
|
||||
EmailEndpoint: request.EmailEndpoint,
|
||||
EmailHTTPPath: request.EmailHTTPPath,
|
||||
@@ -257,18 +308,22 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
HTTPSMode: request.HTTPSMode,
|
||||
})
|
||||
if err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(s.configPath) == "" {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusInternalServerError, "服务未配置配置文件路径,无法保存初始化结果", nil)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(updated.Web.PublicIP) != "" {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusBadRequest, "公网 IP 暂不支持通过 DNS-01 自动申请管理后台证书,请先配置域名或上传自有证书", nil)
|
||||
return
|
||||
}
|
||||
if s.issueSetupCertificate == nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusServiceUnavailable, "初始化证书申请服务尚未配置", nil)
|
||||
return
|
||||
}
|
||||
@@ -286,10 +341,12 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
})
|
||||
certificateCancel()
|
||||
if certificateErr != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
s.writeError(c, http.StatusBadGateway, "申请管理后台证书失败,初始化尚未完成", certificateErr)
|
||||
return
|
||||
}
|
||||
if err := validateSetupCertificateFiles(savedCertificate); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("管理后台证书文件校验失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -300,6 +357,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
updated.Server.TLSKey = savedCertificate.PrivateKeyPath
|
||||
if len(notificationCredentials) > 0 {
|
||||
if err := s.secrets.Put(c.Request.Context(), emailCredentialRef, notificationCredentials); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存 HTTP 通知凭据失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -307,8 +365,22 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if emailSMTPEnabled && strings.TrimSpace(request.EmailSMTPPassword) != "" {
|
||||
if err := s.secrets.Put(c.Request.Context(), smtpCredentialRef, map[string]string{
|
||||
"username": strings.TrimSpace(request.EmailSMTPUsername),
|
||||
"password": request.EmailSMTPPassword,
|
||||
}); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存 SMTP 通知凭据失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "保存 SMTP 通知凭据失败,初始化尚未完成", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
updated.SetupReady = true
|
||||
if err := updated.Validate(); err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("初始化证书配置无效,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -324,6 +396,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
firewallResult, err = s.firewall.OpenTCP(firewallContext, updated.Server.Port)
|
||||
cancel()
|
||||
if err != nil {
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("自动配置本机防火墙失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
@@ -345,6 +418,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
if certificateRollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存初始化配置失败,且初始化证书回滚失败", "error", certificateRollbackErr)
|
||||
}
|
||||
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||
if firewallRollbackErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败,且自动创建的防火墙规则回滚失败,请手动检查本机防火墙", err)
|
||||
return
|
||||
@@ -376,6 +450,36 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) rollbackSetupCredentialsWithLog(references []string) {
|
||||
if err := s.rollbackSetupCredentials(references); err != nil && s.logger != nil {
|
||||
s.logger.Error("\u521d\u59cb\u5316\u654f\u611f\u51ed\u636e\u56de\u6eda\u5931\u8d25", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) rollbackSetupCredentials(references []string) error {
|
||||
if s == nil || s.secrets == nil || len(references) == 0 {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
seen := make(map[string]struct{}, len(references))
|
||||
var rollbackErrors []error
|
||||
for _, reference := range references {
|
||||
reference = strings.TrimSpace(reference)
|
||||
if reference == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[reference]; ok {
|
||||
continue
|
||||
}
|
||||
seen[reference] = struct{}{}
|
||||
if err := s.secrets.Delete(ctx, reference); err != nil {
|
||||
rollbackErrors = append(rollbackErrors, fmt.Errorf("\u56de\u6eda\u654f\u611f\u51ed\u636e %s \u5931\u8d25\uFF1A%w", reference, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(rollbackErrors...)
|
||||
}
|
||||
|
||||
func (s *Server) rollbackIssuedSetupCertificate(saved certificate.SavedResource) error {
|
||||
if s.rollbackSetupCertificate == nil {
|
||||
return nil
|
||||
|
||||
@@ -29,7 +29,8 @@ type fakeSetupDNSVerifier struct {
|
||||
}
|
||||
|
||||
type fakeSetupSecretWriter struct {
|
||||
values map[string]map[string]string
|
||||
values map[string]map[string]string
|
||||
deleted []string
|
||||
}
|
||||
|
||||
func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value map[string]string) error {
|
||||
@@ -44,6 +45,18 @@ func (f *fakeSetupSecretWriter) Put(_ context.Context, reference string, value m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSetupSecretWriter) Delete(_ context.Context, reference string) error {
|
||||
if f.values == nil {
|
||||
return errors.New("secret not found")
|
||||
}
|
||||
if _, ok := f.values[reference]; !ok {
|
||||
return errors.New("secret not found")
|
||||
}
|
||||
delete(f.values, reference)
|
||||
f.deleted = append(f.deleted, reference)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeFirewallManager struct {
|
||||
result firewall.Result
|
||||
openErr error
|
||||
@@ -99,6 +112,14 @@ func (f *fakeSetupDNSVerifier) Verify(context.Context, setup.DNSVerificationInpu
|
||||
CredentialRef: "secret://dns/cloudflare/test",
|
||||
VerificationToken: "verified-token",
|
||||
ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
|
||||
TestReport: setup.DNSVerificationReport{
|
||||
RecordName: "_acme-challenge.example.com.",
|
||||
Stages: []setup.DNSVerificationStage{
|
||||
{Name: "创建记录", Status: "completed", Message: "已创建测试记录"},
|
||||
{Name: "查询记录", Status: "completed", Message: "已确认测试记录"},
|
||||
{Name: "清理记录", Status: "completed", Message: "已清理测试记录"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return f.verifyResult, f.verifyErr
|
||||
@@ -175,6 +196,11 @@ func TestSetupDNSProviderCatalogAndOnlineTest(t *testing.T) {
|
||||
if strings.Contains(testResponse.Body.String(), "secret-token") {
|
||||
t.Fatal("DNS 在线测试响应不应返回明文凭据")
|
||||
}
|
||||
if !strings.Contains(testResponse.Body.String(), "test_report") ||
|
||||
!strings.Contains(testResponse.Body.String(), "创建记录") ||
|
||||
!strings.Contains(testResponse.Body.String(), "清理记录") {
|
||||
t.Fatalf("DNS 在线测试响应应包含阶段报告:%s", testResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
@@ -193,7 +219,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"admin_password":"secure1234",
|
||||
"server_port":8443,
|
||||
"email_provider":"mail-api",
|
||||
"email_endpoint":"https://mail.example.test/send",
|
||||
@@ -234,7 +260,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("读取保存后的配置失败:%v", err)
|
||||
}
|
||||
if strings.Contains(string(data), "secure-pass-123") {
|
||||
if strings.Contains(string(data), "secure1234") {
|
||||
t.Fatal("配置文件不应保存管理员明文密码")
|
||||
}
|
||||
var saved config.Config
|
||||
@@ -275,7 +301,7 @@ func TestSetupApplyEncryptsNotificationCredentialsAndPersistsReference(t *testin
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"admin_password":"secure1234",
|
||||
"server_port":8443,
|
||||
"email_http_enabled":true,
|
||||
"email_provider":"mail-api",
|
||||
@@ -368,7 +394,7 @@ func TestSetupApplyRejectsMissingNotificationCredentials(t *testing.T) {
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
"admin_email":"admin@example.test",
|
||||
"admin_password":"secure-pass-123",
|
||||
"admin_password":"secure1234",
|
||||
"server_port":8443,
|
||||
"email_http_enabled":true,
|
||||
"email_endpoint":"https://mail.example.test",
|
||||
@@ -483,7 +509,7 @@ func TestSetupSaveFailureDoesNotConsumeDNSToken(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -513,7 +539,7 @@ func TestSetupSaveFailureKeepsExistingFirewallRule(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: &fakeSetupDNSVerifier{}, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -536,7 +562,7 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -552,6 +578,48 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupLateFailureDeletesNewNotificationCredentials(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
blockedParent := filepath.Join(baseDir, "blocked")
|
||||
if err := os.WriteFile(blockedParent, []byte("blocked"), 0o600); err != nil {
|
||||
t.Fatalf("create blocked path: %v", err)
|
||||
}
|
||||
secrets := &fakeSetupSecretWriter{}
|
||||
firewallManager := &fakeFirewallManager{result: firewall.Result{
|
||||
Backend: "ufw", RuleName: "Scert Web TCP 8443", Port: 8443, Created: true,
|
||||
}}
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: filepath.Join(blockedParent, "scert.json"),
|
||||
Repository: &stubDomainRepository{}, SetupDNS: &fakeSetupDNSVerifier{}, Secrets: secrets,
|
||||
Firewall: firewallManager, IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure1234"),
|
||||
`"server_port":8443,`,
|
||||
`"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":"http-secret"},
|
||||
"email_smtp_enabled":true,
|
||||
"email_smtp_host":"smtp.example.test",
|
||||
"email_smtp_port":587,
|
||||
"email_smtp_username":"smtp-user",
|
||||
"email_smtp_password":"smtp-secret",
|
||||
"email_smtp_mode":"starttls",`, 1)
|
||||
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.StatusInternalServerError {
|
||||
t.Fatalf("late setup failure should return 500: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if len(secrets.deleted) != 2 || len(secrets.values) != 0 {
|
||||
t.Fatalf("new notification credentials should be deleted: deleted=%v values=%v", secrets.deleted, secrets.values)
|
||||
}
|
||||
}
|
||||
|
||||
func setupPayload(baseDir, password string) string {
|
||||
return `{
|
||||
"admin_username":"root-admin",
|
||||
@@ -578,7 +646,7 @@ func TestSetupCertificateFailureDoesNotSaveOrConsumeDNSToken(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, errors.New("模拟证书申请失败")),
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -609,7 +677,7 @@ func TestSetupCertificateFileValidationDoesNotSaveOrConsumeDNSToken(t *testing.T
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: issuer,
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -634,7 +702,7 @@ func TestSetupWithPublicIPRejectsDNSAutomaticCertificate(t *testing.T) {
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure-pass-123"),
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure1234"),
|
||||
`"web_hostname":"scert.example.test",`,
|
||||
`"web_hostname":"","web_public_ip":"192.0.2.10",`, 1)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(payload))
|
||||
@@ -667,7 +735,7 @@ func TestSetupFirewallFailureRollsBackIssuedCertificate(t *testing.T) {
|
||||
return certificate.RollbackSavedResource(context.Background(), saved)
|
||||
},
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||
request.RemoteAddr = "127.0.0.1:53000"
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
Reference in new issue
Block a user