保存最小权限初始化防火墙策略与依赖加固检查点

This commit is contained in:
xuans committed 2026-09-16 20:49:26 +08:00
1 parent c98c6050c5
commit 7d374dc10d
19 files changed
+255 -20

No files matched your search

+9 -1
View File
@@ -327,7 +327,9 @@ func (completer *Completer) Complete(ctx context.Context, request CompleteReques
candidate.Server.TLSCert = certificateResult.fullChainPath
candidate.Server.TLSKey = certificateResult.privateKeyPath
firewallResult, err = completer.firewall.OpenTCP(ctx, candidate.Server.Port)
firewallContext, cancelFirewall := context.WithTimeout(ctx, 30*time.Second)
firewallResult, err = completer.firewall.OpenTCP(firewallContext, candidate.Server.Port)
cancelFirewall()
if err != nil {
return result, completeError(CompleteErrorDependency, "配置主服务防火墙规则失败", err)
}
@@ -348,6 +350,12 @@ func (completer *Completer) Complete(ctx context.Context, request CompleteReques
completer.base = candidate
result = CompleteResult{Completed: true, ManagementURL: managementURL(candidate)}
result.Warnings = completer.afterCommit(candidate)
if firewallResult.Backend == firewall.BackendExternal {
result.Warnings = append(result.Warnings, firewallResult.Message)
if completer.warn != nil {
completer.warn(firewallResult.Message)
}
}
return result, nil
}
+56 -1
View File
@@ -110,10 +110,13 @@ type completionFirewall struct {
openCalls int
rollbackCalls int
block chan struct{}
deadline time.Time
hasDeadline bool
}
func (manager *completionFirewall) OpenTCP(_ context.Context, port int) (firewall.Result, error) {
func (manager *completionFirewall) OpenTCP(ctx context.Context, port int) (firewall.Result, error) {
manager.mu.Lock()
manager.deadline, manager.hasDeadline = ctx.Deadline()
manager.openCalls++
result := manager.result
openErr := manager.openErr
@@ -291,6 +294,58 @@ func TestCompleterRejectsDNSDomainMismatchBeforeDatabaseSideEffects(t *testing.T
}
}
func TestCompleterExternalFirewallCommitsWithExplicitWarning(t *testing.T) {
fixture := newCompletionFixture(t, "admin.example.test")
selected, err := firewall.NewManagerWithMode(firewall.ModeExternal)
if err != nil {
t.Fatal(err)
}
var warnings []string
result, err := fixture.completer(func(dependencies *CompleteDependencies) {
dependencies.Firewall = selected
dependencies.Warn = func(message string) { warnings = append(warnings, message) }
}).Complete(context.Background(), fixture.request("admin.example.test"))
if err != nil || !result.Completed || len(result.Warnings) != 1 || len(warnings) != 1 {
t.Fatalf("外部管理模式必须完成配置并明确警告:%+v,%v", result, err)
}
if !strings.Contains(result.Warnings[0], "未检查或修改") || !strings.Contains(warnings[0], "8443") {
t.Fatal("响应和运维日志必须说明正式端口没有经过防火墙验证")
}
stored, err := config.Load(fixture.configPath)
if err != nil || !stored.SetupReady {
t.Fatalf("外部管理模式没有保存正式配置:%v", err)
}
}
func TestCompleterFirewallHasBoundedDeadline(t *testing.T) {
fixture := newCompletionFixture(t, "admin.example.test")
started := time.Now()
_, err := fixture.completer(nil).Complete(context.Background(), fixture.request("admin.example.test"))
if err != nil {
t.Fatal(err)
}
if !fixture.firewall.hasDeadline || fixture.firewall.deadline.Before(started) ||
fixture.firewall.deadline.After(time.Now().Add(30*time.Second)) {
t.Fatal("初始化防火墙命令必须有不超过三十秒的超时")
}
}
func TestCompleterAutomaticFirewallFailureDoesNotSilentlySkip(t *testing.T) {
fixture := newCompletionFixture(t, "admin.example.test")
fixture.firewall.openErr = errors.New("permission denied")
_, err := fixture.completer(nil).Complete(context.Background(), fixture.request("admin.example.test"))
var completeErr *CompleteError
if !errors.As(err, &completeErr) || completeErr.Kind != CompleteErrorDependency {
t.Fatalf("自动模式权限失败必须中止初始化:%v", err)
}
if _, statErr := os.Stat(fixture.configPath); !errors.Is(statErr, os.ErrNotExist) {
t.Fatal("防火墙失败不应提交正式配置")
}
if _, statErr := os.Stat(fixture.issuer.saved.CertificatePath); !errors.Is(statErr, os.ErrNotExist) {
t.Fatal("防火墙失败必须回滚本次管理证书")
}
}
func TestCompleterRollsBackCertificateAndFirewallWhenConfigSaveFails(t *testing.T) {
fixture := newCompletionFixture(t, "admin.example.test")
_, err := fixture.completer(func(dependencies *CompleteDependencies) {
+14 -6
View File
@@ -26,11 +26,12 @@ import (
)
type ServerOptions struct {
Config config.Config
ConfigPath string
PublicIP string
URLPath string
Output io.Writer
Config config.Config
ConfigPath string
PublicIP string
URLPath string
Output io.Writer
FirewallMode string
}
// Run 只创建初始化所需组件;正式数据库、业务路由和后台任务由切换后的应用创建。
@@ -38,6 +39,10 @@ func Run(ctx context.Context, options ServerOptions) (bool, error) {
if options.Config.SetupReady {
return false, errors.New("已经初始化,不能启动临时初始化服务")
}
firewallManager, err := firewall.NewManagerWithMode(options.FirewallMode)
if err != nil {
return false, err
}
material, err := NewTemporaryTLSMaterial(options.PublicIP)
if err != nil {
return false, err
@@ -69,7 +74,7 @@ func Run(ctx context.Context, options ServerOptions) (bool, error) {
completer := NewCompleter(CompleteDependencies{
BaseConfig: options.Config, ConfigPath: options.ConfigPath, BootstrapURLPath: options.URLPath,
DatabaseSessions: databases, DNSSessions: dns, Credentials: store, Sessions: sessions,
Firewall: firewall.NewManager(), Certificate: issuer,
Firewall: firewallManager, Certificate: issuer,
Warn: func(message string) {
if options.Output != nil {
fmt.Fprintln(options.Output, message)
@@ -94,6 +99,9 @@ func Run(ctx context.Context, options ServerOptions) (bool, error) {
}()
if options.Output != nil {
writeBootstrapNotice(options.Output, options.Config.Server.Port, options.URLPath, material)
if strings.EqualFold(strings.TrimSpace(options.FirewallMode), firewall.ModeExternal) {
fmt.Fprintln(options.Output, "初始化防火墙采用 external 模式:不检查或修改主机规则及云安全组,请管理员预先放行所需端口。")
}
}
return serveTemporaryHTTPS(ctx, listener, material, handler, router.Completed())
}
@@ -255,6 +255,7 @@ func TestBootstrapRunCancellationRemovesURLWithoutCreatingBusinessDatabase(t *te
ok, err := Run(ctx, ServerOptions{
Config: fixture.base, ConfigPath: fixture.configPath,
PublicIP: "127.0.0.1", URLPath: fixture.urlPath, Output: &output,
FirewallMode: "external",
})
if ok {
err = errors.New("取消操作误报初始化完成")
@@ -292,6 +293,9 @@ func TestBootstrapRunCancellationRemovesURLWithoutCreatingBusinessDatabase(t *te
if !strings.Contains(output.String(), "Bootstrap 临时证书 SHA-256 指纹:") {
t.Fatal("初始化启动日志缺少可通过可信运维通道核对的证书指纹")
}
if !strings.Contains(output.String(), "不检查或修改主机规则及云安全组") {
t.Fatal("外部防火墙管理策略必须明确记录,不得悄悄跳过")
}
for _, path := range []string{fixture.urlPath, fixture.configPath, filepath.Join(fixture.base.Paths.Data, "scert.db")} {
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("取消后不应保留初始化地址或提前产生正式文件:%s", path)
+17
View File
@@ -113,3 +113,20 @@ func TestBootstrapHandlerIsolatesBusinessRoutesAndSettings(t *testing.T) {
t.Fatal("认证后无法读取初始化设置")
}
}
func TestBootstrapRejectsInvalidFirewallModeBeforeWritingFiles(t *testing.T) {
root := t.TempDir()
configPath := filepath.Join(root, "conf", "scert.json")
urlPath := filepath.Join(root, "run", "bootstrap-url")
ok, err := Run(context.Background(), ServerOptions{
Config: config.Default(root), ConfigPath: configPath, URLPath: urlPath,
PublicIP: "127.0.0.1", FirewallMode: "invalid",
})
if err == nil || ok {
t.Fatal("错误防火墙模式不应启动初始化")
}
entries, err := os.ReadDir(root)
if err != nil || len(entries) != 0 {
t.Fatal("防火墙模式校验应发生在创建任何配置或敏感信息文件之前")
}
}