Files
kra-oa/internal/server/middleware/sms_audit_test.go
T
2026-09-29 18:15:35 +08:00

47 lines
1.5 KiB
Go

package middleware
import (
"bytes"
"github.com/gin-gonic/gin"
"kra/internal/config"
"kra/internal/routecatalog"
"log/slog"
"net/http/httptest"
"strings"
"testing"
)
func TestSMSAuditHidesPhoneAndTemplateParameters(t *testing.T) {
gin.SetMode(gin.TestMode)
var output bytes.Buffer
engine := gin.New()
engine.Use(AccessLog(config.NewStore(&config.Config{Admin: &config.Admin{}}), slog.New(slog.NewJSONHandler(&output, nil)), "test"))
engine.POST("/api/integration/sms/:provider/send", func(c *gin.Context) {
if body, _ := c.Get(ctxReqBodyKey); body != "[短信发送参数已隐藏]" {
t.Fatalf("unsafe audit body: %v", body)
}
c.JSON(200, gin.H{"code": 0})
})
path := "/api/integration/sms/aliyun/send"
request := httptest.NewRequest("POST", path, strings.NewReader(`{"phone":"+8613800138000","params":{"code":"987654"}}`))
request.Header.Set("Content-Type", "application/json")
engine.ServeHTTP(httptest.NewRecorder(), request)
for _, value := range []string{"13800138000", "987654"} {
if strings.Contains(output.String(), value) {
t.Fatal("SMS content leaked into access log")
}
}
if !routecatalog.ShouldAudit("POST", path) {
t.Fatal("send route is not audited")
}
}
func TestSMSConfigSecretsAreRedacted(t *testing.T) {
text := redactJSON([]byte(`{"config":{"access_key_secret":"ali-value","secret_id":"tc-id-value","secret_key":"tc-value"}}`), "application/json", 4096)
for _, secret := range []string{"ali-value", "tc-id-value", "tc-value"} {
if strings.Contains(text, secret) {
t.Fatalf("secret leaked: %s", text)
}
}
}