完善初始化向导、通知配置与证书流程

This commit is contained in:
xuans committed 2026-08-29 11:52:31 +08:00
1 parent b2833b761d
commit f85ef10527
41 files changed
+3645 -1697

No files matched your search

@@ -0,0 +1,7 @@
//go:build !windows
package admin
func protectCodeFile(string) error {
return nil
}
@@ -0,0 +1,100 @@
//go:build windows
package admin
import (
"fmt"
"runtime"
"golang.org/x/sys/windows"
)
func protectCodeFile(path string) error {
currentSID, err := currentProcessUserSID()
if err != nil {
return err
}
systemSID, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
if err != nil {
return fmt.Errorf("创建系统账户安全标识失败:%w", err)
}
adminSID, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
if err != nil {
return fmt.Errorf("创建本地管理员组安全标识失败:%w", err)
}
var pinner runtime.Pinner
pinner.Pin(currentSID)
pinner.Pin(systemSID)
pinner.Pin(adminSID)
defer pinner.Unpin()
readDelete := windows.ACCESS_MASK(windows.FILE_GENERIC_READ | windows.DELETE | windows.READ_CONTROL | windows.SYNCHRONIZE)
fullControl := windows.ACCESS_MASK(windows.FILE_GENERIC_READ |
windows.FILE_GENERIC_WRITE |
windows.FILE_GENERIC_EXECUTE |
windows.DELETE |
windows.READ_CONTROL |
windows.WRITE_DAC |
windows.WRITE_OWNER |
windows.SYNCHRONIZE)
entries := []windows.EXPLICIT_ACCESS{
{
AccessPermissions: readDelete,
AccessMode: windows.SET_ACCESS,
Inheritance: windows.NO_INHERITANCE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_USER,
TrusteeValue: windows.TrusteeValueFromSID(currentSID),
},
},
{
AccessPermissions: fullControl,
AccessMode: windows.SET_ACCESS,
Inheritance: windows.NO_INHERITANCE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_WELL_KNOWN_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(systemSID),
},
},
{
AccessPermissions: fullControl,
AccessMode: windows.SET_ACCESS,
Inheritance: windows.NO_INHERITANCE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_ALIAS,
TrusteeValue: windows.TrusteeValueFromSID(adminSID),
},
},
}
acl, err := windows.ACLFromEntries(entries, nil)
if err != nil {
return fmt.Errorf("创建校验码文件访问控制列表失败:%w", err)
}
if err := windows.SetNamedSecurityInfo(
path,
windows.SE_FILE_OBJECT,
windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION,
nil,
nil,
acl,
nil,
); err != nil {
return fmt.Errorf("应用校验码文件访问控制列表失败:%w", err)
}
return nil
}
func currentProcessUserSID() (*windows.SID, error) {
user, err := windows.GetCurrentProcessToken().GetTokenUser()
if err != nil {
return nil, fmt.Errorf("读取当前服务账户安全标识失败:%w", err)
}
if user == nil || user.User.Sid == nil {
return nil, fmt.Errorf("当前服务账户没有有效的安全标识")
}
return user.User.Sid, nil
}
+96 -8
View File
@@ -20,6 +20,7 @@ import (
const (
ResetPath = "/reset"
stateFileName = "scert-admin-reset.json"
codeFileName = "scert-admin-reset-code"
defaultLease = 90 * time.Second
RefreshInterval = 30 * time.Second
)
@@ -30,6 +31,7 @@ type State struct {
Active bool `json:"active"`
ResetURL string `json:"reset_url"`
CodeHash string `json:"code_hash"`
CodePath string `json:"code_path,omitempty"`
ProcessID int `json:"process_id"`
StartedAt time.Time `json:"started_at"`
ExpiresAt time.Time `json:"expires_at"`
@@ -43,15 +45,24 @@ type Session struct {
type Controller struct {
config config.Config
statePath string
codePath string
leaseDuration time.Duration
now func() time.Time
state State
}
func New(cfg config.Config) *Controller {
return NewWithCodePath(cfg, "")
}
func NewWithCodePath(cfg config.Config, codePath string) *Controller {
if strings.TrimSpace(codePath) == "" {
codePath = CodePath(cfg.Paths.Data)
}
return &Controller{
config: cfg,
statePath: StatePath(cfg.Paths.Data),
codePath: codePath,
leaseDuration: defaultLease,
now: time.Now,
}
@@ -61,6 +72,10 @@ func StatePath(dataDir string) string {
return filepath.Join(dataDir, stateFileName)
}
func CodePath(dataDir string) string {
return filepath.Join(dataDir, codeFileName)
}
func (c *Controller) Start() (Session, error) {
if c == nil {
return Session{}, fmt.Errorf("Scert-admin 控制器不能为空")
@@ -72,9 +87,11 @@ func (c *Controller) Start() (Session, error) {
if resetURL == "" {
return Session{}, fmt.Errorf("未配置管理页面域名或公网 IP,无法生成密码重置地址")
}
if active, err := IsActive(c.statePath, c.now()); err != nil {
active, err := IsActive(c.statePath, c.now())
if err != nil {
return Session{}, err
} else if active {
}
if active {
return Session{}, fmt.Errorf("密码重置入口已经启用")
}
code, err := generateCode()
@@ -83,10 +100,14 @@ func (c *Controller) Start() (Session, error) {
}
now := c.now().UTC()
c.state = State{
Active: true, ResetURL: resetURL, CodeHash: hashCode(code), ProcessID: os.Getpid(),
Active: true, ResetURL: resetURL, CodeHash: hashCode(code), CodePath: c.codePath, ProcessID: os.Getpid(),
StartedAt: now, ExpiresAt: now.Add(c.leaseDuration),
}
if err := writeCodeFile(c.codePath, code); err != nil {
return Session{}, err
}
if err := writeState(c.statePath, c.state); err != nil {
_ = removeCodeFile(c.codePath)
return Session{}, err
}
return Session{State: c.state, Code: code}, nil
@@ -102,6 +123,7 @@ func (c *Controller) Refresh() error {
}
if !latest.Active || latest.CodeHash != c.state.CodeHash || !c.now().UTC().Before(latest.ExpiresAt) {
c.state.Active = false
_ = removeCodeFile(codePathForState(c.statePath, latest))
return ErrResetSessionClosed
}
c.state = latest
@@ -113,9 +135,14 @@ func (c *Controller) Stop() error {
if c == nil || !c.state.Active {
return nil
}
c.state.Active = false
c.state.ExpiresAt = c.now().UTC()
return writeState(c.statePath, c.state)
state := c.state
state.Active = false
state.ExpiresAt = c.now().UTC()
if err := writeState(c.statePath, state); err != nil {
return err
}
c.state = state
return removeCodeFile(codePathForState(c.statePath, state))
}
func IsActive(path string, now time.Time) (bool, error) {
@@ -126,7 +153,13 @@ func IsActive(path string, now time.Time) (bool, error) {
if err != nil {
return false, err
}
return state.Active && now.UTC().Before(state.ExpiresAt), nil
active := state.Active && now.UTC().Before(state.ExpiresAt)
if !active {
if err := removeCodeFile(codePathForState(path, state)); err != nil {
return false, err
}
}
return active, nil
}
func VerifyCode(path, code string, now time.Time) (State, error) {
@@ -135,6 +168,7 @@ func VerifyCode(path, code string, now time.Time) (State, error) {
return State{}, err
}
if !state.Active || state.CodeHash == "" || !now.UTC().Before(state.ExpiresAt) {
_ = removeCodeFile(codePathForState(path, state))
return State{}, ErrResetSessionClosed
}
expected := hashCode(code)
@@ -150,6 +184,7 @@ func Consume(path string, session State, now time.Time) error {
return err
}
if !latest.Active || latest.CodeHash == "" || !now.UTC().Before(latest.ExpiresAt) {
_ = removeCodeFile(codePathForState(path, latest))
return ErrResetSessionClosed
}
if subtle.ConstantTimeCompare([]byte(latest.CodeHash), []byte(session.CodeHash)) != 1 {
@@ -158,7 +193,10 @@ func Consume(path string, session State, now time.Time) error {
latest.Active = false
latest.CodeHash = ""
latest.ExpiresAt = now.UTC()
return writeState(path, latest)
if err := writeState(path, latest); err != nil {
return err
}
return removeCodeFile(codePathForState(path, latest))
}
func ReadState(path string) (State, error) {
@@ -200,6 +238,56 @@ func writeState(path string, state State) error {
return nil
}
func writeCodeFile(path, code string) error {
if strings.TrimSpace(path) == "" {
return fmt.Errorf("未配置一次性校验码文件路径")
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return fmt.Errorf("创建一次性校验码目录失败:%w", err)
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return fmt.Errorf("创建一次性校验码文件失败:%w", err)
}
success := false
defer func() {
_ = file.Close()
if !success {
_ = os.Remove(path)
}
}()
if err := file.Chmod(0o600); err != nil {
return fmt.Errorf("设置一次性校验码文件权限失败:%w", err)
}
if _, err := file.WriteString(code + "\n"); err != nil {
return fmt.Errorf("写入一次性校验码文件失败:%w", err)
}
if err := file.Sync(); err != nil {
return fmt.Errorf("刷新一次性校验码文件失败:%w", err)
}
if err := protectCodeFile(path); err != nil {
return fmt.Errorf("保护一次性校验码文件失败:%w", err)
}
success = true
return nil
}
func removeCodeFile(path string) error {
if strings.TrimSpace(path) == "" {
return nil
}
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("销毁一次性校验码文件失败:%w", err)
}
return nil
}
func codePathForState(statePath string, state State) string {
if strings.TrimSpace(state.CodePath) != "" {
return state.CodePath
}
return CodePath(filepath.Dir(statePath))
}
func generateCode() (string, error) {
buffer := make([]byte, 10)
if _, err := rand.Read(buffer); err != nil {
+132 -2
View File
@@ -24,10 +24,12 @@ func TestScertAdminSystemdUnitKeepsManualOnlyPolicy(t *testing.T) {
unit := activeUnitText(string(data))
for _, required := range []string{
"Documentation=file:///scert/docs/Scert-admin服务管理说明.md",
"Documentation=file:///scert/docs/Scert-admin-service-management.md",
"User=Scert",
"Group=Scert",
"ExecStart=/scert/scert-admin --config /scert/conf/scert.json",
"RuntimeDirectory=scert-admin",
"RuntimeDirectoryMode=0700",
"ExecStart=/scert/scert-admin --config /scert/conf/scert.json --code-output /run/scert-admin/reset-code",
"Restart=no",
"RuntimeMaxSec=30min",
"UMask=0077",
@@ -131,6 +133,109 @@ func TestResetCodeCanOnlyBeConsumedOnce(t *testing.T) {
}
}
func TestControllerWritesAndDestroysProtectedCodeFile(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Web.Hostname = "scert.example.test"
codePath := filepath.Join(t.TempDir(), "runtime", "reset-code")
controller := NewWithCodePath(cfg, codePath)
session, err := controller.Start()
if err != nil {
t.Fatalf("启动密码重置入口失败:%v", err)
}
content, err := os.ReadFile(codePath)
if err != nil {
t.Fatalf("读取受保护校验码文件失败:%v", err)
}
if string(content) != session.Code+"\n" {
t.Fatalf("校验码文件内容错误:%q", string(content))
}
if runtime.GOOS != "windows" {
info, err := os.Stat(codePath)
if err != nil {
t.Fatalf("读取校验码文件属性失败:%v", err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("校验码文件权限错误:%o", info.Mode().Perm())
}
}
if err := controller.Stop(); err != nil {
t.Fatalf("停止密码重置入口失败:%v", err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("停止服务后校验码文件必须销毁,当前错误:%v", err)
}
}
func TestConsumeDestroysCodeFile(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Web.Hostname = "scert.example.test"
codePath := filepath.Join(t.TempDir(), "runtime", "reset-code")
controller := NewWithCodePath(cfg, codePath)
now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
controller.now = func() time.Time { return now }
session, err := controller.Start()
if err != nil {
t.Fatalf("启动密码重置入口失败:%v", err)
}
verified, err := VerifyCode(StatePath(cfg.Paths.Data), session.Code, now)
if err != nil {
t.Fatalf("校验一次性校验码失败:%v", err)
}
if err := Consume(StatePath(cfg.Paths.Data), verified, now); err != nil {
t.Fatalf("消费一次性校验码失败:%v", err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("校验码消费后文件必须销毁,当前错误:%v", err)
}
}
func TestExpiredLeaseDestroysCodeFile(t *testing.T) {
dataDir := t.TempDir()
statePath := StatePath(dataDir)
codePath := CodePath(dataDir)
if err := writeCodeFile(codePath, "expired-code"); err != nil {
t.Fatalf("创建过期校验码文件失败:%v", err)
}
now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
if err := writeState(statePath, State{Active: true, CodePath: codePath, ExpiresAt: now.Add(-time.Second)}); err != nil {
t.Fatalf("写入过期租约失败:%v", err)
}
active, err := IsActive(statePath, now)
if err != nil || active {
t.Fatalf("过期租约必须失效:active=%t err=%v", active, err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("租约失效后校验码文件必须销毁,当前错误:%v", err)
}
}
func TestControllerDoesNotOverwriteExistingCodeFile(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Web.Hostname = "scert.example.test"
codePath := filepath.Join(t.TempDir(), "runtime", "reset-code")
if err := os.MkdirAll(filepath.Dir(codePath), 0o700); err != nil {
t.Fatalf("创建测试目录失败:%v", err)
}
const existing = "existing-code\n"
if err := os.WriteFile(codePath, []byte(existing), 0o600); err != nil {
t.Fatalf("创建已有校验码文件失败:%v", err)
}
if _, err := NewWithCodePath(cfg, codePath).Start(); err == nil {
t.Fatal("已有校验码文件时不允许覆盖")
}
content, err := os.ReadFile(codePath)
if err != nil {
t.Fatalf("读取已有校验码文件失败:%v", err)
}
if string(content) != existing {
t.Fatalf("已有校验码文件被修改:%q", string(content))
}
}
func activeUnitText(unit string) string {
lines := strings.Split(unit, "\n")
active := make([]string, 0, len(lines))
@@ -143,3 +248,28 @@ func activeUnitText(unit string) string {
}
return strings.Join(active, "\n")
}
func TestConsumeExpiredSessionRemovesCodeFile(t *testing.T) {
baseDir := t.TempDir()
statePath := filepath.Join(baseDir, "state.json")
codePath := filepath.Join(baseDir, "reset-code")
now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
if err := os.WriteFile(codePath, []byte("expired-code\n"), 0o600); err != nil {
t.Fatalf("创建过期校验码文件失败:%v", err)
}
state := State{
Active: true,
CodeHash: hashCode("expired-code"),
CodePath: codePath,
ExpiresAt: now.Add(-time.Second),
}
if err := writeState(statePath, state); err != nil {
t.Fatalf("写入过期会话失败:%v", err)
}
if err := Consume(statePath, state, now); err != ErrResetSessionClosed {
t.Fatalf("消费过期会话应返回关闭错误:%v", err)
}
if _, err := os.Stat(codePath); !os.IsNotExist(err) {
t.Fatalf("消费过期会话后必须销毁校验码文件:%v", err)
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ func TestScertSystemdUnitPolicy(t *testing.T) {
}
unit := activeUnitText(string(data))
for _, required := range []string{
"Documentation=file:///scert/docs/Scert服务管理说明.md",
"Documentation=file:///scert/docs/Scert-service-management.md",
"User=Scert",
"Group=Scert",
"ExecStart=/scert/scert --config /scert/conf/scert.json serve",