waflog.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package admin
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. adminApi "github.com/go-nunu/nunu-layout-advanced/api/v1/admin"
  8. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  9. adminRep "github.com/go-nunu/nunu-layout-advanced/internal/repository/admin"
  10. "github.com/go-nunu/nunu-layout-advanced/internal/repository/api/waf"
  11. "github.com/go-nunu/nunu-layout-advanced/internal/service"
  12. "github.com/go-nunu/nunu-layout-advanced/pkg/rabbitmq"
  13. amqp "github.com/rabbitmq/amqp091-go"
  14. "go.uber.org/zap"
  15. "strings"
  16. )
  17. type WafLogService interface {
  18. GetWafLog(ctx context.Context, id int64) (*model.WafLog, error)
  19. GetWafLogList(ctx context.Context, req adminApi.SearchWafLogParams) (*v1.PaginatedResponse[model.WafLog], error)
  20. AddWafLog(ctx context.Context, req adminApi.WafLog) error
  21. BatchAddWafLog(ctx context.Context, reqs []*adminApi.WafLog) error
  22. PublishIpWafLogTask(ctx context.Context, req adminApi.WafLog)
  23. }
  24. func NewWafLogService(
  25. service *service.Service,
  26. wafLogRepository adminRep.WafLogRepository,
  27. globalLimitRepository waf.GlobalLimitRepository,
  28. mq *rabbitmq.RabbitMQ,
  29. ) WafLogService {
  30. return &wafLogService{
  31. Service: service,
  32. wafLogRepository: wafLogRepository,
  33. globalLimitRepository: globalLimitRepository,
  34. mq : mq,
  35. }
  36. }
  37. type wafLogService struct {
  38. *service.Service
  39. wafLogRepository adminRep.WafLogRepository
  40. globalLimitRepository waf.GlobalLimitRepository
  41. mq *rabbitmq.RabbitMQ
  42. }
  43. var ApiDescriptionMap = map[string]string{
  44. "/webForward/get": "获取web详情",
  45. "/webForward/getList" : "获取web列表",
  46. "/webForward/add" : "添加web",
  47. "/webForward/update" : "更新web",
  48. "/webForward/delete" : "删除web",
  49. "/tcpForward/add" : "添加tcp",
  50. "/tcpForward/update" : "更新tcp",
  51. "/tcpForward/delete" : "删除tcp",
  52. "/tcpForward/getList" : "获取tcp列表",
  53. "/tcpForward/get" : "获取tcp详情",
  54. "/udpForward/add" : "添加udp",
  55. "/udpForward/update" : "更新udp",
  56. "/udpForward/delete" : "删除udp",
  57. "/udpForward/getList" : "获取udp列表",
  58. "/udpForward/get" : "获取udp详情",
  59. "/globalLimit/add" : "添加实例",
  60. "/globalLimit/edit" : "编辑实例",
  61. "/globalLimit/delete" : "删除实例",
  62. "/allowAndDeny/get" : "获取黑白名单详情",
  63. "/allowAndDeny/getList" : "获取黑白名单列表",
  64. "/allowAndDeny/add" : "添加黑白名单",
  65. "/allowAndDeny/edit" : "编辑黑白名单",
  66. "/allowAndDeny/delete" : "删除黑白名单",
  67. "/cc/getList" : "获取CC列表",
  68. "/cc/editState" : "删除CC黑名单",
  69. "/ccIpList/getList" : "获取CC白名单列表",
  70. "/ccIpList/add" : "添加CC白名单",
  71. "/ccIpList/edit" : "编辑CC白名单",
  72. "/ccIpList/delete" : "删除CC白名单",
  73. }
  74. func (s *wafLogService) getFirstPathSegment(path string) (segment []string, ok bool) {
  75. // 1. 为了统一处理,先去掉路径最前面的 "/"
  76. // 这样 "/v1/admin" 会变成 "v1/admin",而 "v1/admin" 保持不变
  77. trimmedPath := strings.TrimPrefix(path, "/")
  78. // 如果去掉 "/" 后字符串为空(比如原路径是 "/" 或 ""),则无法提取
  79. if trimmedPath == "" {
  80. return nil, false
  81. }
  82. // 2. 使用 "/" 作为分隔符来切割字符串
  83. // "v1/admin/menus" 会被切割成一个字符串切片 (slice): ["v1", "admin", "menus"]
  84. parts := strings.Split(trimmedPath, "/")
  85. // 3. 只要切片不为空,第一个元素就是我们需要的值
  86. // len(parts) > 0 这个检查可以保证程序不会因为空切片而出错
  87. if len(parts) > 0 {
  88. return parts, true
  89. }
  90. return nil, false
  91. }
  92. func (s *wafLogService) GetWafLog(ctx context.Context, id int64) (*model.WafLog, error) {
  93. return s.wafLogRepository.GetWafLog(ctx, id)
  94. }
  95. func (s *wafLogService) GetWafLogList(ctx context.Context,req adminApi.SearchWafLogParams) (*v1.PaginatedResponse[model.WafLog], error) {
  96. return s.wafLogRepository.GetWafLogList(ctx, req)
  97. }
  98. func (s *wafLogService) AddWafLog(ctx context.Context, req adminApi.WafLog) error {
  99. if req.Api != "" {
  100. api := strings.TrimPrefix(req.Api, "/v1")
  101. if _, ok := ApiDescriptionMap[api]; ok {
  102. req.ApiName = ApiDescriptionMap[api]
  103. }
  104. apiType, ok := s.getFirstPathSegment(req.Api)
  105. if ok {
  106. req.ApiType = apiType[len(apiType)-1]
  107. }
  108. }
  109. userInfo, err := s.globalLimitRepository.GetUserInfo(ctx, int64(req.Uid))
  110. if err != nil {
  111. return err
  112. }
  113. req.Name = userInfo.Username
  114. extraData, err := json.Marshal(req.ExtraData)
  115. if err != nil {
  116. return err
  117. }
  118. return s.wafLogRepository.AddWafLog(ctx, &model.WafLog{
  119. Uid: req.Uid,
  120. Name: req.Name,
  121. RequestIp: req.RequestIp,
  122. RuleId: req.RuleId,
  123. HostId: req.HostId,
  124. UserAgent: req.UserAgent,
  125. Api: req.Api,
  126. ApiType: req.ApiType,
  127. ApiName: req.ApiName,
  128. ExtraData: extraData,
  129. })
  130. }
  131. func (s *wafLogService) BatchAddWafLog(ctx context.Context, reqs []*adminApi.WafLog) error {
  132. if len(reqs) == 0 {
  133. return nil
  134. }
  135. wafLogs := make([]*model.WafLog, 0, len(reqs))
  136. for _, req := range reqs {
  137. if req.Api != "" {
  138. api := strings.TrimPrefix(req.Api, "/v1")
  139. if _, ok := ApiDescriptionMap[api]; ok {
  140. req.ApiName = ApiDescriptionMap[api]
  141. }
  142. apiType, ok := s.getFirstPathSegment(req.Api)
  143. if ok {
  144. req.ApiType = apiType[len(apiType)-1]
  145. }
  146. }
  147. userInfo, err := s.globalLimitRepository.GetUserInfo(ctx, int64(req.Uid))
  148. if err != nil {
  149. s.Logger.Error("获取用户信息失败", zap.Error(err), zap.Int("uid", req.Uid))
  150. continue
  151. }
  152. req.Name = userInfo.Username
  153. extraData, err := json.Marshal(req.ExtraData)
  154. if err != nil {
  155. s.Logger.Error("序列化额外数据失败", zap.Error(err))
  156. continue
  157. }
  158. wafLogs = append(wafLogs, &model.WafLog{
  159. Uid: req.Uid,
  160. Name: req.Name,
  161. RequestIp: req.RequestIp,
  162. RuleId: req.RuleId,
  163. HostId: req.HostId,
  164. UserAgent: req.UserAgent,
  165. Api: req.Api,
  166. ApiType: req.ApiType,
  167. ApiName: req.ApiName,
  168. ExtraData: extraData,
  169. })
  170. }
  171. // 调用repository层的批量插入方法
  172. return s.wafLogRepository.BatchAddWafLog(ctx, wafLogs)
  173. }
  174. func (s *wafLogService) PublishIpWafLogTask(ctx context.Context, req adminApi.WafLog) {
  175. payload := &req
  176. // Serialize the message
  177. msgBody, err := json.Marshal(payload)
  178. if err != nil {
  179. s.Logger.Error("序列化 WafLog 任务消息失败", zap.Error(err), zap.Int("hostId", payload.HostId), zap.Int("uid", payload.Uid), zap.Any("req", req))
  180. return
  181. }
  182. // Get task configuration
  183. taskCfg, ok := s.mq.GetTaskConfig("waf_log")
  184. if !ok {
  185. s.Logger.Error("无法获取“waf_Log”任务配置")
  186. return
  187. }
  188. // Construct the routing key dynamically based on the action
  189. routingKey := fmt.Sprintf("wafLog.%s", "add")
  190. // Construct the amqp.Publishing message
  191. publishingMsg := amqp.Publishing{
  192. ContentType: "application/json",
  193. Body: msgBody,
  194. DeliveryMode: amqp.Persistent, // Persistent message
  195. }
  196. // Publish the message
  197. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  198. if err != nil {
  199. s.Logger.Error("发布 WafLog 任务消息失败", zap.Error(err), zap.Int("hostId", payload.HostId), zap.Int("uid", payload.Uid), zap.Any("req", req))
  200. } else {
  201. s.Logger.Info("已成功发布 WafLog 任务消息", zap.Int("hostId", payload.HostId), zap.Int("uid", payload.Uid), zap.Any("req", req))
  202. }
  203. }