fix: tighten password and surface persistence errors

This commit is contained in:
Your Name
2026-05-28 20:38:34 +08:00
parent caad1aba0c
commit 9cc5892565
7 changed files with 228 additions and 11 deletions

View File

@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"io"
"log"
"time"
"github.com/gin-gonic/gin"
@@ -87,10 +88,16 @@ func (m *OperationLogMiddleware) Record() gin.HandlerFunc {
UserAgent: c.Request.UserAgent(),
}
if m == nil || m.repo == nil {
return
}
go func(entry *domain.OperationLog) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_ = m.repo.Create(ctx, entry)
if err := m.repo.Create(ctx, entry); err != nil {
log.Printf("[operation-log] create failed: %v", err)
}
}(logEntry)
}
}

View File

@@ -0,0 +1,59 @@
package middleware
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestOperationLogRecord_AllowsNilRepository(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use((&OperationLogMiddleware{}).Record())
router.POST("/operation-log", func(c *gin.Context) {
c.JSON(http.StatusCreated, gin.H{"ok": true})
})
body := bytes.NewBufferString(`{"password":"secret","token":"abc"}`)
req := httptest.NewRequest(http.MethodPost, "/operation-log", body)
req.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
if recorder.Code != http.StatusCreated {
t.Fatalf("unexpected status: got %d want %d", recorder.Code, http.StatusCreated)
}
}
func TestSanitizeParams_MasksSensitiveFields(t *testing.T) {
sanitized := sanitizeParams([]byte(`{"password":"secret","nested":"ok","token":"abc"}`))
var payload map[string]any
if err := json.Unmarshal([]byte(sanitized), &payload); err != nil {
t.Fatalf("sanitized payload should remain valid json: %v", err)
}
if payload["password"] != "***" {
t.Fatalf("password should be masked, got: %#v", payload["password"])
}
if payload["token"] != "***" {
t.Fatalf("token should be masked, got: %#v", payload["token"])
}
}
func TestSanitizeParams_FallbacksForNonJSONPayload(t *testing.T) {
longText := strings.Repeat("x", 600)
sanitized := sanitizeParams([]byte(longText))
if len(sanitized) != 503 {
t.Fatalf("expected truncated fallback length 503, got %d", len(sanitized))
}
if !strings.HasSuffix(sanitized, "...") {
t.Fatalf("expected truncated fallback to end with ellipsis: %q", sanitized[len(sanitized)-3:])
}
}