完善证书管理与邮件通知流程
This commit is contained in:
1 parent
c74372284a
commit
b2833b761d
60 files changed
+7340
-254
No files matched your search
@@ -47,7 +47,7 @@ func (s *Server) authLogin(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, authRequestBodyLimit)
|
||||
var request authLoginRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "\u767b\u5f55\u8bf7\u6c42\u53c2\u6570\u65e0\u6548", err)
|
||||
s.writeError(c, http.StatusBadRequest, "登录请求参数无效", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -55,13 +55,13 @@ func (s *Server) authLogin(c *gin.Context) {
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
if !cfg.SetupReady {
|
||||
s.writeError(c, http.StatusConflict, "\u8bf7\u5148\u5b8c\u6210\u521d\u59cb\u5316\u914d\u7f6e", nil)
|
||||
s.writeError(c, http.StatusConflict, "请先完成初始化配置", nil)
|
||||
return
|
||||
}
|
||||
|
||||
key := loginAttemptKey(c.Request, request.Identifier)
|
||||
if !s.allowLogin(key) {
|
||||
s.writeError(c, http.StatusTooManyRequests, "\u767b\u5f55\u5931\u8d25\u6b21\u6570\u8fc7\u591a\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5", nil)
|
||||
s.writeError(c, http.StatusTooManyRequests, "登录失败次数过多,请稍后再试", nil)
|
||||
return
|
||||
}
|
||||
account, err := auth.AuthenticateAdmin(
|
||||
@@ -73,15 +73,15 @@ func (s *Server) authLogin(c *gin.Context) {
|
||||
)
|
||||
if err != nil {
|
||||
s.recordLoginFailure(key)
|
||||
s.recordAuthAudit(c, "\u767b\u5f55\u5931\u8d25", "failed", "\u767b\u5f55\u51ed\u636e\u6821\u9a8c\u5931\u8d25")
|
||||
s.writeError(c, http.StatusUnauthorized, "\u8d26\u53f7\u6216\u5bc6\u7801\u9519\u8bef", nil)
|
||||
s.recordAuthAudit(c, "登录失败", "failed", "登录凭据校验失败")
|
||||
s.writeError(c, http.StatusUnauthorized, "账号或密码错误", nil)
|
||||
return
|
||||
}
|
||||
s.clearLoginFailures(key)
|
||||
|
||||
token, err := newAuthToken()
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "\u65e0\u6cd5\u521b\u5efa\u767b\u5f55\u4f1a\u8bdd\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5", err)
|
||||
s.writeError(c, http.StatusInternalServerError, "无法创建登录会话,请稍后重试", err)
|
||||
return
|
||||
}
|
||||
lifetime := authSessionLifetime
|
||||
@@ -98,7 +98,7 @@ func (s *Server) authLogin(c *gin.Context) {
|
||||
}
|
||||
s.authMu.Unlock()
|
||||
s.setAuthCookie(c, token, expiresAt)
|
||||
s.recordAuthAudit(c, "\u767b\u5f55\u6210\u529f", "success", "\u8d85\u7ea7\u7ba1\u7406\u5458\u767b\u5f55\u6210\u529f")
|
||||
s.recordAuthAudit(c, "登录成功", "success", "超级管理员登录成功")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authenticated": true,
|
||||
"account": account.Username,
|
||||
@@ -137,9 +137,9 @@ func (s *Server) authLogout(c *gin.Context) {
|
||||
}
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: authCookieName, Value: "", Path: "/", MaxAge: -1,
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: requestIsHTTPS(c.Request),
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.requestIsHTTPS(c.Request),
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{"authenticated": false, "message": "\u5df2\u9000\u51fa\u767b\u5f55"})
|
||||
c.JSON(http.StatusOK, gin.H{"authenticated": false, "message": "已退出登录"})
|
||||
}
|
||||
|
||||
func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
|
||||
@@ -167,7 +167,7 @@ func (s *Server) setAuthCookie(c *gin.Context, token string, expiresAt time.Time
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: authCookieName, Value: token, Path: "/",
|
||||
Expires: expiresAt, MaxAge: max(1, int(time.Until(expiresAt).Seconds())),
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: requestIsHTTPS(c.Request),
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.requestIsHTTPS(c.Request),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -216,7 +216,7 @@ func (s *Server) recordAuthAudit(c *gin.Context, action, status, message string)
|
||||
if err := s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: action, ResourceType: "auth", ResourceID: "login", Status: status, Message: message,
|
||||
}); err != nil && s.logger != nil {
|
||||
s.logger.Warn("\u4fdd\u5b58\u767b\u5f55\u5ba1\u8ba1\u65e5\u5fd7\u5931\u8d25", "error", err)
|
||||
s.logger.Warn("保存登录审计日志失败", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,11 +239,21 @@ func newAuthToken() (string, error) {
|
||||
return hex.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func requestIsHTTPS(request *http.Request) bool {
|
||||
func (s *Server) requestIsHTTPS(request *http.Request) bool {
|
||||
if request == nil {
|
||||
return false
|
||||
}
|
||||
return request.TLS != nil || strings.EqualFold(strings.TrimSpace(request.Header.Get("X-Forwarded-Proto")), "https")
|
||||
if request.TLS != nil {
|
||||
return true
|
||||
}
|
||||
s.configMu.RLock()
|
||||
proxyMode := s.config.Server.HTTPSMode == "proxy"
|
||||
s.configMu.RUnlock()
|
||||
if !proxyMode {
|
||||
return false
|
||||
}
|
||||
forwardedProto := strings.TrimSpace(strings.Split(request.Header.Get("X-Forwarded-Proto"), ",")[0])
|
||||
return strings.EqualFold(forwardedProto, "https")
|
||||
}
|
||||
|
||||
func max(left, right int) int {
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
const certificateUploadLimit = 20 << 20
|
||||
|
||||
type certificateReader interface {
|
||||
Current(context.Context, string) (certificate.IssueResult, error)
|
||||
ListVersions(context.Context, string) ([]certificate.SavedResource, error)
|
||||
}
|
||||
|
||||
type certificatePathRequest struct {
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
IssuerBundlePath string `json:"issuer_bundle_path"`
|
||||
}
|
||||
|
||||
func (s *Server) listCertificates(c *gin.Context) {
|
||||
if s.repository == nil || s.currentCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书管理接口尚未配置", errors.New("证书服务未配置"))
|
||||
return
|
||||
}
|
||||
items, err := s.repository.List(c.Request.Context())
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询域名证书失败", err)
|
||||
return
|
||||
}
|
||||
result := make([]gin.H, 0, len(items))
|
||||
for _, item := range items {
|
||||
entry := gin.H{"domain": item, "certificate": nil}
|
||||
current, currentErr := s.currentCertificate.Current(c.Request.Context(), item.ID)
|
||||
if currentErr == nil {
|
||||
entry["certificate"] = current
|
||||
} else {
|
||||
entry["certificate_error"] = currentErr.Error()
|
||||
}
|
||||
result = append(result, entry)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": result})
|
||||
}
|
||||
|
||||
func (s *Server) getCertificate(c *gin.Context) {
|
||||
if s.currentCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书管理接口尚未配置", errors.New("证书服务未配置"))
|
||||
return
|
||||
}
|
||||
result, err := s.currentCertificate.Current(c.Request.Context(), strings.TrimSpace(c.Param("id")))
|
||||
if err != nil {
|
||||
s.writeError(c, certificateErrorStatus(err), "读取当前证书失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (s *Server) listCertificateVersions(c *gin.Context) {
|
||||
if s.currentCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书管理接口尚未配置", errors.New("证书服务未配置"))
|
||||
return
|
||||
}
|
||||
items, err := s.currentCertificate.ListVersions(c.Request.Context(), strings.TrimSpace(c.Param("id")))
|
||||
if err != nil {
|
||||
s.writeError(c, certificateErrorStatus(err), "查询证书历史版本失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (s *Server) validateCertificate(c *gin.Context) {
|
||||
if s.currentCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书校验接口尚未配置", errors.New("证书服务未配置"))
|
||||
return
|
||||
}
|
||||
result, err := s.currentCertificate.Current(c.Request.Context(), strings.TrimSpace(c.Param("id")))
|
||||
if err != nil {
|
||||
s.writeError(c, certificateErrorStatus(err), "读取当前证书失败", err)
|
||||
return
|
||||
}
|
||||
validation, err := (certificate.LocalValidator{VerifyChain: true}).ValidateFiles(
|
||||
c.Request.Context(),
|
||||
result.Saved.CertificatePath,
|
||||
result.Saved.FullChainPath,
|
||||
result.Saved.PrivateKeyPath,
|
||||
result.Domains,
|
||||
)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusUnprocessableEntity, "证书校验失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"certificate": result, "validation": validation})
|
||||
}
|
||||
|
||||
func (s *Server) deployCertificateCurrent(c *gin.Context) {
|
||||
if s.deployCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书部署接口尚未配置", errors.New("证书部署流程未配置"))
|
||||
return
|
||||
}
|
||||
result, report, err := s.deployCertificate(c.Request.Context(), strings.TrimSpace(c.Param("id")))
|
||||
response := gin.H{"certificate": result, "deployment": report}
|
||||
if err != nil {
|
||||
response["error"] = err.Error()
|
||||
c.JSON(http.StatusBadGateway, response)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
func (s *Server) importCertificateFiles(c *gin.Context) {
|
||||
if s.importCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书导入接口尚未配置", errors.New("证书导入流程未配置"))
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, certificateUploadLimit)
|
||||
request, cleanup, err := parseCertificateImportRequest(c)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "证书上传参数无效", err)
|
||||
return
|
||||
}
|
||||
defer cleanup()
|
||||
result, report, err := s.importCertificate(c.Request.Context(), request)
|
||||
response := gin.H{"certificate": result, "deployment": report}
|
||||
if err != nil {
|
||||
response["error"] = err.Error()
|
||||
c.JSON(http.StatusBadGateway, response)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
func parseCertificateImportRequest(c *gin.Context) (certificate.ImportRequest, func(), error) {
|
||||
cleanup := func() {}
|
||||
contentType := c.GetHeader("Content-Type")
|
||||
if strings.HasPrefix(strings.ToLower(contentType), "multipart/form-data") {
|
||||
if err := c.Request.ParseMultipartForm(certificateUploadLimit); err != nil {
|
||||
return certificate.ImportRequest{}, cleanup, fmt.Errorf("解析上传表单失败:%w", err)
|
||||
}
|
||||
certificatePath, cleanCertificate, err := saveMultipartFile(c.Request.MultipartForm, "certificate")
|
||||
if err != nil {
|
||||
return certificate.ImportRequest{}, cleanup, err
|
||||
}
|
||||
privateKeyPath, cleanPrivateKey, err := saveMultipartFile(c.Request.MultipartForm, "private_key")
|
||||
if err != nil {
|
||||
cleanCertificate()
|
||||
return certificate.ImportRequest{}, cleanup, err
|
||||
}
|
||||
issuerPath, cleanIssuer, err := saveOptionalMultipartFile(c.Request.MultipartForm, "issuer_bundle")
|
||||
if err != nil {
|
||||
cleanCertificate()
|
||||
cleanPrivateKey()
|
||||
return certificate.ImportRequest{}, cleanup, err
|
||||
}
|
||||
cleanup = func() {
|
||||
cleanCertificate()
|
||||
cleanPrivateKey()
|
||||
cleanIssuer()
|
||||
}
|
||||
return certificate.ImportRequest{
|
||||
DomainID: c.Param("id"), Certificate: certificatePath, PrivateKey: privateKeyPath, IssuerBundle: issuerPath,
|
||||
}, cleanup, nil
|
||||
}
|
||||
var body certificatePathRequest
|
||||
if err := json.NewDecoder(c.Request.Body).Decode(&body); err != nil {
|
||||
return certificate.ImportRequest{}, cleanup, fmt.Errorf("读取证书路径失败:%w", err)
|
||||
}
|
||||
if strings.TrimSpace(body.CertificatePath) == "" {
|
||||
return certificate.ImportRequest{}, cleanup, errors.New("证书路径不能为空")
|
||||
}
|
||||
if strings.TrimSpace(body.PrivateKeyPath) == "" {
|
||||
return certificate.ImportRequest{}, cleanup, errors.New("私钥路径不能为空")
|
||||
}
|
||||
return certificate.ImportRequest{
|
||||
DomainID: c.Param("id"), Certificate: body.CertificatePath, PrivateKey: body.PrivateKeyPath, IssuerBundle: body.IssuerBundlePath,
|
||||
}, cleanup, nil
|
||||
}
|
||||
|
||||
func saveMultipartFile(form *multipart.Form, field string) (string, func(), error) {
|
||||
path, cleanup, err := saveOptionalMultipartFile(form, field)
|
||||
if err != nil {
|
||||
return "", cleanup, err
|
||||
}
|
||||
if path == "" {
|
||||
return "", cleanup, fmt.Errorf("缺少上传文件:%s", field)
|
||||
}
|
||||
return path, cleanup, nil
|
||||
}
|
||||
|
||||
func saveOptionalMultipartFile(form *multipart.Form, field string) (string, func(), error) {
|
||||
cleanup := func() {}
|
||||
if form == nil {
|
||||
return "", cleanup, errors.New("上传表单为空")
|
||||
}
|
||||
files := form.File[field]
|
||||
if len(files) == 0 {
|
||||
return "", cleanup, nil
|
||||
}
|
||||
file, err := files[0].Open()
|
||||
if err != nil {
|
||||
return "", cleanup, fmt.Errorf("打开上传文件失败:%w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
temporary, err := os.CreateTemp("", "scert-upload-*")
|
||||
if err != nil {
|
||||
return "", cleanup, fmt.Errorf("创建上传临时文件失败:%w", err)
|
||||
}
|
||||
path := temporary.Name()
|
||||
cleanup = func() { _ = os.Remove(path) }
|
||||
if err := temporary.Chmod(0600); err != nil {
|
||||
_ = temporary.Close()
|
||||
cleanup()
|
||||
return "", func() {}, fmt.Errorf("设置上传临时文件权限失败:%w", err)
|
||||
}
|
||||
written, err := io.CopyN(temporary, file, certificateUploadLimit+1)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
_ = temporary.Close()
|
||||
cleanup()
|
||||
return "", func() {}, fmt.Errorf("保存上传文件失败:%w", err)
|
||||
}
|
||||
if written > certificateUploadLimit {
|
||||
_ = temporary.Close()
|
||||
cleanup()
|
||||
return "", func() {}, fmt.Errorf("上传文件超过 %d MB 限制", certificateUploadLimit>>20)
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
cleanup()
|
||||
return "", func() {}, fmt.Errorf("关闭上传临时文件失败:%w", err)
|
||||
}
|
||||
return path, cleanup, nil
|
||||
}
|
||||
|
||||
func certificateErrorStatus(err error) int {
|
||||
if repository.IsNotFound(err) || errors.Is(err, os.ErrNotExist) {
|
||||
return http.StatusNotFound
|
||||
}
|
||||
return http.StatusUnprocessableEntity
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"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/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
type certificateReaderStub struct {
|
||||
result certificate.IssueResult
|
||||
versions []certificate.SavedResource
|
||||
err error
|
||||
}
|
||||
|
||||
func (s certificateReaderStub) Current(context.Context, string) (certificate.IssueResult, error) {
|
||||
return s.result, s.err
|
||||
}
|
||||
|
||||
func (s certificateReaderStub) ListVersions(context.Context, string) ([]certificate.SavedResource, error) {
|
||||
return s.versions, s.err
|
||||
}
|
||||
|
||||
func TestCertificateReadAPIs(t *testing.T) {
|
||||
expiresAt := time.Now().UTC().Add(90 * 24 * time.Hour)
|
||||
reader := certificateReaderStub{
|
||||
result: certificate.IssueResult{
|
||||
DomainID: "domain-1",
|
||||
Domains: []string{"example.com", "www.example.com"},
|
||||
Saved: certificate.SavedResource{
|
||||
Domain: "example.com",
|
||||
CertificateType: "san",
|
||||
Version: "20260827-120000.000000000",
|
||||
NotAfter: expiresAt,
|
||||
},
|
||||
},
|
||||
versions: []certificate.SavedResource{{Version: "20260827-120000.000000000"}},
|
||||
}
|
||||
repo := &stubDomainRepository{items: []domain.Domain{{ID: "domain-1", Name: "example.com", CertificateType: domain.CertificateSAN}}}
|
||||
server := New(Dependencies{Config: config.Default(t.TempDir()), Repository: repo, CurrentCertificate: reader})
|
||||
|
||||
list := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(list, httptest.NewRequest(http.MethodGet, "/api/v1/certificates", nil))
|
||||
if list.Code != http.StatusOK || !strings.Contains(list.Body.String(), "example.com") {
|
||||
t.Fatalf("证书列表响应错误:%d %s", list.Code, list.Body.String())
|
||||
}
|
||||
|
||||
detail := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(detail, httptest.NewRequest(http.MethodGet, "/api/v1/certificates/domain-1", nil))
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "20260827-120000.000000000") {
|
||||
t.Fatalf("证书详情响应错误:%d %s", detail.Code, detail.Body.String())
|
||||
}
|
||||
|
||||
versions := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(versions, httptest.NewRequest(http.MethodGet, "/api/v1/domains/domain-1/certificate/versions", nil))
|
||||
if versions.Code != http.StatusOK || !strings.Contains(versions.Body.String(), "20260827-120000.000000000") {
|
||||
t.Fatalf("证书历史版本响应错误:%d %s", versions.Code, versions.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateImportAPIAcceptsMultipartFiles(t *testing.T) {
|
||||
var received certificate.ImportRequest
|
||||
importer := func(_ context.Context, request certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error) {
|
||||
received = request
|
||||
certificateData, err := os.ReadFile(request.Certificate)
|
||||
if err != nil {
|
||||
return certificate.IssueResult{}, deployment.Report{}, err
|
||||
}
|
||||
privateKeyData, err := os.ReadFile(request.PrivateKey)
|
||||
if err != nil {
|
||||
return certificate.IssueResult{}, deployment.Report{}, err
|
||||
}
|
||||
if string(certificateData) != "certificate" || string(privateKeyData) != "private-key" {
|
||||
return certificate.IssueResult{}, deployment.Report{}, os.ErrInvalid
|
||||
}
|
||||
return certificate.IssueResult{DomainID: request.DomainID}, deployment.Report{Status: "success"}, nil
|
||||
}
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(t.TempDir()),
|
||||
Repository: &stubDomainRepository{},
|
||||
ImportCertificate: importer,
|
||||
})
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
certificatePart, err := writer.CreateFormFile("certificate", "cert.pem")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = certificatePart.Write([]byte("certificate"))
|
||||
privateKeyPart, err := writer.CreateFormFile("private_key", "key.pem")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = privateKeyPart.Write([]byte("private-key"))
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/import", body)
|
||||
request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || received.DomainID != "domain-1" {
|
||||
t.Fatalf("证书导入响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if _, err := os.Stat(received.Certificate); !os.IsNotExist(err) {
|
||||
t.Fatalf("证书上传临时文件未在请求结束后清理:%s", received.Certificate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateImportAPIRejectsMissingFiles(t *testing.T) {
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(t.TempDir()),
|
||||
Repository: &stubDomainRepository{},
|
||||
ImportCertificate: func(context.Context, certificate.ImportRequest) (certificate.IssueResult, deployment.Report, error) {
|
||||
return certificate.IssueResult{}, deployment.Report{}, nil
|
||||
},
|
||||
})
|
||||
body, _ := json.Marshal(certificatePathRequest{CertificatePath: "", PrivateKeyPath: ""})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/certificate/import", bytes.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("缺少证书路径应返回参数错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Scert-Request-ID"
|
||||
|
||||
func (s *Server) requestMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
requestID := strings.TrimSpace(c.GetHeader(requestIDHeader))
|
||||
if !validRequestID(requestID) {
|
||||
requestID = newRequestID()
|
||||
}
|
||||
c.Set("request_id", requestID)
|
||||
c.Header(requestIDHeader, requestID)
|
||||
started := time.Now()
|
||||
c.Next()
|
||||
if s.logger != nil {
|
||||
s.logger.Info("HTTP 请求完成",
|
||||
"request_id", requestID,
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"status", c.Writer.Status(),
|
||||
"duration_ms", time.Since(started).Milliseconds(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) requireAdmin(c *gin.Context) {
|
||||
s.configMu.RLock()
|
||||
setupReady := s.config.SetupReady
|
||||
s.configMu.RUnlock()
|
||||
if !setupReady {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if _, ok := s.currentAuthSession(c); !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "请先登录管理后台",
|
||||
"request_id": requestIDFromContext(c),
|
||||
})
|
||||
return
|
||||
}
|
||||
if !s.sameOriginForAPI(c.Request) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"error": "请求来源校验失败",
|
||||
"request_id": requestIDFromContext(c),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func (s *Server) sameOriginForAPI(request *http.Request) bool {
|
||||
if request == nil {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(request.Header.Get("Origin"))
|
||||
if origin == "" {
|
||||
origin = strings.TrimSpace(request.Header.Get("Referer"))
|
||||
}
|
||||
if origin == "" {
|
||||
return true
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" {
|
||||
return false
|
||||
}
|
||||
requestScheme := "http"
|
||||
if s.requestIsHTTPS(request) {
|
||||
requestScheme = "https"
|
||||
}
|
||||
return strings.EqualFold(parsed.Host, request.Host) && strings.EqualFold(parsed.Scheme, requestScheme)
|
||||
}
|
||||
|
||||
func requestIDFromContext(c *gin.Context) string {
|
||||
value, exists := c.Get("request_id")
|
||||
if !exists {
|
||||
return ""
|
||||
}
|
||||
requestID, _ := value.(string)
|
||||
return requestID
|
||||
}
|
||||
|
||||
func validRequestID(value string) bool {
|
||||
if len(value) < 8 || len(value) > 128 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if (char < 'a' || char > 'z') && (char < 'A' || char > 'Z') && (char < '0' || char > '9') && char != '-' && char != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
buffer := make([]byte, 16)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "scert-request"
|
||||
}
|
||||
return "scert-" + hex.EncodeToString(buffer)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestRequestMiddlewareAddsAndPreservesRequestID(t *testing.T) {
|
||||
server := New(Dependencies{Config: config.Default(t.TempDir()), Repository: &stubDomainRepository{}})
|
||||
|
||||
first := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
generated := first.Header().Get(requestIDHeader)
|
||||
if !validRequestID(generated) {
|
||||
t.Fatalf("请求 ID 未正确生成:%q", generated)
|
||||
}
|
||||
|
||||
secondRequest := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
secondRequest.Header.Set(requestIDHeader, "client-request-123")
|
||||
second := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(second, secondRequest)
|
||||
if actual := second.Header().Get(requestIDHeader); actual != "client-request-123" {
|
||||
t.Fatalf("请求 ID 未保留:%q", actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAPIRequiresAuthenticationAfterSetup(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.com"
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("Password123"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
cfg.Admin.PasswordHash = string(hash)
|
||||
|
||||
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/domains", nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("未登录访问管理接口应返回 401,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAPIAcceptsAuthenticatedSessionAndRejectsCrossOrigin(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.com"
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("Password123"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
cfg.Admin.PasswordHash = string(hash)
|
||||
repository := &stubDomainRepository{items: []domain.Domain{}}
|
||||
server := New(Dependencies{Config: cfg, Repository: repository})
|
||||
|
||||
loginBody := strings.NewReader(`{"identifier":"admin","password":"Password123"}`)
|
||||
loginRequest := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", loginBody)
|
||||
loginRequest.Header.Set("Content-Type", "application/json")
|
||||
loginResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(loginResponse, loginRequest)
|
||||
if loginResponse.Code != http.StatusOK {
|
||||
t.Fatalf("登录失败:%d %s", loginResponse.Code, loginResponse.Body.String())
|
||||
}
|
||||
cookie := loginResponse.Result().Cookies()
|
||||
if len(cookie) == 0 {
|
||||
t.Fatal("登录响应未返回会话 Cookie")
|
||||
}
|
||||
|
||||
authenticatedRequest := httptest.NewRequest(http.MethodGet, "/api/v1/domains", nil)
|
||||
authenticatedRequest.AddCookie(cookie[0])
|
||||
authenticatedResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(authenticatedResponse, authenticatedRequest)
|
||||
if authenticatedResponse.Code != http.StatusOK {
|
||||
t.Fatalf("登录后访问管理接口失败:%d %s", authenticatedResponse.Code, authenticatedResponse.Body.String())
|
||||
}
|
||||
|
||||
crossOriginRequest := httptest.NewRequest(http.MethodGet, "/api/v1/domains", nil)
|
||||
crossOriginRequest.AddCookie(cookie[0])
|
||||
crossOriginRequest.Host = "127.0.0.1:5200"
|
||||
crossOriginRequest.Header.Set("Origin", "https://malicious.example")
|
||||
crossOriginResponse := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(crossOriginResponse, crossOriginRequest)
|
||||
if crossOriginResponse.Code != http.StatusForbidden {
|
||||
t.Fatalf("跨来源管理请求应返回 403,实际为 %d:%s", crossOriginResponse.Code, crossOriginResponse.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/auth"
|
||||
)
|
||||
|
||||
const passwordResetResolveBodyLimit = 16 * 1024
|
||||
|
||||
type passwordResetResolveRequest struct {
|
||||
Identifier string `json:"identifier"`
|
||||
}
|
||||
|
||||
type passwordResetResolution struct {
|
||||
AccountType string `json:"account_type"`
|
||||
AccountLabel string `json:"account_label"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Action string `json:"action"`
|
||||
ResetPath string `json:"reset_path,omitempty"`
|
||||
}
|
||||
|
||||
// resolvePasswordResetAccount 根据账户标识返回对应的密码处理内容。
|
||||
func (s *Server) resolvePasswordResetAccount(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, passwordResetResolveBodyLimit)
|
||||
var request passwordResetResolveRequest
|
||||
decoder := json.NewDecoder(c.Request.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "账户信息格式无效"})
|
||||
return
|
||||
}
|
||||
|
||||
identifier, err := auth.NormalizeIdentifier(request.Identifier)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请输入有效的用户名或绑定邮箱"})
|
||||
return
|
||||
}
|
||||
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
if !cfg.SetupReady {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Scert 尚未完成初始化,暂不能处理密码重置"})
|
||||
return
|
||||
}
|
||||
|
||||
if auth.IsMatch(identifier, cfg.Admin.Username, cfg.Admin.Email) {
|
||||
c.JSON(http.StatusOK, passwordResetResolution{
|
||||
AccountType: "super_admin",
|
||||
AccountLabel: "超级管理员",
|
||||
Title: "超级管理员密码重置",
|
||||
Description: "已识别为超级管理员账户。超级管理员不能通过普通重置页面修改密码,请使用 Scert-admin 开启的一次性重置入口。",
|
||||
Action: "use_super_admin_entry",
|
||||
ResetPath: admin.ResetPath,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 未识别账户时不返回具体账户信息,避免通过重置入口枚举账户。
|
||||
c.JSON(http.StatusOK, passwordResetResolution{
|
||||
AccountType: "unknown",
|
||||
AccountLabel: "未识别账户",
|
||||
Title: "无法识别账户",
|
||||
Description: "未找到匹配的账户,请检查用户名或绑定邮箱;如果账户属于其他用户类型,请联系有权限的管理员处理。",
|
||||
Action: "check_identifier",
|
||||
})
|
||||
}
|
||||
@@ -83,7 +83,7 @@ func (s *Server) resetSubmit(c *gin.Context) {
|
||||
c.Status(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
if !sameOrigin(c.Request) {
|
||||
if !s.sameOrigin(c.Request) {
|
||||
s.resetLimiter.failed(ip, now)
|
||||
s.recordResetAudit(c, "rejected", "密码重置请求来源校验失败")
|
||||
s.writeResetFailure(c, http.StatusForbidden, "请求来源校验失败,请从重置页面重新提交")
|
||||
@@ -171,12 +171,12 @@ func (s *Server) resetSubmit(c *gin.Context) {
|
||||
s.renderResetSuccess(c, "密码重置成功,请停止 Scert-admin 以结束本次维护窗口")
|
||||
}
|
||||
|
||||
func sameOrigin(request *http.Request) bool {
|
||||
func (s *Server) sameOrigin(request *http.Request) bool {
|
||||
if request == nil || strings.TrimSpace(request.Host) == "" {
|
||||
return false
|
||||
}
|
||||
scheme := "http"
|
||||
if request.TLS != nil {
|
||||
if s.requestIsHTTPS(request) {
|
||||
scheme = "https"
|
||||
}
|
||||
origin := strings.TrimSpace(request.Header.Get("Origin"))
|
||||
|
||||
@@ -3,8 +3,11 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -25,42 +28,54 @@ import (
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
Servers repository.ServerRepository
|
||||
SSHKeys *sshkey.Service
|
||||
SetupDNS setupDNSVerifier
|
||||
Firewall firewall.Manager
|
||||
IssueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
ResetStatePath string
|
||||
Audit repository.AuditRepository
|
||||
Config config.Config
|
||||
ConfigPath string
|
||||
Logger *logging.Logger
|
||||
Repository repository.DomainRepository
|
||||
Servers repository.ServerRepository
|
||||
SSHKeys *sshkey.Service
|
||||
SetupDNS setupDNSVerifier
|
||||
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
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
configMu sync.RWMutex
|
||||
config config.Config
|
||||
configPath string
|
||||
logger *logging.Logger
|
||||
repository repository.DomainRepository
|
||||
servers repository.ServerRepository
|
||||
sshKeys *sshkey.Service
|
||||
setupDNS setupDNSVerifier
|
||||
firewall firewall.Manager
|
||||
issueCertificate func(context.Context, string) (certificate.IssueResult, deployment.Report, error)
|
||||
resetStatePath string
|
||||
audit repository.AuditRepository
|
||||
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
|
||||
configMu sync.RWMutex
|
||||
config config.Config
|
||||
configPath string
|
||||
logger *logging.Logger
|
||||
repository repository.DomainRepository
|
||||
servers repository.ServerRepository
|
||||
sshKeys *sshkey.Service
|
||||
setupDNS setupDNSVerifier
|
||||
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
|
||||
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 {
|
||||
@@ -70,16 +85,23 @@ func New(deps Dependencies) *Server {
|
||||
server := &Server{
|
||||
config: deps.Config, configPath: deps.ConfigPath, logger: deps.Logger,
|
||||
repository: deps.Repository, setupDNS: deps.SetupDNS, firewall: deps.Firewall, router: router,
|
||||
servers: deps.Servers,
|
||||
sshKeys: deps.SSHKeys,
|
||||
issueCertificate: deps.IssueCertificate,
|
||||
resetStatePath: deps.ResetStatePath,
|
||||
audit: deps.Audit,
|
||||
resetLimiter: newResetRateLimiter(),
|
||||
authSessions: make(map[string]authSession),
|
||||
loginAttempts: make(map[string]loginAttempt),
|
||||
now: time.Now,
|
||||
servers: deps.Servers,
|
||||
sshKeys: deps.SSHKeys,
|
||||
issueCertificate: deps.IssueCertificate,
|
||||
issueSetupCertificate: deps.IssueSetupCertificate,
|
||||
rollbackSetupCertificate: deps.RollbackSetupCertificate,
|
||||
importCertificate: deps.ImportCertificate,
|
||||
deployCertificate: deps.DeployCertificate,
|
||||
currentCertificate: deps.CurrentCertificate,
|
||||
resetStatePath: deps.ResetStatePath,
|
||||
audit: deps.Audit,
|
||||
tasks: deps.Tasks,
|
||||
resetLimiter: newResetRateLimiter(),
|
||||
authSessions: make(map[string]authSession),
|
||||
loginAttempts: make(map[string]loginAttempt),
|
||||
now: time.Now,
|
||||
}
|
||||
router.Use(server.requestMiddleware())
|
||||
server.registerRoutes()
|
||||
server.registerSetupRoutes()
|
||||
return server
|
||||
@@ -94,21 +116,33 @@ func (s *Server) registerRoutes() {
|
||||
s.router.GET("/api/v1/auth/session", s.authSession)
|
||||
s.router.POST("/api/v1/auth/login", s.authLogin)
|
||||
s.router.POST("/api/v1/auth/logout", s.authLogout)
|
||||
s.router.GET("/api/v1/domains", s.listDomains)
|
||||
s.router.POST("/api/v1/domains", s.createDomain)
|
||||
s.router.PUT("/api/v1/domains/:id", s.updateDomain)
|
||||
s.router.DELETE("/api/v1/domains/:id", s.deleteDomain)
|
||||
s.router.POST("/api/v1/domains/:id/issue", s.issueDomain)
|
||||
s.router.GET("/api/v1/domains/:id/servers", s.listDomainServers)
|
||||
s.router.PUT("/api/v1/domains/:id/servers", s.replaceDomainServers)
|
||||
s.router.GET("/api/v1/servers", s.listServers)
|
||||
s.router.POST("/api/v1/servers", s.createServer)
|
||||
s.router.GET("/api/v1/servers/:id", s.getServer)
|
||||
s.router.PUT("/api/v1/servers/:id", s.updateServer)
|
||||
s.router.DELETE("/api/v1/servers/:id", s.deleteServer)
|
||||
s.router.GET("/api/v1/ssh-keys", s.listSSHKeys)
|
||||
s.router.POST("/api/v1/ssh-keys", s.createSSHKey)
|
||||
s.router.DELETE("/api/v1/ssh-keys/:id", s.deleteSSHKey)
|
||||
s.router.POST("/api/v1/password-reset/resolve", s.resolvePasswordResetAccount)
|
||||
adminAPI := s.router.Group("/api/v1", s.requireAdmin)
|
||||
adminAPI.GET("/domains", s.listDomains)
|
||||
adminAPI.POST("/domains", s.createDomain)
|
||||
adminAPI.PUT("/domains/:id", s.updateDomain)
|
||||
adminAPI.DELETE("/domains/:id", s.deleteDomain)
|
||||
adminAPI.POST("/domains/:id/issue", s.issueDomain)
|
||||
adminAPI.GET("/tasks", s.listTasks)
|
||||
adminAPI.GET("/tasks/:id", s.getTask)
|
||||
adminAPI.GET("/tasks/:id/attempts", s.listTaskAttempts)
|
||||
adminAPI.GET("/audit-logs", s.listAuditLogs)
|
||||
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.GET("/domains/:id/servers", s.listDomainServers)
|
||||
adminAPI.PUT("/domains/:id/servers", s.replaceDomainServers)
|
||||
adminAPI.GET("/servers", s.listServers)
|
||||
adminAPI.POST("/servers", s.createServer)
|
||||
adminAPI.GET("/servers/:id", s.getServer)
|
||||
adminAPI.PUT("/servers/:id", s.updateServer)
|
||||
adminAPI.DELETE("/servers/:id", s.deleteServer)
|
||||
adminAPI.GET("/ssh-keys", s.listSSHKeys)
|
||||
adminAPI.POST("/ssh-keys", s.createSSHKey)
|
||||
adminAPI.DELETE("/ssh-keys/:id", s.deleteSSHKey)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
@@ -119,18 +153,64 @@ func (s *Server) ListenAndServe() error {
|
||||
s.configMu.RLock()
|
||||
cfg := s.config
|
||||
s.configMu.RUnlock()
|
||||
address, err := listenAddress(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.httpServer = &http.Server{
|
||||
Addr: net.JoinHostPort(cfg.Server.Host, strconv.Itoa(cfg.Server.Port)),
|
||||
Addr: address,
|
||||
Handler: s.router,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
if s.logger != nil {
|
||||
s.logger.Info("HTTP 服务启动", "address", s.httpServer.Addr, "https_mode", cfg.Server.HTTPSMode)
|
||||
if !cfg.SetupReady {
|
||||
if s.logger != nil {
|
||||
s.logger.Info("HTTP 服务启动", "address", s.httpServer.Addr, "https_mode", "初始化明文 HTTP")
|
||||
}
|
||||
return s.httpServer.ListenAndServe()
|
||||
}
|
||||
return s.httpServer.ListenAndServe()
|
||||
certPath := strings.TrimSpace(cfg.Server.TLSCert)
|
||||
keyPath := strings.TrimSpace(cfg.Server.TLSKey)
|
||||
if certPath == "" || keyPath == "" {
|
||||
return fmt.Errorf("初始化已完成,但 HTTPS 证书或私钥路径未配置")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Clean(certPath)); err != nil {
|
||||
return fmt.Errorf("读取 HTTPS 证书失败:%w", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Clean(keyPath)); err != nil {
|
||||
return fmt.Errorf("读取 HTTPS 私钥失败:%w", err)
|
||||
}
|
||||
if s.logger != nil {
|
||||
s.logger.Info("HTTPS 服务启动", "address", s.httpServer.Addr, "https_mode", cfg.Server.HTTPSMode)
|
||||
}
|
||||
return s.httpServer.ListenAndServeTLS(certPath, keyPath)
|
||||
}
|
||||
|
||||
// listenAddress 返回当前 HTTPS 模式实际使用的监听地址。
|
||||
// 高级模式的核心服务只允许通过本机回环地址提供内部 HTTPS,避免误绑定到公网网卡。
|
||||
func listenAddress(cfg config.Config) (string, error) {
|
||||
host := strings.TrimSpace(cfg.Server.Host)
|
||||
if host == "" {
|
||||
return "", fmt.Errorf("服务监听地址不能为空")
|
||||
}
|
||||
if cfg.Server.Port < 1 || cfg.Server.Port > 65535 {
|
||||
return "", fmt.Errorf("服务监听端口无效:%d", cfg.Server.Port)
|
||||
}
|
||||
if cfg.Server.HTTPSMode == "proxy" && !isLoopbackHost(host) {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
return net.JoinHostPort(strings.Trim(host, "[]"), strconv.Itoa(cfg.Server.Port)), nil
|
||||
}
|
||||
|
||||
func isLoopbackHost(host string) bool {
|
||||
host = strings.Trim(strings.TrimSpace(host), "[]")
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
@@ -302,6 +382,10 @@ func (s *Server) deleteDomain(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (s *Server) issueDomain(c *gin.Context) {
|
||||
if s.tasks != nil {
|
||||
s.issueDomainAsTask(c)
|
||||
return
|
||||
}
|
||||
if s.issueCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书申请接口尚未配置", errors.New("证书申请工作流未配置"))
|
||||
return
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/logging"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
|
||||
@@ -471,3 +472,96 @@ func resetForm(code, csrfToken, password string) url.Values {
|
||||
"confirm_password": {password},
|
||||
}
|
||||
}
|
||||
|
||||
func TestListenAddressKeepsDirectModeBinding(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Server.Host = "0.0.0.0"
|
||||
cfg.Server.Port = 5200
|
||||
cfg.Server.HTTPSMode = "direct"
|
||||
address, err := listenAddress(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("直接 HTTPS 模式监听地址生成失败:%v", err)
|
||||
}
|
||||
if address != "0.0.0.0:5200" {
|
||||
t.Fatalf("直接 HTTPS 模式应保留配置监听地址:%s", address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListenAddressRestrictsProxyModeToLoopback(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Server.Host = "0.0.0.0"
|
||||
cfg.Server.Port = 5201
|
||||
cfg.Server.HTTPSMode = "proxy"
|
||||
address, err := listenAddress(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("高级 HTTPS 模式监听地址生成失败:%v", err)
|
||||
}
|
||||
if address != "127.0.0.1:5201" {
|
||||
t.Fatalf("高级 HTTPS 模式必须绑定本机回环地址:%s", address)
|
||||
}
|
||||
|
||||
cfg.Server.Host = "192.168.2.3"
|
||||
address, err = listenAddress(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("高级 HTTPS 模式公网地址校正失败:%v", err)
|
||||
}
|
||||
if address != "127.0.0.1:5201" {
|
||||
t.Fatalf("高级 HTTPS 模式不得绑定局域网地址:%s", address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListenAddressAllowsLoopbackProxyBinding(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.Server.Host = "[::1]"
|
||||
cfg.Server.Port = 5202
|
||||
cfg.Server.HTTPSMode = "proxy"
|
||||
address, err := listenAddress(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("回环 HTTPS 模式监听地址生成失败:%v", err)
|
||||
}
|
||||
if address != "[::1]:5202" {
|
||||
t.Fatalf("已配置 IPv6 回环地址时不应被替换:%s", address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardedHTTPSIsTrustedOnlyInProxyMode(t *testing.T) {
|
||||
direct := config.Default(t.TempDir())
|
||||
direct.Server.HTTPSMode = "direct"
|
||||
directServer := New(Dependencies{Config: direct, Repository: &stubDomainRepository{}})
|
||||
directRequest := httptest.NewRequest(http.MethodGet, "http://scert.example.test/healthz", nil)
|
||||
directRequest.Header.Set("X-Forwarded-Proto", "https")
|
||||
if directServer.requestIsHTTPS(directRequest) {
|
||||
t.Fatal("直接 HTTPS 模式不应信任外部伪造的 X-Forwarded-Proto")
|
||||
}
|
||||
|
||||
proxy := config.Default(t.TempDir())
|
||||
proxy.Server.HTTPSMode = "proxy"
|
||||
proxyServer := New(Dependencies{Config: proxy, Repository: &stubDomainRepository{}})
|
||||
proxyRequest := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:5200/healthz", nil)
|
||||
proxyRequest.Header.Set("X-Forwarded-Proto", "https, http")
|
||||
if !proxyServer.requestIsHTTPS(proxyRequest) {
|
||||
t.Fatal("高级 HTTPS 模式应识别可信反向代理传入的 HTTPS 协议")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyModeAcceptsHTTPSSameOrigin(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir())
|
||||
cfg.SetupReady = true
|
||||
cfg.Server.HTTPSMode = "proxy"
|
||||
cfg.Admin.Username = "admin"
|
||||
cfg.Admin.Email = "admin@example.com"
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("Password123"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||
}
|
||||
cfg.Admin.PasswordHash = string(hash)
|
||||
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{items: []domain.Domain{}}})
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:5200/api/v1/domains", nil)
|
||||
request.Host = "scert.example.test"
|
||||
request.Header.Set("Origin", "https://scert.example.test")
|
||||
request.Header.Set("X-Forwarded-Proto", "https")
|
||||
if !server.sameOriginForAPI(request) {
|
||||
t.Fatal("高级 HTTPS 模式应接受反向代理后的同源 HTTPS 请求")
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,13 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/setup"
|
||||
@@ -25,22 +27,37 @@ 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"`
|
||||
EmailProvider string `json:"email_provider"`
|
||||
EmailEndpoint string `json:"email_endpoint"`
|
||||
Recipients []string `json:"recipients"`
|
||||
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"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type dnsTestRequest struct {
|
||||
@@ -169,23 +186,42 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
if request.WebEnabled != nil {
|
||||
webEnabled = *request.WebEnabled
|
||||
}
|
||||
emailHTTPEnabled := false
|
||||
if request.EmailHTTPEnabled != nil {
|
||||
emailHTTPEnabled = *request.EmailHTTPEnabled
|
||||
}
|
||||
updated := s.config
|
||||
err := setup.Apply(&updated, setup.Input{
|
||||
AdminUsername: request.AdminUsername,
|
||||
AdminEmail: request.AdminEmail,
|
||||
AdminPassword: request.AdminPassword,
|
||||
ServerPort: request.ServerPort,
|
||||
EmailProvider: request.EmailProvider,
|
||||
EmailEndpoint: request.EmailEndpoint,
|
||||
EmailRecipients: request.Recipients,
|
||||
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: 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,
|
||||
})
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||
@@ -195,6 +231,48 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
s.writeError(c, http.StatusInternalServerError, "服务未配置配置文件路径,无法保存初始化结果", nil)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(updated.Web.PublicIP) != "" {
|
||||
s.writeError(c, http.StatusBadRequest, "公网 IP 暂不支持通过 DNS-01 自动申请管理后台证书,请先配置域名或上传自有证书", nil)
|
||||
return
|
||||
}
|
||||
if s.issueSetupCertificate == nil {
|
||||
s.writeError(c, http.StatusServiceUnavailable, "初始化证书申请服务尚未配置", nil)
|
||||
return
|
||||
}
|
||||
updated.SetupReady = false
|
||||
certificateContext, certificateCancel := context.WithTimeout(c.Request.Context(), 10*time.Minute)
|
||||
savedCertificate, certificateErr := s.issueSetupCertificate(certificateContext, certificate.SetupCertificateRequest{
|
||||
Domains: []string{updated.Web.Hostname},
|
||||
CertificateType: "single",
|
||||
ProviderID: updated.DNS.Provider,
|
||||
CredentialRef: updated.DNS.CredentialRef,
|
||||
AccountEmail: updated.Admin.Email,
|
||||
Environment: updated.ACME.Environment,
|
||||
CertificateRoot: updated.Paths.Certificate,
|
||||
BackupRoot: updated.Paths.Backup,
|
||||
})
|
||||
certificateCancel()
|
||||
if certificateErr != nil {
|
||||
s.writeError(c, http.StatusBadGateway, "申请管理后台证书失败,初始化尚未完成", certificateErr)
|
||||
return
|
||||
}
|
||||
if err := validateSetupCertificateFiles(savedCertificate); err != nil {
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("管理后台证书文件校验失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "管理后台证书文件校验失败:初始化尚未完成", err)
|
||||
return
|
||||
}
|
||||
updated.Server.TLSCert = savedCertificate.FullChainPath
|
||||
updated.Server.TLSKey = savedCertificate.PrivateKeyPath
|
||||
updated.SetupReady = true
|
||||
if err := updated.Validate(); err != nil {
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("初始化证书配置无效,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "初始化证书配置无效:初始化尚未完成", err)
|
||||
return
|
||||
}
|
||||
firewallResult := firewall.Result{
|
||||
Backend: firewall.BackendNone, Port: updated.Server.Port,
|
||||
Message: "未配置防火墙管理器,已跳过本机规则创建",
|
||||
@@ -204,23 +282,35 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
firewallResult, err = s.firewall.OpenTCP(firewallContext, updated.Server.Port)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if rollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate); rollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("自动配置本机防火墙失败,且证书回滚失败", "error", rollbackErr)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "自动配置本机防火墙失败,请使用管理员权限重新运行初始化程序", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := updated.Save(s.configPath); err != nil {
|
||||
firewallRollbackErr := error(nil)
|
||||
if firewallResult.Created && s.firewall != nil {
|
||||
rollbackContext, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
rollbackErr := s.firewall.Rollback(rollbackContext, firewallResult)
|
||||
firewallRollbackErr = s.firewall.Rollback(rollbackContext, firewallResult)
|
||||
cancel()
|
||||
if rollbackErr != nil {
|
||||
if s.logger != nil {
|
||||
s.logger.Error("保存初始化配置失败,且回滚本机防火墙规则失败", "error", rollbackErr, "rule", firewallResult.RuleName)
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败,且自动创建的防火墙规则回滚失败,请手动检查本机防火墙", err)
|
||||
return
|
||||
if firewallRollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存初始化配置失败,且回滚本机防火墙规则失败", "error", firewallRollbackErr, "rule", firewallResult.RuleName)
|
||||
}
|
||||
}
|
||||
certificateRollbackErr := s.rollbackIssuedSetupCertificate(savedCertificate)
|
||||
if certificateRollbackErr != nil && s.logger != nil {
|
||||
s.logger.Error("保存初始化配置失败,且初始化证书回滚失败", "error", certificateRollbackErr)
|
||||
}
|
||||
if firewallRollbackErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败,且自动创建的防火墙规则回滚失败,请手动检查本机防火墙", err)
|
||||
return
|
||||
}
|
||||
if certificateRollbackErr != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败,且管理后台证书回滚失败,请手动检查证书目录", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败", err)
|
||||
return
|
||||
}
|
||||
@@ -231,7 +321,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"initialized": true,
|
||||
"message": fmt.Sprintf(
|
||||
"初始化配置已保存,DNS API 已完成在线验证且凭据已加密保存。%s。请确认云安全组已放行主服务端口 %d;Scert-admin 默认关闭,启动后通过 %s 使用临时重置入口。证书申请和 HTTPS 切换将在后续任务中完成。",
|
||||
"初始化配置已保存,DNS API 已完成在线验证且凭据已加密保存。%s。请确认云安全组已放行主服务端口 %d;Scert-admin 默认关闭,启动后通过 %s 使用临时重置入口。管理后台证书申请成功。",
|
||||
firewallResult.Message, updated.Server.Port, updated.ResetURL(),
|
||||
),
|
||||
"status": gin.H{
|
||||
@@ -244,6 +334,33 @@ func (s *Server) applySetup(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) rollbackIssuedSetupCertificate(saved certificate.SavedResource) error {
|
||||
if s.rollbackSetupCertificate == nil {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
return s.rollbackSetupCertificate(ctx, saved)
|
||||
}
|
||||
func validateSetupCertificateFiles(saved certificate.SavedResource) error {
|
||||
for label, path := range map[string]string{
|
||||
"完整证书链": saved.FullChainPath,
|
||||
"私钥": saved.PrivateKeyPath,
|
||||
} {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return fmt.Errorf("%s路径为空", label)
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取%s失败:%w", label, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("%s不是普通文件", label)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) allowSetupRequest(c *gin.Context) bool {
|
||||
s.configMu.RLock()
|
||||
initialized := s.config.SetupReady
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"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/dnsprovider"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
|
||||
@@ -35,6 +36,31 @@ type fakeFirewallManager struct {
|
||||
rollbackCall bool
|
||||
}
|
||||
|
||||
type setupCertificateIssuer func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error)
|
||||
|
||||
func newSetupCertificateIssuer(t *testing.T, baseDir string, issueErr error) setupCertificateIssuer {
|
||||
t.Helper()
|
||||
if issueErr != nil {
|
||||
return func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
|
||||
return certificate.SavedResource{}, issueErr
|
||||
}
|
||||
}
|
||||
fullChainPath := filepath.Join(baseDir, "fullchain.pem")
|
||||
privateKeyPath := filepath.Join(baseDir, "key.pem")
|
||||
if err := os.WriteFile(fullChainPath, []byte("test certificate"), 0o644); err != nil {
|
||||
t.Fatalf("创建测试文件失败:%v", err)
|
||||
}
|
||||
if err := os.WriteFile(privateKeyPath, []byte("test private key"), 0o600); err != nil {
|
||||
t.Fatalf("创建测试文件失败:%v", err)
|
||||
}
|
||||
return func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
|
||||
return certificate.SavedResource{
|
||||
FullChainPath: fullChainPath,
|
||||
PrivateKeyPath: privateKeyPath,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeFirewallManager) OpenTCP(_ context.Context, port int) (firewall.Result, error) {
|
||||
f.openedPort = port
|
||||
if f.result.Port == 0 {
|
||||
@@ -146,6 +172,7 @@ func TestSetupApplyPersistsConfigurationWithoutPlainPassword(t *testing.T) {
|
||||
server := New(Dependencies{
|
||||
Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{},
|
||||
SetupDNS: verifier, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := `{
|
||||
"admin_username":"root-admin",
|
||||
@@ -317,6 +344,7 @@ func TestSetupSaveFailureDoesNotConsumeDNSToken(t *testing.T) {
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: filepath.Join(blockedParent, "scert.json"),
|
||||
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.RemoteAddr = "127.0.0.1:53000"
|
||||
@@ -346,6 +374,7 @@ func TestSetupSaveFailureKeepsExistingFirewallRule(t *testing.T) {
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: filepath.Join(blockedParent, "scert.json"),
|
||||
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.RemoteAddr = "127.0.0.1:53000"
|
||||
@@ -368,6 +397,7 @@ func TestSetupFirewallFailureDoesNotSaveOrConsumeToken(t *testing.T) {
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: configPath,
|
||||
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.RemoteAddr = "127.0.0.1:53000"
|
||||
@@ -401,3 +431,114 @@ func setupPayload(baseDir, password string) string {
|
||||
"https_mode":"direct"
|
||||
}`
|
||||
}
|
||||
|
||||
func TestSetupCertificateFailureDoesNotSaveOrConsumeDNSToken(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
configPath := filepath.Join(baseDir, "config", "scert.json")
|
||||
verifier := &fakeSetupDNSVerifier{}
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: configPath,
|
||||
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.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.StatusBadGateway || !strings.Contains(response.Body.String(), "申请管理后台证书失败") {
|
||||
t.Fatalf("证书申请失败应返回明确错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if !verifier.checked || verifier.consumed {
|
||||
t.Fatalf("证书申请失败时应检查但不消费 DNS 令牌:checked=%t consumed=%t", verifier.checked, verifier.consumed)
|
||||
}
|
||||
if _, err := os.Stat(configPath); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("证书申请失败时不得保存初始化配置:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupCertificateFileValidationDoesNotSaveOrConsumeDNSToken(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
configPath := filepath.Join(baseDir, "config", "scert.json")
|
||||
verifier := &fakeSetupDNSVerifier{}
|
||||
issuer := func(context.Context, certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
|
||||
return certificate.SavedResource{
|
||||
FullChainPath: filepath.Join(baseDir, "missing-fullchain.pem"),
|
||||
PrivateKeyPath: filepath.Join(baseDir, "missing-key.pem"),
|
||||
}, nil
|
||||
}
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: configPath,
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: issuer,
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
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 || !strings.Contains(response.Body.String(), "管理后台证书文件校验失败") {
|
||||
t.Fatalf("证书文件校验失败应返回明确错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if verifier.consumed {
|
||||
t.Fatal("证书文件校验失败时不得消费 DNS 令牌")
|
||||
}
|
||||
if _, err := os.Stat(configPath); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("证书文件校验失败时不得保存初始化配置:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupWithPublicIPRejectsDNSAutomaticCertificate(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
configPath := filepath.Join(baseDir, "config", "scert.json")
|
||||
verifier := &fakeSetupDNSVerifier{}
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: configPath,
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
})
|
||||
payload := strings.Replace(setupPayload(baseDir, "secure-pass-123"),
|
||||
`"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))
|
||||
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(), "公网 IP 暂不支持") {
|
||||
t.Fatalf("公网 IP 自动申请应被拒绝:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if verifier.consumed {
|
||||
t.Fatal("公网 IP 场景不得消费 DNS 令牌")
|
||||
}
|
||||
if _, err := os.Stat(configPath); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("公网 IP 场景不得保存初始化配置:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupFirewallFailureRollsBackIssuedCertificate(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
verifier := &fakeSetupDNSVerifier{}
|
||||
firewallManager := &fakeFirewallManager{openErr: errors.New("access denied")}
|
||||
rolledBack := false
|
||||
server := New(Dependencies{
|
||||
Config: config.Default(baseDir), ConfigPath: filepath.Join(baseDir, "config", "scert.json"),
|
||||
Repository: &stubDomainRepository{}, SetupDNS: verifier, Firewall: firewallManager,
|
||||
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, nil),
|
||||
RollbackSetupCertificate: func(_ context.Context, saved certificate.SavedResource) error {
|
||||
rolledBack = true
|
||||
return certificate.RollbackSavedResource(context.Background(), saved)
|
||||
},
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure-pass-123")))
|
||||
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("防火墙失败应返回服务器错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
if !rolledBack {
|
||||
t.Fatal("防火墙配置失败时应回滚已保存的初始化证书")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
if s.issueCertificate == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "证书申请接口尚未配置", errors.New("证书申请工作流未配置"))
|
||||
return
|
||||
}
|
||||
domainID := strings.TrimSpace(c.Param("id"))
|
||||
if _, err := s.repository.GetByID(c.Request.Context(), domainID); err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "域名不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取域名失败", err)
|
||||
return
|
||||
}
|
||||
if active, err := s.tasks.FindActiveTaskByDomain(c.Request.Context(), domainID, "certificate_issue"); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "该域名已有正在执行的证书任务", "task": active})
|
||||
return
|
||||
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||
s.writeError(c, http.StatusInternalServerError, "检查正在执行的任务失败", err)
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
task := repository.Task{
|
||||
ID: domain.NewID(),
|
||||
DomainID: domainID,
|
||||
TaskType: "certificate_issue",
|
||||
Status: "queued",
|
||||
Stage: "queued",
|
||||
Message: "等待执行证书申请",
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := s.tasks.CreateTask(c.Request.Context(), task); err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "创建证书任务失败", err)
|
||||
return
|
||||
}
|
||||
attempt := repository.TaskAttempt{
|
||||
ID: domain.NewID(),
|
||||
TaskID: task.ID,
|
||||
AttemptNumber: 1,
|
||||
Stage: "certificate_issue",
|
||||
Status: "running",
|
||||
Message: "开始申请证书",
|
||||
StartedAt: &now,
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.tasks.CreateAttempt(c.Request.Context(), attempt); err != nil {
|
||||
_ = s.tasks.UpdateTask(context.Background(), task.ID, "failed", "certificate_issue", "创建任务尝试失败", &now, &now)
|
||||
s.writeError(c, http.StatusInternalServerError, "创建任务尝试失败", err)
|
||||
return
|
||||
}
|
||||
if err := s.tasks.UpdateTask(c.Request.Context(), task.ID, "running", "certificate_issue", "正在申请证书并部署", &now, nil); err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "更新任务状态失败", err)
|
||||
return
|
||||
}
|
||||
certificateResult, deploymentReport, issueErr := s.issueCertificate(c.Request.Context(), domainID)
|
||||
finished := time.Now().UTC()
|
||||
status := "success"
|
||||
message := "证书申请和部署完成"
|
||||
if issueErr != nil {
|
||||
status = "failed"
|
||||
message = issueErr.Error()
|
||||
}
|
||||
_ = s.tasks.UpdateTask(context.Background(), task.ID, status, "certificate_issue", message, &now, &finished)
|
||||
_ = s.tasks.FinishAttempt(context.Background(), attempt.ID, status, message, &finished)
|
||||
if s.audit != nil {
|
||||
auditStatus := status
|
||||
if issueErr != nil {
|
||||
auditStatus = "error"
|
||||
}
|
||||
_ = s.audit.CreateAuditLog(context.Background(), repository.AuditLog{
|
||||
Action: "certificate_issue",
|
||||
ResourceType: "domain",
|
||||
ResourceID: domainID,
|
||||
Status: auditStatus,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
response := gin.H{
|
||||
"task": task,
|
||||
"certificate": certificateResult,
|
||||
"deployment": deploymentReport,
|
||||
"task_status": status,
|
||||
"finished_at": finished,
|
||||
}
|
||||
if issueErr != nil {
|
||||
response["error"] = issueErr.Error()
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *Server) listTasks(c *gin.Context) {
|
||||
if s.tasks == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "任务管理接口尚未配置", errors.New("任务仓储未配置"))
|
||||
return
|
||||
}
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
|
||||
items, err := s.tasks.ListTasks(c.Request.Context(), c.Query("domain_id"), limit)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询任务失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (s *Server) getTask(c *gin.Context) {
|
||||
if s.tasks == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "任务管理接口尚未配置", errors.New("任务仓储未配置"))
|
||||
return
|
||||
}
|
||||
item, err := s.tasks.GetTask(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
s.writeError(c, http.StatusNotFound, "任务不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取任务失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, item)
|
||||
}
|
||||
|
||||
func (s *Server) listTaskAttempts(c *gin.Context) {
|
||||
if s.tasks == nil {
|
||||
s.writeError(c, http.StatusNotImplemented, "任务管理接口尚未配置", errors.New("任务仓储未配置"))
|
||||
return
|
||||
}
|
||||
if _, err := s.tasks.GetTask(c.Request.Context(), c.Param("id")); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
s.writeError(c, http.StatusNotFound, "任务不存在", err)
|
||||
return
|
||||
}
|
||||
s.writeError(c, http.StatusInternalServerError, "读取任务失败", err)
|
||||
return
|
||||
}
|
||||
items, err := s.tasks.ListAttempts(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询任务尝试失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (s *Server) listAuditLogs(c *gin.Context) {
|
||||
reader, ok := s.audit.(repository.AuditReader)
|
||||
if !ok {
|
||||
s.writeError(c, http.StatusNotImplemented, "审计日志查询接口尚未配置", errors.New("审计日志读取服务未配置"))
|
||||
return
|
||||
}
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
|
||||
items, err := reader.ListAuditLogs(c.Request.Context(), limit)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusInternalServerError, "查询审计日志失败", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
func newTaskAPITestServer(t *testing.T, issue func(context.Context, string) (certificate.IssueResult, deployment.Report, error)) (*Server, *repository.SQLTaskRepository, *repository.SQLAuditRepository, func()) {
|
||||
t.Helper()
|
||||
cfg := config.Default(t.TempDir())
|
||||
db, err := database.Open(context.Background(), cfg.Database)
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败:%v", err)
|
||||
}
|
||||
if err := database.Migrate(context.Background(), db.DB, cfg.Database.Driver); err != nil {
|
||||
db.Close()
|
||||
t.Fatalf("迁移测试数据库失败:%v", err)
|
||||
}
|
||||
domainRepo := repository.NewSQLDomainRepository(db.DB)
|
||||
taskRepo := repository.NewSQLTaskRepository(db.DB)
|
||||
auditRepo := repository.NewSQLAuditRepository(db.DB)
|
||||
item, err := domain.NewDomain("example.com", domain.CertificateSingle, nil)
|
||||
item.ID = "domain-1"
|
||||
if err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := domainRepo.Create(context.Background(), item); err != nil {
|
||||
db.Close()
|
||||
t.Fatalf("创建测试域名失败:%v", err)
|
||||
}
|
||||
server := New(Dependencies{
|
||||
Config: cfg,
|
||||
Repository: domainRepo,
|
||||
IssueCertificate: issue,
|
||||
Tasks: taskRepo,
|
||||
Audit: auditRepo,
|
||||
})
|
||||
return server, taskRepo, auditRepo, func() { _ = db.Close() }
|
||||
}
|
||||
|
||||
func TestTaskAPIRecordsSuccessfulIssueAndAudit(t *testing.T) {
|
||||
server, taskRepo, auditRepo, closeDB := newTaskAPITestServer(t, func(_ context.Context, id string) (certificate.IssueResult, deployment.Report, error) {
|
||||
return certificate.IssueResult{DomainID: id}, deployment.Report{Status: "success"}, nil
|
||||
})
|
||||
defer closeDB()
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/issue", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("成功任务响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
items, err := taskRepo.ListTasks(context.Background(), "", 10)
|
||||
if err != nil || len(items) != 1 || items[0].Status != "success" {
|
||||
t.Fatalf("任务没有进入成功状态:%+v %v", items, err)
|
||||
}
|
||||
attempts, err := taskRepo.ListAttempts(context.Background(), items[0].ID)
|
||||
if err != nil || len(attempts) != 1 || attempts[0].Status != "success" {
|
||||
t.Fatalf("任务尝试记录错误:%+v %v", attempts, err)
|
||||
}
|
||||
logs, err := auditRepo.ListAuditLogs(context.Background(), 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
t.Fatalf("审计日志记录错误:%+v %v", logs, err)
|
||||
}
|
||||
|
||||
list := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(list, httptest.NewRequest(http.MethodGet, "/api/v1/tasks?limit=10", nil))
|
||||
if list.Code != http.StatusOK || !strings.Contains(list.Body.String(), items[0].ID) {
|
||||
t.Fatalf("任务列表响应错误:%d %s", list.Code, list.Body.String())
|
||||
}
|
||||
|
||||
detail := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(detail, httptest.NewRequest(http.MethodGet, "/api/v1/tasks/"+items[0].ID, nil))
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "success") {
|
||||
t.Fatalf("任务详情响应错误:%d %s", detail.Code, detail.Body.String())
|
||||
}
|
||||
|
||||
attemptList := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(attemptList, httptest.NewRequest(http.MethodGet, "/api/v1/tasks/"+items[0].ID+"/attempts", nil))
|
||||
if attemptList.Code != http.StatusOK || !strings.Contains(attemptList.Body.String(), "certificate_issue") {
|
||||
t.Fatalf("任务尝试接口响应错误:%d %s", attemptList.Code, attemptList.Body.String())
|
||||
}
|
||||
|
||||
logList := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(logList, httptest.NewRequest(http.MethodGet, "/api/v1/audit-logs?limit=10", nil))
|
||||
if logList.Code != http.StatusOK || !strings.Contains(logList.Body.String(), "certificate_issue") {
|
||||
t.Fatalf("审计日志接口响应错误:%d %s", logList.Code, logList.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskAPIReturnsFailureAndKeepsTaskTrace(t *testing.T) {
|
||||
server, taskRepo, auditRepo, closeDB := newTaskAPITestServer(t, func(context.Context, string) (certificate.IssueResult, deployment.Report, error) {
|
||||
return certificate.IssueResult{}, deployment.Report{Status: "failed"}, errors.New("模拟证书申请失败")
|
||||
})
|
||||
defer closeDB()
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/issue", nil))
|
||||
if response.Code != http.StatusBadGateway || !strings.Contains(response.Body.String(), "模拟证书申请失败") {
|
||||
t.Fatalf("失败任务响应错误:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
items, err := taskRepo.ListTasks(context.Background(), "", 10)
|
||||
if err != nil || len(items) != 1 || items[0].Status != "failed" {
|
||||
t.Fatalf("失败任务状态错误:%+v %v", items, err)
|
||||
}
|
||||
logs, err := auditRepo.ListAuditLogs(context.Background(), 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "error" {
|
||||
t.Fatalf("失败审计状态错误:%+v %v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskAPIRejectsUnknownTask(t *testing.T) {
|
||||
server, _, _, closeDB := newTaskAPITestServer(t, nil)
|
||||
defer closeDB()
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/tasks/unknown", nil))
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("未知任务应返回 404:%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user