完善证书申请续期与安装初始化流程

This commit is contained in:
xuans committed 2026-08-27 00:31:40 +08:00
1 parent fd8d8608f5
commit 07636abe44
66 files changed
+9470 -165

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
package admin
import (
"bufio"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
)
func TestLinuxInstallerPolicy(t *testing.T) {
_, sourceFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("无法定位测试源文件")
}
installerPath := filepath.Join(filepath.Dir(sourceFile), "..", "..", "..", "deploy", "install-linux.sh")
data, err := os.ReadFile(installerPath)
if err != nil {
t.Fatalf("读取 Linux 安装器失败:%v", err)
}
content := string(data)
required := []string{
`readonly INSTALL_DIR="/scert"`,
`readonly DEFAULT_CERTIFICATE_DIR="/ssl"`,
`readonly SERVICE_USER="Scert"`,
`readonly INSTALL_METADATA_FILE="$INSTALL_DIR/conf/installation.json"`,
`useradd --system`,
`--badname`,
`--shell "$nologin_shell"`,
`systemctl daemon-reload`,
`--certificate-dir`,
`readlink -m -- "$certificate_dir"`,
`reject_symlink_path "$certificate_dir" "证书目录"`,
`/etc|/etc/*`,
`/scert|/scert/*`,
`chown -R -h "$SERVICE_USER:$SERVICE_GROUP"`,
`write_install_metadata`,
`10-certificate-path.conf`,
`"$INSTALL_DIR/conf"`,
`"$INSTALL_DIR/data"`,
`"$INSTALL_DIR/log"`,
`"$INSTALL_DIR/backups"`,
`"$certificate_dir"`,
}
for _, item := range required {
if !strings.Contains(content, item) {
t.Errorf("Linux 安装器缺少必要策略:%s", item)
}
}
forbiddenCommands := []string{
"systemctl enable Scert-admin",
"systemctl start Scert-admin",
"systemctl restart Scert-admin",
"systemctl enable --now Scert-admin",
}
for _, command := range forbiddenCommands {
if containsExecutableLine(content, command) || containsSystemctlAction(content, strings.Fields(command)[1], "Scert-admin") {
t.Errorf("Linux 安装器不得执行命令:%s", command)
}
}
for _, command := range []string{"ufw ", "firewall-cmd ", "New-NetFirewallRule"} {
if strings.Contains(content, command) {
t.Errorf("Linux 文件安装器不得直接配置防火墙:%s", command)
}
}
if countExecutableLine(content, "systemctl daemon-reload") != 1 {
t.Errorf("Linux 安装器必须且只能执行一次 systemctl daemon-reload")
}
}
func TestSystemctlPolicyMatcherCoversWrappedCommands(t *testing.T) {
for _, content := range []string{
"systemctl --no-block start Scert-admin",
`command systemctl restart "Scert-admin"`,
"sudo systemctl reload Scert-admin",
} {
if !containsSystemctlAction(content, strings.Fields(content)[2], "Scert-admin") {
t.Fatalf("未识别受禁止的 systemctl 调用:%s", content)
}
}
}
func containsExecutableLine(content, command string) bool {
return countExecutableLine(content, command) > 0
}
func containsSystemctlAction(content, action, unit string) bool {
pattern := `(?m)^\s*(?:command\s+|sudo\s+)?systemctl\b[^\n]*\b` + regexp.QuoteMeta(action) + `\b[^\n]*\b` + regexp.QuoteMeta(unit) + `\b`
return regexp.MustCompile(pattern).MatchString(content)
}
func countExecutableLine(content, command string) int {
count := 0
scanner := bufio.NewScanner(strings.NewReader(content))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if line == command {
count++
}
}
return count
}
+67
View File
@@ -0,0 +1,67 @@
package admin
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"time"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
type Server struct {
config config.Config
http *http.Server
}
func New(cfg config.Config) *Server {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", health)
mux.HandleFunc("/api/v1/admin/status", func(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet {
writer.WriteHeader(http.StatusMethodNotAllowed)
return
}
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(writer).Encode(map[string]any{
"service": "scert-admin",
"reset_enabled": false,
"listen_scope": "local_only",
"message": "密码重置协议尚未启用,当前仅提供受保护服务入口",
})
})
return &Server{config: cfg, http: &http.Server{
Addr: net.JoinHostPort(cfg.Admin.ResetServiceHost, strconv.Itoa(cfg.Admin.ResetServicePort)),
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}}
}
func (s *Server) ListenAndServe() error {
if s.config.Admin.ResetServiceHost != "127.0.0.1" && s.config.Admin.ResetServiceHost != "::1" {
return fmt.Errorf("Scert-admin 仅允许监听本机回环地址")
}
return s.http.ListenAndServe()
}
func (s *Server) Shutdown(ctx context.Context) error {
if s == nil || s.http == nil {
return nil
}
return s.http.Shutdown(ctx)
}
func health(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet {
writer.WriteHeader(http.StatusMethodNotAllowed)
return
}
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(writer).Encode(map[string]string{"status": "ok", "service": "scert-admin"})
}
+80
View File
@@ -0,0 +1,80 @@
package admin
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/config"
)
func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
_, sourceFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("无法定位测试源文件")
}
unitPath := filepath.Join(filepath.Dir(sourceFile), "..", "..", "..", "deploy", "systemd", "Scert-admin.service")
data, err := os.ReadFile(unitPath)
if err != nil {
t.Fatalf("读取 Scert-admin systemd unit 失败:%v", err)
}
unit := activeUnitText(string(data))
for _, required := range []string{
"Documentation=file:///scert/docs/Scert-admin服务管理说明.md",
"User=Scert",
"Group=Scert",
"ExecStart=/scert/scert-admin --config /scert/conf/scert.json",
"Restart=no",
"UMask=0077",
"ProtectHome=yes",
"NoNewPrivileges=yes",
} {
if !strings.Contains(unit, required) {
t.Errorf("Scert-admin systemd unit 缺少必要策略:%s", required)
}
}
for _, forbidden := range []string{
"[Install]",
"WantedBy=",
"Restart=always",
"Restart=on-failure",
"ExecReload=",
} {
if strings.Contains(unit, forbidden) {
t.Errorf("Scert-admin systemd unit 不得包含:%s", forbidden)
}
}
}
func TestListenAndServeRejectsNonLoopbackHost(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.Admin.ResetServiceHost = "0.0.0.0"
server := New(cfg)
if err := server.ListenAndServe(); err == nil {
t.Fatal("Scert-admin 必须拒绝非回环监听地址")
}
}
func TestConfigRejectsLocalhostAlias(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.Admin.ResetServiceHost = "localhost"
if err := cfg.Validate(); err == nil {
t.Fatal("Scert-admin 不得依赖 localhost 名称解析")
}
}
func activeUnitText(unit string) string {
lines := strings.Split(unit, "\n")
active := make([]string, 0, len(lines))
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
active = append(active, trimmed)
}
return strings.Join(active, "\n")
}
@@ -0,0 +1,42 @@
package admin
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestScertSystemdUnitPolicy(t *testing.T) {
_, sourceFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("无法定位测试源文件")
}
unitPath := filepath.Join(filepath.Dir(sourceFile), "..", "..", "..", "deploy", "systemd", "Scert.service")
data, err := os.ReadFile(unitPath)
if err != nil {
t.Fatalf("读取 Scert systemd unit 失败:%v", err)
}
unit := activeUnitText(string(data))
for _, required := range []string{
"Documentation=file:///scert/docs/Scert服务管理说明.md",
"User=Scert",
"Group=Scert",
"ExecStart=/scert/scert --config /scert/conf/scert.json serve",
"Restart=on-failure",
"UMask=0077",
"ReadWritePaths=/ssl /scert/conf /scert/data /scert/log /scert/backups",
"[Install]",
"WantedBy=multi-user.target",
} {
if !strings.Contains(unit, required) {
t.Errorf("Scert systemd unit 缺少必要策略:%s", required)
}
}
for _, forbidden := range []string{"ExecReload=", "Restart=always"} {
if strings.Contains(unit, forbidden) {
t.Errorf("Scert systemd unit 不得包含:%s", forbidden)
}
}
}