feat(audit): align chatwoot audit log payloads

This commit is contained in:
2026-06-05 10:21:15 +08:00
parent c00d313576
commit 3f8f04d65a
5 changed files with 250 additions and 28 deletions
+64 -7
View File
@@ -6,12 +6,14 @@ import (
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
applogger "github.com/gochat/gochat/pkg/logger"
"github.com/gochat/gochat/pkg/pagination"
"github.com/gochat/gochat/pkg/response"
)
const auditLogsPerPage = 25
// AuditHandler handles audit log listing and retrieval.
// Reference: Chatwoot enterprise audit logs controller + P2B M11 spec
type AuditHandler struct {
@@ -32,20 +34,29 @@ func (h *AuditHandler) List(c *gin.Context) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isAuditAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
pg := pagination.Parse(c)
page := parseAuditPage(c.Query("page"))
action := c.Query("action")
auditableType := c.Query("auditable_type")
audits, total, svcErr := h.svc.ListByAccount(c.Request.Context(), accountID, action, auditableType, pg.Page, pg.PerPage)
audits, total, svcErr := h.svc.ListByAccount(c.Request.Context(), accountID, action, auditableType, page, auditLogsPerPage)
if svcErr != nil {
applogger.L().Errorf("AuditHandler.List account=%d: %v", accountID, svcErr)
handleServiceError(c, svcErr)
return
}
response.OKWithMeta(c, toInterfaceSlice(audits), pg.Page, pg.PerPage, total)
c.JSON(http.StatusOK, gin.H{
"per_page": auditLogsPerPage,
"total_entries": total,
"current_page": page,
"audit_logs": serializeAuditLogs(audits),
})
}
// Get retrieves a single audit log entry by ID.
@@ -56,6 +67,10 @@ func (h *AuditHandler) Get(c *gin.Context) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isAuditAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
@@ -63,14 +78,14 @@ func (h *AuditHandler) Get(c *gin.Context) {
return
}
audit, svcErr := h.svc.GetByID(c.Request.Context(), uint(id))
audit, svcErr := h.svc.GetByIDForAccount(c.Request.Context(), accountID, uint(id))
if svcErr != nil {
applogger.L().Errorf("AuditHandler.Get id=%d: %v", id, svcErr)
handleServiceError(c, svcErr)
return
}
response.OK(c, audit)
c.JSON(http.StatusOK, serializeAuditLog(*audit))
}
// RegisterAuditRoutes registers audit log routes on a gin.RouterGroup.
@@ -80,4 +95,46 @@ func RegisterAuditRoutes(rg *gin.RouterGroup, h *AuditHandler) {
audits.GET("/", h.List)
audits.GET("/:id", h.Get)
}
}
}
func isAuditAdmin(c *gin.Context) bool {
role := getRole(c)
return role == "administrator" || role == "super_admin"
}
func parseAuditPage(raw string) int {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return 1
}
return page
}
func serializeAuditLogs(audits []model.Audit) []gin.H {
items := make([]gin.H, 0, len(audits))
for _, audit := range audits {
items = append(items, serializeAuditLog(audit))
}
return items
}
func serializeAuditLog(audit model.Audit) gin.H {
return gin.H{
"id": audit.ID,
"auditable_id": audit.AuditableID,
"auditable_type": audit.AuditableType,
"auditable": nil,
"associated_id": audit.AssociatedID,
"associated_type": audit.AssociatedType,
"user_id": audit.UserID,
"user_type": audit.UserType,
"username": audit.Username,
"action": audit.Action,
"audited_changes": audit.AuditedChanges,
"version": audit.Version,
"comment": audit.Comment,
"request_uuid": audit.RequestUUID,
"created_at": audit.CreatedAt.Unix(),
"remote_address": audit.RemoteAddress,
}
}
+118 -5
View File
@@ -1,10 +1,12 @@
package v1
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
@@ -52,24 +54,135 @@ func TestAuditHandlerSuite(t *testing.T) {
suite.Run(t, new(AuditHandlerTestSuite))
}
func (s *AuditHandlerTestSuite) TestList_Success() {
func (s *AuditHandlerTestSuite) SetupTest() {
s.Require().NoError(s.db.Exec("DELETE FROM audits").Error)
}
func (s *AuditHandlerTestSuite) TestList_ChatwootPayloadFiltersAndSerializer() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/audit_logs", s.handler.List)
r.GET("/api/v1/accounts/:account_id/audit_logs", withAuditRole("administrator", s.handler.List))
createdAt := time.Unix(1710000000, 0).UTC()
userID := uint(42)
associatedID := s.account.ID
version := 3
audit := &model.Audit{
AccountID: &s.account.ID,
UserID: &userID,
AuditableType: "Conversation",
AuditableID: 777,
Action: "update",
AuditedChanges: json.RawMessage(`{"status":["open","resolved"]}`),
AssociatedType: "Account",
AssociatedID: &associatedID,
Username: "admin@example.com",
RemoteAddress: "203.0.113.10",
RequestUUID: "req-123",
Version: &version,
Comment: "status changed",
UserType: "User",
CreatedAt: createdAt,
}
s.Require().NoError(s.db.Create(audit).Error)
otherAccount := &model.Account{Name: "other-audit-account"}
s.Require().NoError(s.db.Create(otherAccount).Error)
s.Require().NoError(s.db.Create(&model.Audit{
AccountID: &otherAccount.ID,
AuditableType: "Conversation",
AuditableID: 999,
Action: "update",
AuditedChanges: json.RawMessage(`{}`),
}).Error)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/audit_logs?page=1&per_page=100&action=update&auditable_type=Conversation", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var body map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &body))
assert.NotContains(s.T(), body, "success")
assert.Equal(s.T(), float64(25), body["per_page"])
assert.Equal(s.T(), float64(1), body["current_page"])
assert.Equal(s.T(), float64(1), body["total_entries"])
logs := body["audit_logs"].([]any)
s.Require().Len(logs, 1)
log := logs[0].(map[string]any)
assert.Equal(s.T(), float64(audit.ID), log["id"])
assert.Equal(s.T(), float64(777), log["auditable_id"])
assert.Equal(s.T(), "Conversation", log["auditable_type"])
assert.Contains(s.T(), log, "auditable")
assert.Nil(s.T(), log["auditable"])
assert.Equal(s.T(), float64(s.account.ID), log["associated_id"])
assert.Equal(s.T(), "Account", log["associated_type"])
assert.Equal(s.T(), float64(userID), log["user_id"])
assert.Equal(s.T(), "User", log["user_type"])
assert.Equal(s.T(), "admin@example.com", log["username"])
assert.Equal(s.T(), "update", log["action"])
assert.Equal(s.T(), float64(version), log["version"])
assert.Equal(s.T(), "status changed", log["comment"])
assert.Equal(s.T(), "req-123", log["request_uuid"])
assert.Equal(s.T(), float64(createdAt.Unix()), log["created_at"])
assert.Equal(s.T(), "203.0.113.10", log["remote_address"])
}
func (s *AuditHandlerTestSuite) TestList_AssociatedAccountScopeAndFixedPageSize() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/audit_logs", withAuditRole("administrator", s.handler.List))
associatedID := s.account.ID
for i := 0; i < 26; i++ {
s.Require().NoError(s.db.Create(&model.Audit{
AuditableType: "Conversation",
AuditableID: uint(i + 1),
Action: "update",
AuditedChanges: json.RawMessage(`{}`),
AssociatedType: "Account",
AssociatedID: &associatedID,
CreatedAt: time.Unix(int64(1710000000+i), 0),
}).Error)
}
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/audit_logs?page=2&per_page=1", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var body map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &body))
assert.Equal(s.T(), float64(25), body["per_page"])
assert.Equal(s.T(), float64(2), body["current_page"])
assert.Equal(s.T(), float64(26), body["total_entries"])
assert.Len(s.T(), body["audit_logs"].([]any), 1)
}
func (s *AuditHandlerTestSuite) TestList_UnauthorizedForAgent() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/audit_logs", withAuditRole("agent", s.handler.List))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/audit_logs", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
assert.Equal(s.T(), http.StatusUnauthorized, w.Code)
}
func (s *AuditHandlerTestSuite) TestGet_BadRequest_InvalidID() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/audit_logs/:id", s.handler.Get)
r.GET("/api/v1/accounts/:account_id/audit_logs/:id", withAuditRole("administrator", s.handler.Get))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/audit_logs/abc", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
}
func withAuditRole(role string, h gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("role", role)
h(c)
}
}