Files
ginframework/http/accesslog/accesslog_test.go
T
zhangdeman c25bc4528a
Verify / verify (push) Canceled after 0s
feat(logger): 开放敏感内容列表定制并增加敏感检测开关
- 将凭据片段列表提升为全局默认列表,新增 DefaultSensitiveList、NewSensitiveList、Extend 与 SafeWith,支持整体替换或在默认列表之上扩展
- 新增 SetSensitiveDetection 与 SensitiveDetectionEnabled,缺省开启敏感检测,关闭后日志副本不再按名称隐藏凭据字段
- 显式敏感列表、访问日志固定凭据头与 RedactKeys、SQL config_value 与 Redis 认证命令等固定策略不受开关影响
- 同步接入使用指南的能力清单与使用说明
2026-11-29 16:39:50 +08:00

125 lines
4.9 KiB
Go

package accesslog
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue"
"github.com/gin-gonic/gin"
)
func TestSafeCopiesAndSnapshots(t *testing.T) {
source := map[string]any{"password": "private-password", "config_value": "private-config", "items": []any{map[string]any{"token": "private-token"}}, "visible": "ok"}
headers := []string{"X-Visible", "Authorization"}
cfg := Config{RequestHeaderList: headers, RedactKeys: []string{"config_value"}, MaxResponseBodyBytes: 32}
records := []Record{}
engine := gin.New()
engine.Use(New(cfg, Options{
RequestBody: func(*gin.Context) any { return source },
ResponseBody: func(*gin.Context) any { return map[string]any{"payload": strings.Repeat("x", 100)} },
Emit: func(_ *gin.Context, r Record) { records = append(records, r) },
}))
headers[0] = "X-Later"
cfg.RedactKeys[0] = "other"
engine.POST("/api", func(ctx *gin.Context) {
data, err := io.ReadAll(ctx.Request.Body)
if err != nil || string(data) != "original-stream" {
t.Fatalf("body altered: %s %v", data, err)
}
ctx.Header("Set-Cookie", "private-cookie")
ctx.Header("Content-Type", "application/json")
ctx.String(200, "ok")
})
req := httptest.NewRequest("POST", "/api?token=private-query", strings.NewReader("original-stream"))
req.Header.Set("X-Visible", "yes")
req.Header.Set("Authorization", "private-header")
engine.ServeHTTP(httptest.NewRecorder(), req)
if len(records) != 2 {
t.Fatalf("records=%+v", records)
}
encoded, err := json.Marshal(records)
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"private-password", "private-config", "private-token", "private-query", "private-header", "private-cookie"} {
if strings.Contains(string(encoded), secret) {
t.Fatalf("leaked %s", secret)
}
}
if records[0].Header.Get("X-Visible") != "yes" || !strings.Contains(string(encoded), "sha256") {
t.Fatalf("missing header or digest: %s", encoded)
}
records[0].Body.(map[string]any)["visible"] = "changed"
if source["visible"] != "ok" || source["password"] != "private-password" {
t.Fatal("source modified")
}
}
func TestStreamingWriterAndIndependentPolicies(t *testing.T) {
records := []Record{}
engine := gin.New()
engine.Use(New(Config{}, Options{RecordRequest: func(*gin.Context) bool { return false }, RecordResponse: func(*gin.Context) bool { return true }, Emit: func(_ *gin.Context, r Record) { records = append(records, r) }}))
engine.GET("/events", func(ctx *gin.Context) { ctx.SSEvent("ready", "hello"); ctx.Writer.Flush() })
out := httptest.NewRecorder()
engine.ServeHTTP(out, httptest.NewRequest("GET", "/events", nil))
if !out.Flushed || !strings.Contains(out.Body.String(), "hello") || len(records) != 1 || records[0].Request || records[0].Body != nil {
t.Fatalf("stream changed: %+v %s", records, out.Body.String())
}
}
func TestDefaultPoliciesAndDisabledCollector(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodOptions} {
count := 0
engine := gin.New()
engine.Use(New(Config{}, Options{Filter: func(*gin.Context) bool { return true }, Emit: func(*gin.Context, Record) { count++ }}))
engine.Handle(method, "/api", func(ctx *gin.Context) { ctx.Status(204) })
engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(method, "/api", nil))
expected := 1
if method == http.MethodOptions {
expected = 0
}
if count != expected {
t.Fatalf("%s count=%d", method, count)
}
}
engine := gin.New()
engine.Use(New(Config{}, Options{RequestBody: func(*gin.Context) any { t.Fatal("disabled collector read"); return nil }}))
engine.GET("/api", func(ctx *gin.Context) { ctx.Status(204) })
engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/api", nil))
}
// TestDisabledSensitiveDetectionKeepsFixedPolicies 验证关闭敏感检测后正文保留原值,固定忽略的凭据头仍然隐藏。
func TestDisabledSensitiveDetectionKeepsFixedPolicies(t *testing.T) {
storagevalue.SetSensitiveDetection(false)
defer storagevalue.SetSensitiveDetection(true)
records := []Record{}
engine := gin.New()
engine.Use(New(Config{}, Options{
RequestBody: func(*gin.Context) any { return map[string]any{"password": "private-password"} },
Emit: func(_ *gin.Context, r Record) { records = append(records, r) },
}))
engine.POST("/api", func(ctx *gin.Context) { ctx.Status(204) })
req := httptest.NewRequest("POST", "/api", strings.NewReader("{}"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "private-header")
engine.ServeHTTP(httptest.NewRecorder(), req)
if len(records) != 1 {
t.Fatalf("records=%+v", records)
}
if records[0].Header.Get("Authorization") != "" {
t.Fatal("fixed credential header policy was disabled")
}
body, err := json.Marshal(records[0].Body)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), "private-password") {
t.Fatal("disabled detection still hid the body field")
}
}