package v1 import ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) type CustomRoleHandlerTestSuite struct { suite.Suite db *gorm.DB handler *CustomRoleHandler account *model.Account } func (s *CustomRoleHandlerTestSuite) SetupSuite() { gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Silent), }) s.Require().NoError(err) s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.User{}, &model.AccountUser{}, &model.CustomRole{}, &model.Audit{})) s.db = db repo := repository.NewCustomRoleRepo(db) svc := service.NewCustomRoleService(repo) auditSvc := service.NewAuditService(repository.NewAuditRepo(db)) s.handler = NewCustomRoleHandler(svc).WithAuditService(auditSvc) s.account = &model.Account{Name: "test-custom-role-account"} s.Require().NoError(db.Create(s.account).Error) } func (s *CustomRoleHandlerTestSuite) TearDownSuite() { if s.db != nil { sqlDB, _ := s.db.DB() sqlDB.Close() } } func TestCustomRoleHandlerSuite(t *testing.T) { suite.Run(t, new(CustomRoleHandlerTestSuite)) } func (s *CustomRoleHandlerTestSuite) SetupTest() { s.Require().NoError(s.db.Exec("DELETE FROM audits").Error) s.Require().NoError(s.db.Exec("DELETE FROM account_users").Error) s.Require().NoError(s.db.Exec("DELETE FROM users").Error) s.Require().NoError(s.db.Exec("DELETE FROM custom_roles").Error) } func (s *CustomRoleHandlerTestSuite) TestList_Success() { r := gin.New() r.GET("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.List)) s.Require().NoError(s.db.Create(&model.CustomRole{AccountID: s.account.ID, Name: "Supervisor", Permissions: `["conversation_manage"]`}).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload []map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Require().Len(payload, 1) s.Equal("Supervisor", payload[0]["name"]) s.NotContains(payload[0], "data") s.NotContains(payload[0], "success") } func (s *CustomRoleHandlerTestSuite) TestCreate_BadRequest_EmptyBody() { r := gin.New() r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.Create)) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestCreate_BadRequest_RequiresEnvelope() { r := gin.New() r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.Create)) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(`{"name":"raw-role","permissions":[]}`)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestGet_BadRequest_InvalidID() { r := gin.New() r.GET("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Get)) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/abc", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestUpdate_BadRequest_InvalidID() { r := gin.New() r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Update)) w := httptest.NewRecorder() req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/abc", s.account.ID), nil) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestUpdate_BadRequest_RequiresEnvelope() { role := &model.CustomRole{AccountID: s.account.ID, Name: "raw-update", Permissions: `[]`} s.Require().NoError(s.db.Create(role).Error) r := gin.New() r.PATCH("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Update)) w := httptest.NewRecorder() req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), bytes.NewBufferString(`{"name":"raw-update-edited","permissions":[]}`)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestDelete_BadRequest_InvalidID() { r := gin.New() r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Delete)) w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/abc", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestCreate_Success() { r := gin.New() r.POST("/api/v1/accounts/:account_id/custom_roles", func(c *gin.Context) { c.Set("account_id", uint(s.account.ID)) c.Set("role", "administrator") s.handler.Create(c) }) w := httptest.NewRecorder() body := `{"custom_role":{"name":"test-role","permissions":["conversation_manage","contact_manage"]}}` req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(body)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Equal("test-role", payload["name"]) s.Equal([]interface{}{"conversation_manage", "contact_manage"}, payload["permissions"]) s.NotContains(payload, "data") } func (s *CustomRoleHandlerTestSuite) TestChatwootPermissionSetCreateUpdateListShowParity() { chatwootPermissions := []string{ "conversation_manage", "conversation_unassigned_manage", "conversation_participating_manage", "contact_manage", "report_manage", "knowledge_base_manage", } r := gin.New() r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.Create)) r.GET("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.List)) r.GET("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Get)) r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Update)) createBody := fmt.Sprintf(`{"custom_role":{"name":"chatwoot-full-permissions","description":"all enterprise permissions","permissions":%s}}`, mustJSONForCustomRoleTest(s.T(), chatwootPermissions)) createW := httptest.NewRecorder() createReq, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(createBody)) createReq.Header.Set("Content-Type", "application/json") r.ServeHTTP(createW, createReq) s.Require().Equal(http.StatusOK, createW.Code) var created map[string]any s.Require().NoError(json.Unmarshal(createW.Body.Bytes(), &created)) s.Equal("chatwoot-full-permissions", created["name"]) s.Equal("all enterprise permissions", created["description"]) s.Equal(toInterfaceStrings(chatwootPermissions), created["permissions"]) s.NotContains(created, "data") s.NotContains(created, "success") roleID := uint(created["id"].(float64)) showW := httptest.NewRecorder() showReq, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, roleID), nil) r.ServeHTTP(showW, showReq) s.Require().Equal(http.StatusOK, showW.Code) var shown map[string]any s.Require().NoError(json.Unmarshal(showW.Body.Bytes(), &shown)) s.Equal(toInterfaceStrings(chatwootPermissions), shown["permissions"]) listW := httptest.NewRecorder() listReq, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil) r.ServeHTTP(listW, listReq) s.Require().Equal(http.StatusOK, listW.Code) var listed []map[string]any s.Require().NoError(json.Unmarshal(listW.Body.Bytes(), &listed)) s.Require().Len(listed, 1) s.Equal(toInterfaceStrings(chatwootPermissions), listed[0]["permissions"]) updateBody := `{"custom_role":{"name":"chatwoot-cleared-permissions","description":"","permissions":[]}}` updateW := httptest.NewRecorder() updateReq, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, roleID), bytes.NewBufferString(updateBody)) updateReq.Header.Set("Content-Type", "application/json") r.ServeHTTP(updateW, updateReq) s.Require().Equal(http.StatusOK, updateW.Code) var updated map[string]any s.Require().NoError(json.Unmarshal(updateW.Body.Bytes(), &updated)) s.Equal("chatwoot-cleared-permissions", updated["name"]) s.Equal("", updated["description"]) s.Empty(updated["permissions"]) } func (s *CustomRoleHandlerTestSuite) TestGet_Success() { // Create a custom role first role := &model.CustomRole{AccountID: s.account.ID, Name: "get-test-role", Permissions: `["report_manage"]`} s.Require().NoError(s.db.Create(role).Error) r := gin.New() r.GET("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Get)) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Equal([]interface{}{"report_manage"}, payload["permissions"]) } func (s *CustomRoleHandlerTestSuite) TestUpdate_Success() { role := &model.CustomRole{AccountID: s.account.ID, Name: "update-test-role", Description: "old description", Permissions: `["report_manage"]`} s.Require().NoError(s.db.Create(role).Error) r := gin.New() r.PATCH("/api/v1/accounts/:account_id/custom_roles/:id", func(c *gin.Context) { c.Set("account_id", uint(s.account.ID)) c.Set("role", "administrator") s.handler.Update(c) }) w := httptest.NewRecorder() body := `{"custom_role":{"name":"updated-role","description":"","permissions":["knowledge_base_manage"]}}` req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), bytes.NewBufferString(body)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload map[string]interface{} s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Equal("updated-role", payload["name"]) s.Equal("", payload["description"]) s.Equal([]interface{}{"knowledge_base_manage"}, payload["permissions"]) } func (s *CustomRoleHandlerTestSuite) TestDelete_Success() { role := &model.CustomRole{AccountID: s.account.ID, Name: "delete-test-role", Permissions: `["conversation_manage"]`} s.Require().NoError(s.db.Create(role).Error) user := &model.User{AccountID: s.account.ID, Name: "Role User", Email: "role-user@example.com", Password: "pw", Active: true} s.Require().NoError(s.db.Create(user).Error) s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: user.ID, Role: "agent", CustomRoleID: role.ID}).Error) r := gin.New() r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", func(c *gin.Context) { c.Set("account_id", uint(s.account.ID)) c.Set("role", "administrator") s.handler.Delete(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) s.Empty(w.Body.String()) var au model.AccountUser s.Require().NoError(s.db.Where("account_id = ? AND user_id = ?", s.account.ID, user.ID).First(&au).Error) s.Equal(uint(0), au.CustomRoleID) s.Equal("agent", au.Role) } func (s *CustomRoleHandlerTestSuite) TestCreate_InvalidPermission() { r := gin.New() r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.Create)) w := httptest.NewRecorder() body := `{"custom_role":{"name":"bad-role","permissions":["conversation_delete"]}}` req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(body)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusBadRequest, w.Code) } func (s *CustomRoleHandlerTestSuite) TestList_NonAdminDenied() { r := gin.New() r.GET("/api/v1/accounts/:account_id/custom_roles", func(c *gin.Context) { c.Set("account_id", s.account.ID) c.Set("role", "agent") s.handler.List(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusUnauthorized, w.Code) } func (s *CustomRoleHandlerTestSuite) TestMutations_WriteAuditEntries() { r := gin.New() r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAuditContext(s.account.ID, 77, s.handler.Create)) r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAuditContext(s.account.ID, 77, s.handler.Update)) r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAuditContext(s.account.ID, 77, s.handler.Delete)) createBody := `{"custom_role":{"name":"audit-role","permissions":["conversation_manage"]}}` createReq, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(createBody)) createReq.Header.Set("Content-Type", "application/json") createReq.Header.Set("X-Request-ID", "audit-create-req") createReq.RemoteAddr = "203.0.113.20:1234" createW := httptest.NewRecorder() r.ServeHTTP(createW, createReq) s.Require().Equal(http.StatusOK, createW.Code) var createResp struct { ID uint `json:"id"` } s.Require().NoError(json.Unmarshal(createW.Body.Bytes(), &createResp)) roleID := createResp.ID updateBody := `{"custom_role":{"name":"audit-role-updated","permissions":["contact_manage"]}}` updateReq, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, roleID), bytes.NewBufferString(updateBody)) updateReq.Header.Set("Content-Type", "application/json") updateW := httptest.NewRecorder() r.ServeHTTP(updateW, updateReq) s.Require().Equal(http.StatusOK, updateW.Code) deleteReq, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, roleID), nil) deleteW := httptest.NewRecorder() r.ServeHTTP(deleteW, deleteReq) s.Require().Equal(http.StatusOK, deleteW.Code) var audits []model.Audit s.Require().NoError(s.db.Order("id ASC").Find(&audits).Error) s.Require().Len(audits, 3) for _, audit := range audits { s.Equal(s.account.ID, *audit.AccountID) s.Equal("Account", audit.AssociatedType) s.Equal(s.account.ID, *audit.AssociatedID) s.Equal(uint(77), *audit.UserID) s.Equal("User", audit.UserType) s.Equal("CustomRole", audit.AuditableType) s.Equal(roleID, audit.AuditableID) s.NotEmpty(audit.AuditedChanges) } s.Equal("create", audits[0].Action) s.Equal("audit-create-req", audits[0].RequestUUID) s.Equal("update", audits[1].Action) s.Equal("destroy", audits[2].Action) } func withCustomRoleAuditContext(accountID uint, userID uint, h gin.HandlerFunc) gin.HandlerFunc { return func(c *gin.Context) { c.Set("account_id", accountID) c.Set("user_id", userID) c.Set("role", "administrator") h(c) } } func withCustomRoleAdminContext(accountID uint, h gin.HandlerFunc) gin.HandlerFunc { return func(c *gin.Context) { c.Set("account_id", accountID) c.Set("role", "administrator") h(c) } } func mustJSONForCustomRoleTest(t *testing.T, value any) string { t.Helper() data, err := json.Marshal(value) if err != nil { t.Fatalf("failed to marshal custom role test value: %v", err) } return string(data) } func toInterfaceStrings(values []string) []any { out := make([]any, 0, len(values)) for _, value := range values { out = append(out, value) } return out }