Files

111 lines
3.5 KiB
Go

// audit_test.go Day 29:审计拦截中间件(who/what/when 留痕)。
package middleware
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
"go-sms/internal/service/audit"
)
// newAudit29 内存库审计环境。
func newAudit29(t *testing.T) (*gin.Engine, *gorm.DB, string) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&entity.SystemOperateLog{}); err != nil {
t.Fatal(err)
}
gin.SetMode(gin.TestMode)
r := gin.New()
tok, _ := SignAccessToken("sec", 7, "admin", "admin", time.Minute)
protected := r.Group("/api/v1", AuthJWT("sec"), AuditTrail(audit.NewService(db)))
protected.POST("/accounts/:id/recharge", func(c *gin.Context) { c.Status(http.StatusOK) })
protected.GET("/accounts", func(c *gin.Context) { c.Status(http.StatusOK) })
protected.GET("/accounts/export", func(c *gin.Context) { c.Status(http.StatusOK) })
protected.POST("/accounts", func(c *gin.Context) { c.Status(http.StatusBadRequest) })
return r, db, tok
}
// countLogs 库内日志条数(可选过滤)。
func countLogs(t *testing.T, db *gorm.DB) []entity.SystemOperateLog {
t.Helper()
var logs []entity.SystemOperateLog
if err := db.Order("id").Find(&logs).Error; err != nil {
t.Fatal(err)
}
return logs
}
// TestAuditTrail_WritesAreLogged 验收:写操作 100% 留痕(who/what/when)。
func TestAuditTrail_WritesAreLogged(t *testing.T) {
r, db, tok := newAudit29(t)
// POST 200 → 留痕
req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/2/recharge", nil)
req.Header.Set("Authorization", "Bearer "+tok)
r.ServeHTTP(httptest.NewRecorder(), req)
logs := countLogs(t, db)
if len(logs) != 1 {
t.Fatalf("写操作应留痕 1 条, got %d", len(logs))
}
l := logs[0]
if l.Operator != "admin" || l.AccountID != 7 {
t.Fatalf("who 异常: %q/%d", l.Operator, l.AccountID)
}
if l.Module != "account" || l.Action != "recharge:post" || l.Target != "2" {
t.Fatalf("what 异常: %s/%s/%s", l.Module, l.Action, l.Target)
}
if l.CreatedAt.IsZero() {
t.Fatal("when(created_at) 异常")
}
if l.Detail == "" {
t.Fatal("detail 应含方法/路径/状态摘要")
}
}
// TestAuditTrail_SkipRules GET 普通不留;GET export 留;失败请求不留;未认证不留。
func TestAuditTrail_SkipRules(t *testing.T) {
r, db, tok := newAudit29(t)
hit := func(method, path, token string) {
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
r.ServeHTTP(httptest.NewRecorder(), req)
}
hit(http.MethodGet, "/api/v1/accounts", tok) // 普通 GET:不留
hit(http.MethodPost, "/api/v1/accounts", tok) // 400:不留
hit(http.MethodPost, "/api/v1/accounts/2/recharge", "") // 401:不留
hit(http.MethodGet, "/api/v1/accounts/export", tok) // 导出 GET:留
logs := countLogs(t, db)
if len(logs) != 1 {
t.Fatalf("应仅导出留痕 1 条, got %d", len(logs))
}
if logs[0].Action != "export:get" {
t.Fatalf("导出动作 = %s", logs[0].Action)
}
}
// TestAuditTrail_NilRecorder 降级直通。
func TestAuditTrail_NilRecorder(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.POST("/x", AuditTrail(nil), func(c *gin.Context) { c.JSON(http.StatusOK, json.RawMessage("{}")) })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", nil))
if w.Code != http.StatusOK {
t.Fatalf("nil recorder 应直通, got %d", w.Code)
}
}