修复正式初始化边界与向导过期校验并补齐回归测试

This commit is contained in:
xuans committed 2026-09-16 20:18:07 +08:00
1 parent c6bfcfd9ae
commit f277e101f2
10 files changed
+343 -75

No files matched your search

@@ -14,7 +14,9 @@ import (
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -115,7 +117,7 @@ func TestHTTPSBootstrapCompletesSQLiteAndStartsApplication(t *testing.T) {
input.DNSVerificationToken = dnsResult.Token
var completed CompleteResult
post("/api/v1/bootstrap/complete", input, &completed)
if !completed.Completed || completed.ManagementURL != "https://"+net.JoinHostPort(input.WebPublicIP, strings.Split(address, ":")[1])+"/" {
if !completed.Completed || completed.ManagementURL != "https://"+net.JoinHostPort(input.WebPublicIP, strconv.Itoa(input.ServerPort))+"/" {
t.Fatal("初始化未返回正确管理地址")
}
select {
@@ -143,6 +145,23 @@ func TestHTTPSBootstrapCompletesSQLiteAndStartsApplication(t *testing.T) {
t.Fatal(err)
}
applicationResult := make(chan error, 1)
var closeOnce sync.Once
closeApplication := func() {
closeOnce.Do(func() {
if err := application.Close(); err != nil {
t.Error(err)
}
select {
case err := <-applicationResult:
if !errors.Is(err, http.ErrServerClosed) {
t.Errorf("正式服务关闭错误:%v", err)
}
case <-time.After(5 * time.Second):
t.Error("正式服务关闭超时")
}
})
}
defer closeApplication()
go func() { applicationResult <- application.HTTP.ListenAndServe() }()
// 正式 IP 证书与临时证书不同,只信任本次生成的正式证书。
certificatePEM, err := os.ReadFile(stored.Server.TLSCert)
@@ -174,7 +193,6 @@ func TestHTTPSBootstrapCompletesSQLiteAndStartsApplication(t *testing.T) {
}
time.Sleep(10 * time.Millisecond)
}
defer application.Close()
for path, expected := range map[string]int{
"/api/v1/bootstrap/status": http.StatusNotFound,
"/api/v1/bootstrap/settings": http.StatusNotFound,
@@ -189,17 +207,7 @@ func TestHTTPSBootstrapCompletesSQLiteAndStartsApplication(t *testing.T) {
t.Fatalf("切换后 %s 状态错误:%d", path, response.StatusCode)
}
}
if err := application.Close(); err != nil {
t.Fatal(err)
}
select {
case err := <-applicationResult:
if !errors.Is(err, http.ErrServerClosed) {
t.Fatalf("正式服务关闭错误:%v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("正式服务关闭超时")
}
closeApplication()
}
func TestBootstrapRunCancellationRemovesURLWithoutCreatingBusinessDatabase(t *testing.T) {
+26 -12
View File
@@ -112,6 +112,8 @@ type Server struct {
loginInFlight int
loginPrunedAt time.Time
now func() time.Time
httpMu sync.Mutex
httpStopped bool
httpServer *http.Server
router *gin.Engine
}
@@ -221,17 +223,13 @@ func (s *Server) ListenAndServe() error {
s.configMu.RLock()
cfg := s.config
s.configMu.RUnlock()
if !cfg.SetupReady {
return errors.New("初始化未完成,请使用独立 HTTPS 初始化服务")
}
address, err := listenAddress(cfg)
if err != nil {
return err
}
s.httpServer = newHTTPServer(address, s.router)
if !cfg.SetupReady {
if s.logger != nil {
s.logger.Info("HTTP 服务启动", "address", s.httpServer.Addr, "https_mode", "初始化明文 HTTP")
}
return s.httpServer.ListenAndServe()
}
certPath := strings.TrimSpace(cfg.Server.TLSCert)
keyPath := strings.TrimSpace(cfg.Server.TLSKey)
if certPath == "" || keyPath == "" {
@@ -243,10 +241,22 @@ func (s *Server) ListenAndServe() error {
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)
server := newHTTPServer(address, s.router)
s.httpMu.Lock()
if s.httpStopped {
s.httpMu.Unlock()
return http.ErrServerClosed
}
return s.httpServer.ListenAndServeTLS(certPath, keyPath)
if s.httpServer != nil {
s.httpMu.Unlock()
return errors.New("HTTPS 服务已经启动")
}
s.httpServer = server
s.httpMu.Unlock()
if s.logger != nil {
s.logger.Info("HTTPS 服务启动", "address", server.Addr, "https_mode", cfg.Server.HTTPSMode)
}
return server.ListenAndServeTLS(certPath, keyPath)
}
func newHTTPServer(address string, handler http.Handler) *http.Server {
@@ -289,10 +299,14 @@ func isLoopbackHost(host string) bool {
}
func (s *Server) Shutdown(ctx context.Context) error {
if s.httpServer == nil {
s.httpMu.Lock()
s.httpStopped = true
server := s.httpServer
s.httpMu.Unlock()
if server == nil {
return nil
}
err := s.httpServer.Shutdown(ctx)
err := server.Shutdown(ctx)
if errors.Is(err, http.ErrServerClosed) {
return nil
}
+4
View File
@@ -80,6 +80,10 @@ type dnsTestRequest struct {
func (s *Server) registerSetupRoutes() {
s.router.GET("/api/v1/setup/status", s.setupStatus)
// 正式服务只保留状态查询;旧写接口仅供桌面端本机初始化使用。
if s.config.SetupReady {
return
}
s.router.GET("/api/v1/setup/dns/providers", s.setupDNSProviders)
s.router.POST("/api/v1/setup/dns/test", s.requireSameOrigin, s.requireSetupAccess, s.dnsOperation, s.testSetupDNS)
s.router.POST("/api/v1/setup", s.requireSameOrigin, s.requireSetupAccess, s.longOperation(12*time.Minute), s.applySetup)
@@ -0,0 +1,81 @@
package httpapi
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
func TestReadyServerDoesNotRegisterLegacySetupWrites(t *testing.T) {
server := New(Dependencies{Config: readyTestConfig(t.TempDir())})
for _, item := range []struct {
method string
path string
status int
}{
{http.MethodGet, "/api/v1/setup/status", http.StatusOK},
{http.MethodGet, "/api/v1/setup/dns/providers", http.StatusNotFound},
{http.MethodPost, "/api/v1/setup/dns/test", http.StatusNotFound},
{http.MethodPost, "/api/v1/setup", http.StatusNotFound},
{http.MethodGet, "/api/v1/bootstrap/status", http.StatusNotFound},
} {
for _, remote := range []string{"127.0.0.1:12345", "203.0.113.20:12345"} {
request := httptest.NewRequest(item.method, item.path, strings.NewReader(`{}`))
request.RemoteAddr = remote
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != item.status {
t.Fatalf("正式服务路由状态错误:%s %s %d", item.method, item.path, response.Code)
}
}
}
}
func TestUninitializedServerCannotStartPlainHTTP(t *testing.T) {
server := New(Dependencies{Config: config.Default(t.TempDir())})
if err := server.ListenAndServe(); err == nil || !strings.Contains(err.Error(), "独立 HTTPS") {
t.Fatalf("未初始化服务应拒绝启动明文监听:%v", err)
}
if server.httpServer != nil {
t.Fatal("未初始化不应创建正式监听服务")
}
}
func TestShutdownBeforeStartPreventsLaterListener(t *testing.T) {
dir := t.TempDir()
cfg := readyTestConfig(dir)
// 停止状态必须在加载证书和监听端口前生效,夹具不需要可用的证书。
cfg.Server.TLSCert = filepath.Join(dir, "cert.pem")
cfg.Server.TLSKey = filepath.Join(dir, "key.pem")
for _, path := range []string{cfg.Server.TLSCert, cfg.Server.TLSKey} {
if err := os.WriteFile(path, []byte("test-only"), 0o600); err != nil {
t.Fatal(err)
}
}
server := New(Dependencies{Config: cfg})
if err := server.Shutdown(context.Background()); err != nil {
t.Fatal(err)
}
var pending sync.WaitGroup
for index := 0; index < 16; index++ {
pending.Go(func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
t.Errorf("关闭后不应重新监听:%v", err)
}
})
pending.Go(func() {
if err := server.Shutdown(context.Background()); err != nil {
t.Error(err)
}
})
}
pending.Wait()
}