补齐首次初始化临时证书指纹核对与回归测试

This commit is contained in:
xuans committed 2026-09-16 20:38:03 +08:00
1 parent f3cce10664
commit 213f030b4d
6 files changed
+51 -6

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
package bootstrap
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"strings"
"testing"
)
func TestBootstrapNoticeMatchesTLSCertificateFingerprint(t *testing.T) {
material, err := NewTemporaryTLSMaterial("203.0.113.20")
if err != nil {
t.Fatal(err)
}
var output bytes.Buffer
writeBootstrapNotice(&output, 8080, "/run/scert/bootstrap-url", material)
digest := sha256.Sum256(material.Leaf.Raw)
want := strings.ToUpper(hex.EncodeToString(digest[:]))
if !strings.Contains(output.String(), "SHA-256 指纹:"+want) || !strings.Contains(output.String(), "/run/scert/bootstrap-url") {
t.Fatal("启动提示缺少实际 TLS 证书的 SHA-256 指纹或受保护地址路径")
}
for _, forbidden := range []string{"token=", "PRIVATE KEY", "CERTIFICATE-----"} {
if strings.Contains(output.String(), forbidden) {
t.Fatal("启动提示不得泄露令牌、私钥或完整证书材料")
}
}
}
+9 -2
View File
@@ -2,6 +2,7 @@ package bootstrap
import (
"context"
"crypto/sha256"
"crypto/tls"
"errors"
"fmt"
@@ -92,12 +93,18 @@ func Run(ctx context.Context, options ServerOptions) (bool, error) {
}
}()
if options.Output != nil {
// 一次性令牌只能写入受保护文件,不进入终端日志或 systemd journal。
fmt.Fprintf(options.Output, "首次初始化 HTTPS 服务已启动,端口 %d。请读取 %s 获取一次性访问地址;临时自签名证书需人工核对。\n", options.Config.Server.Port, options.URLPath)
writeBootstrapNotice(options.Output, options.Config.Server.Port, options.URLPath, material)
}
return serveTemporaryHTTPS(ctx, listener, material, handler, router.Completed())
}
func writeBootstrapNotice(output io.Writer, port int, path string, material TLSMaterial) {
// 指纹是公开证书摘要;一次性令牌和私钥仍只能留在受保护文件或内存中。
fingerprint := sha256.Sum256(material.Certificate.Certificate[0])
fmt.Fprintf(output, "首次初始化 HTTPS 服务已启动,端口 %d。请读取 %s 获取一次性访问地址。\n", port, path)
fmt.Fprintf(output, "Bootstrap 临时证书 SHA-256 指纹:%X\n请通过可信运维通道与浏览器证书详情核对;指纹不一致时不要输入初始化令牌、密码或 RAM 凭据。\n", fingerprint)
}
func serveTemporaryHTTPS(ctx context.Context, listener net.Listener, material TLSMaterial, handler http.Handler, completed <-chan struct{}) (bool, error) {
requestContext, cancelRequests := context.WithCancel(context.Background())
defer cancelRequests()
@@ -289,6 +289,9 @@ func TestBootstrapRunCancellationRemovesURLWithoutCreatingBusinessDatabase(t *te
if parsed.Fragment == "" || strings.Contains(output.String(), parsed.Fragment) {
t.Fatal("一次性令牌缺失或泄露到日志")
}
if !strings.Contains(output.String(), "Bootstrap 临时证书 SHA-256 指纹:") {
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)