From 6dfaecddf87f3669a3f0108d2a77313dd18d6190 Mon Sep 17 00:00:00 2001 From: zhaoyixiang Date: Wed, 24 Apr 2024 00:00:10 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat:=20=E9=87=8D=E6=9E=84=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 1 + .../entity/user/AccessTokenResponse.java | 17 +++++ .../configuration/entity/user/User.java | 2 + .../configuration/entity/user/UserFull.java | 67 ++++++++++++++++ .../server/user/login/LoginController.java | 44 +++++++++-- .../server/user/login/LoginService.java | 76 ++++++++++++++++++- 6 files changed, 197 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/realtime/protection/configuration/entity/user/AccessTokenResponse.java create mode 100644 src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java diff --git a/build.gradle b/build.gradle index 4eb220c..63ab739 100644 --- a/build.gradle +++ b/build.gradle @@ -49,6 +49,7 @@ dependencies { implementation 'com.alibaba:easyexcel:3.3.3' implementation 'com.baomidou:dynamic-datasource-spring-boot3-starter:4.3.0' implementation 'com.github.xiaoymin:knife4j-openapi3-jakarta-spring-boot-starter:4.4.0' + implementation 'com.squareup.okhttp3:okhttp:4.12.0' } tasks.named('test') { diff --git a/src/main/java/com/realtime/protection/configuration/entity/user/AccessTokenResponse.java b/src/main/java/com/realtime/protection/configuration/entity/user/AccessTokenResponse.java new file mode 100644 index 0000000..f360ab6 --- /dev/null +++ b/src/main/java/com/realtime/protection/configuration/entity/user/AccessTokenResponse.java @@ -0,0 +1,17 @@ +package com.realtime.protection.configuration.entity.user; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Yixiang Zhao + **/ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class AccessTokenResponse { + private String access_token; + private String token_type; + private int expires_in; +} diff --git a/src/main/java/com/realtime/protection/configuration/entity/user/User.java b/src/main/java/com/realtime/protection/configuration/entity/user/User.java index 687f14f..73cb4f9 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/user/User.java +++ b/src/main/java/com/realtime/protection/configuration/entity/user/User.java @@ -2,9 +2,11 @@ package com.realtime.protection.configuration.entity.user; import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; @Data @AllArgsConstructor +@NoArgsConstructor public class User { private Long userId; diff --git a/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java b/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java new file mode 100644 index 0000000..dc5fd4b --- /dev/null +++ b/src/main/java/com/realtime/protection/configuration/entity/user/UserFull.java @@ -0,0 +1,67 @@ +package com.realtime.protection.configuration.entity.user; + +import java.util.List; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Yixiang Zhao + **/ +public class UserFull { + public String ticket; + public List groups; + public List roles; + public List orgs; + public String mobile; + public String nickName; + public String email; + public String uid; + public String employeeNumber; + public String name; + public List resoures; + + public String getOrgCode() { + if (orgs.size() > 0) { + return orgs.get(0).orgCode; + } + return ""; + } + + public String getRoleKey() { + if (roles.size() > 0) { + return roles.get(0).roleKey; + } + return ""; + } +} + +class Group { + public int groupId; + public int applicationId; + public String groupKey; + public String groupName; + public String groupTag; // Assume it's a JSON String, otherwise it could be List or similar + public String groupRemark; +} + +class Role { + public int roleId; + public int applicationId; + public String roleKey; + public String roleName; + public String roleRemark; + public String roleTag; // Same assumption as above + public List res; // Assuming a Resource class exists + public List resources; // Assuming a Resource class exists +} + +class Org { + public String orgName; + public String orgDescription; + public int orgParentId; + public String orgCode; + public String orgTag; // Same assumption as above + public int orgId; + public String userOrgworkType; +} diff --git a/src/main/java/com/realtime/protection/server/user/login/LoginController.java b/src/main/java/com/realtime/protection/server/user/login/LoginController.java index b69f1b8..e3e161d 100644 --- a/src/main/java/com/realtime/protection/server/user/login/LoginController.java +++ b/src/main/java/com/realtime/protection/server/user/login/LoginController.java @@ -1,11 +1,22 @@ package com.realtime.protection.server.user.login; -import com.realtime.protection.configuration.entity.user.User; -import com.realtime.protection.configuration.response.ResponseResult; -import org.springframework.web.bind.annotation.*; - import javax.security.auth.login.LoginException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.realtime.protection.configuration.entity.user.User; +import com.realtime.protection.configuration.entity.user.UserFull; +import com.realtime.protection.configuration.response.ResponseResult; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; + // Just for example, not in production environment @RestController @RequestMapping("/user") @@ -36,10 +47,29 @@ public class LoginController { @PostMapping("/auth") public ResponseResult auth(@RequestParam("sessionData") String sessionData, - @RequestParam("accessToken") String accessToken, + @Autowired HttpServletRequest request, @RequestParam(value = "scopes", required = false) String scopes) { - return ResponseResult.ok().setMessage("success") - .setData("success", true); + try { + UserFull userFull = loginService.loginWithSSO(sessionData); + if (userFull == null) { + throw new LoginException("登录失败,无法获取用户信息"); + } + // 设置 session + HttpSession session = request.getSession(); + session.setAttribute("user", userFull); + // 返回结果 + return ResponseResult.ok().setMessage("success") + .setData("userId", userFull.uid) + .setData("userName", userFull.name) + .setData("userRole", userFull.getRoleKey()); + } catch (Exception e) { + return ResponseResult.error(e.getMessage()); + } } + @GetMapping("/auth_redirect") + public String authRedirect(@RequestParam(value = "SESSION_DATA", required = false) String sessionData) { + System.out.println("SESSION_DATA: " + sessionData); + return ""; + } } diff --git a/src/main/java/com/realtime/protection/server/user/login/LoginService.java b/src/main/java/com/realtime/protection/server/user/login/LoginService.java index e36afb4..0567b53 100644 --- a/src/main/java/com/realtime/protection/server/user/login/LoginService.java +++ b/src/main/java/com/realtime/protection/server/user/login/LoginService.java @@ -1,11 +1,26 @@ package com.realtime.protection.server.user.login; -import cn.dev33.satoken.stp.StpUtil; -import com.realtime.protection.configuration.entity.user.User; -import org.springframework.stereotype.Service; +import org.apache.logging.log4j.util.Strings; import javax.security.auth.login.LoginException; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.realtime.protection.configuration.entity.user.AccessTokenResponse; +import com.realtime.protection.configuration.entity.user.User; +import com.realtime.protection.configuration.entity.user.UserFull; + +import cn.dev33.satoken.stp.StpUtil; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +import io.micrometer.common.util.StringUtils; + @Service // just for example, not for production environment public class LoginService { @@ -28,4 +43,59 @@ public class LoginService { StpUtil.login(userId); return userId; } + + public UserFull loginWithSSO(String sessionData) throws LoginException { + String accessToken = ""; + // 获取 ACCESS_TOKEN + ObjectMapper objectMapper = new ObjectMapper(); + OkHttpClient client = new OkHttpClient(); + Request request = new Request.Builder() + .url("http://114.243.134.122:9217/passport/accessToken?grant_type=client_credentials") + .header("Authorization", "Basic TlNBRERAWlguT1JHOk14a1hHZ1ltOUNROUE3TCRSOCNLRW02R1pSeEhwd1c2") + .post(okhttp3.internal.Util.EMPTY_REQUEST) + .build(); + try { + Response response = client.newCall(request).execute(); + String rsp = response.body().string(); + try { + AccessTokenResponse atr = objectMapper.readValue(rsp, AccessTokenResponse.class); + accessToken = atr.getAccess_token(); + } catch (Exception e) { + throw new LoginException("解析 ACCESS_TOKEN 失败"); + } + } catch (Exception e) { + e.printStackTrace(); + throw new LoginException("获取 ACCESS_TOKEN 失败,网络请求错误"); + } + if (Strings.isBlank(accessToken)) { + throw new LoginException("获取 ACCESS_TOKEN 失败"); + } + // 校验 SESSION_DATA + RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) + .addFormDataPart("sessionData", sessionData).build(); + request = new Request.Builder() + .url("http://114.243.134.122:9217/passport/accessApplication") + .header("Authorization", "Bearer " + accessToken) + .header("Content-Type", "application/x-www-form-urlencoded") + .post(body) + .build(); + try { + Response response = client.newCall(request).execute(); + String rsp = response.body().string(); + // System.out.println("user: " + rsp); + if (StringUtils.isBlank(rsp)) { + throw new LoginException("解析用户数据为空"); + } + try { + UserFull userFull = objectMapper.readValue(rsp, UserFull.class); + return userFull; + } catch (Exception e) { + e.printStackTrace(); + throw new LoginException("解析 ACCESS_TOKEN 失败"); + } + } catch (Exception e) { + e.printStackTrace(); + throw new LoginException("校验 SESSION_DATA 失败"); + } + } } From 042ce322b48a8bdfa41f71cd39f26d58245cbf04 Mon Sep 17 00:00:00 2001 From: PushM <584406942@qq.com> Date: Wed, 24 Apr 2024 11:20:34 +0800 Subject: [PATCH 2/7] =?UTF-8?q?1=E3=80=81=E6=96=B0=E5=A2=9E=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E8=A7=84=E5=88=99=E5=AE=A1=E6=89=B9=E5=92=8C=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E5=AE=A1=E6=89=B9=EF=BC=8C=E5=8A=A8=E6=80=81=E8=A7=84?= =?UTF-8?q?=E5=88=99=E6=96=B0=E5=A2=9Eaudit=5Fstatus=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dynamicrule/DynamicRuleController.java | 58 +++++++++++++- .../rule/dynamicrule/DynamicRuleMapper.java | 11 +++ .../rule/dynamicrule/DynamicRuleService.java | 77 ++++++++++++++++--- .../resources/mappers/DynamicRuleMapper.xml | 32 ++++++++ .../rule/dynamic/DynamicRuleServiceTest.java | 14 ++++ 5 files changed, 181 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleController.java b/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleController.java index 32b4b9a..73990c8 100644 --- a/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleController.java +++ b/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleController.java @@ -6,7 +6,9 @@ import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; +import java.util.ArrayList; import java.util.List; +import java.util.Map; @RestController @RequestMapping("dynamicrule") @@ -19,7 +21,7 @@ public class DynamicRuleController implements DynamicRuleControllerApi { this.dynamicRuleService = dynamicRuleService; } - // 新增 要关联防护对象!!!! + // @Override @PostMapping("/new") public ResponseResult newDynamicRuleObject(@RequestBody @Valid DynamicRuleObject dynamicRuleObject) { @@ -120,6 +122,58 @@ public class DynamicRuleController implements DynamicRuleControllerApi { //详情查看?? 就是按id查询吧 - //审核?不需要 + /** + * 审批 + */ + @GetMapping("/{id}/audit/{auditStatus}") + public ResponseResult updateDynamicRuleAuditStatus(@PathVariable Integer id, @PathVariable Integer auditStatus) { + if (id <= 0 || auditStatus < 0 || auditStatus > 2) { + return new ResponseResult(400, "id or status is invalid") + .setData("staticRule_id", id) + .setData("success", false); + } + return ResponseResult.ok() + .addDataMap(dynamicRuleService.updateAuditStatus(id, auditStatus)) + .setData("dynamicRule_id", id); + } + + /** + * 批量审批 + */ + @PostMapping("/auditbatch") + public ResponseResult updateDynamicRuleAuditStatusBatch(@RequestBody Map idsWithAuditStatusMap) { + List errorIds = new ArrayList<>(); + for (Map.Entry entry: idsWithAuditStatusMap.entrySet()) { + Integer id = entry.getKey(); + Integer auditStatus = entry.getValue(); + if (id <= 0 || auditStatus < 0 || auditStatus > 2) { + errorIds.add(id); + } + } + if (!errorIds.isEmpty()){ + return new ResponseResult(400, "id or status is invalid") + .setData("staticRule_id", errorIds) + .setData("success", false); + } + + return ResponseResult.ok() + .setData("success", dynamicRuleService.updateAuditStatusBatch(idsWithAuditStatusMap)); + } + + + /** + * 获取统计数据 + */ + @GetMapping("/statistics") + public ResponseResult getStaticRuleStatisticsData(){ + + return ResponseResult.ok() + .setData("dynamic_rule_num", dynamicRuleService.queryDynamicRuleTotalNum(null, null, + null, null)) + .setData("dynamic_rule_used_num", dynamicRuleService.queryUsedDynamicRuleTotalNum()) + .setData("dynamic_rule_audit_num", dynamicRuleService.queryAuditDynamicRuleTotalNum(1)) + .setData("dynamic_rule_unaudit_num", dynamicRuleService.queryAuditDynamicRuleTotalNum(0)); + } + } diff --git a/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleMapper.java b/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleMapper.java index 04b9e73..7d589fb 100644 --- a/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleMapper.java +++ b/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleMapper.java @@ -7,6 +7,7 @@ import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; +import java.util.Map; @Mapper public interface DynamicRuleMapper { @@ -47,4 +48,14 @@ public interface DynamicRuleMapper { List queryDynamicRuleByIds(List ids); Integer queryTaskStatusBydynamicRuleId(Integer dynamicRuleId); + + Integer queryUsedDynamicRuleTotalNum(); + + Integer queryAuditDynamicRuleTotalNum(int auditStatus); + + Integer queryAuditStatusById(Integer dynamicRuleId); + + Boolean updateAuditStatusById(Integer dynamicRuleId, Integer auditStatus); + + void updateAuditStatusByIdBatch(@Param("idWithAuditStatusBatch") Map idWithAuditStatusBatch); } diff --git a/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleService.java b/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleService.java index c034ed6..b864643 100644 --- a/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleService.java +++ b/src/main/java/com/realtime/protection/server/rule/dynamicrule/DynamicRuleService.java @@ -5,11 +5,14 @@ import com.realtime.protection.configuration.entity.defense.template.Template; import com.realtime.protection.configuration.entity.rule.dynamicrule.DynamicRuleObject; import com.realtime.protection.configuration.utils.SqlSessionWrapper; import com.realtime.protection.configuration.utils.enums.StateEnum; +import com.realtime.protection.configuration.utils.enums.audit.AuditStatusValidator; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.function.Function; @Service @@ -73,16 +76,21 @@ public class DynamicRuleService { public void deleteDynamicRuleObject(Integer dynamicRuleId) { //根据任务状态判断能否删除 Integer taskStatus = dynamicRuleMapper.queryTaskStatusBydynamicRuleId(dynamicRuleId); - switch (StateEnum.getStateEnumByNum(taskStatus)){ - case RUNNING: - throw new IllegalArgumentException("使用该动态规则的任务处于运行状态"); - case PAUSED: - throw new IllegalArgumentException("使用该动态规则的任务处于暂停状态"); - default: - break; + if (taskStatus == null){ + dynamicRuleMapper.deleteDynamicRuleObject(dynamicRuleId); + }else{ + switch (StateEnum.getStateEnumByNum(taskStatus)){ + case RUNNING: + throw new IllegalArgumentException("使用该动态规则的任务处于运行状态"); + case PAUSED: + throw new IllegalArgumentException("使用该动态规则的任务处于暂停状态"); + default: + break; + } + //不需要使用 join,在数据库中设置了级联删除 ON DELETE CASCADE,在删除在从父表中删除数据时自动删除子表中的数据 + dynamicRuleMapper.deleteDynamicRuleObject(dynamicRuleId); } - //不需要使用 join,在数据库中设置了级联删除 ON DELETE CASCADE,在删除在从父表中删除数据时自动删除子表中的数据 - dynamicRuleMapper.deleteDynamicRuleObject(dynamicRuleId); + } @@ -177,4 +185,55 @@ public class DynamicRuleService { public List queryDynamicRuleByIds(List ids) { return dynamicRuleMapper.queryDynamicRuleByIds(ids); } + + public Integer queryUsedDynamicRuleTotalNum() { + return dynamicRuleMapper.queryUsedDynamicRuleTotalNum(); + } + + public Integer queryAuditDynamicRuleTotalNum(int auditStatus) { + return dynamicRuleMapper.queryAuditDynamicRuleTotalNum(auditStatus); + } + + public Map updateAuditStatus(Integer id, Integer auditStatus) { + Integer originalAuditStatus = dynamicRuleMapper.queryAuditStatusById(id); + if (originalAuditStatus == null) { + throw new IllegalArgumentException("cannot find audit status of static rule " + id + ", maybe static rule doesn't exist?"); + } + if (!AuditStatusValidator.setOriginal(originalAuditStatus).checkValidate(auditStatus)) { + throw new IllegalArgumentException("invalid audit status"); + } + Boolean success = dynamicRuleMapper.updateAuditStatusById(id, auditStatus); + + Map resultMap = new HashMap<>(); + resultMap.put("success", success); + resultMap.put("audit_status", auditStatus); + return resultMap; + } + + public Object updateAuditStatusBatch(Map idsWithAuditStatusMap) { + Function, Boolean>> updateDynamicRuleAuditStatusFunction = + mapper -> map -> { + if (map == null || map.isEmpty()) { + return false; + } + + Map idWithAuditStatusBatch = new HashMap<>(); + for (Map.Entry item : map.entrySet()) { + idWithAuditStatusBatch.put(item.getKey(), item.getValue()); + if (idWithAuditStatusBatch.size() < 100) { + continue; + } + //mapper指的就是外层函数输入的参数,也就是WhiteListMapper + mapper.updateAuditStatusByIdBatch(idWithAuditStatusBatch); + idWithAuditStatusBatch.clear(); + } + if (!idWithAuditStatusBatch.isEmpty()) { + mapper.updateAuditStatusByIdBatch(idWithAuditStatusBatch); + } + return true; + }; + //实现事务操作 + return sqlSessionWrapper.startBatchSession(DynamicRuleMapper.class, updateDynamicRuleAuditStatusFunction, idsWithAuditStatusMap); + + } } diff --git a/src/main/resources/mappers/DynamicRuleMapper.xml b/src/main/resources/mappers/DynamicRuleMapper.xml index a85f970..ec6e2ec 100644 --- a/src/main/resources/mappers/DynamicRuleMapper.xml +++ b/src/main/resources/mappers/DynamicRuleMapper.xml @@ -101,6 +101,26 @@ where dynamic_rule_id = #{dynamicRuleId} + + update t_dynamic_rule + set audit_status = #{auditStatus} + where dynamic_rule_id = #{dynamicRuleId} + + + + + update t_dynamic_rule + set audit_status = CASE dynamic_rule_id + + WHEN #{id} THEN #{auditStatus} + + ELSE audit_status + END + WHERE dynamic_rule_id IN + + #{id} + + + + + + \ No newline at end of file diff --git a/src/test/java/com/realtime/protection/server/rule/dynamic/DynamicRuleServiceTest.java b/src/test/java/com/realtime/protection/server/rule/dynamic/DynamicRuleServiceTest.java index c48bd61..9976537 100644 --- a/src/test/java/com/realtime/protection/server/rule/dynamic/DynamicRuleServiceTest.java +++ b/src/test/java/com/realtime/protection/server/rule/dynamic/DynamicRuleServiceTest.java @@ -14,7 +14,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.time.LocalDateTime; +import java.util.HashMap; import java.util.List; +import java.util.Map; @SpringBootTest public class DynamicRuleServiceTest extends ProtectionApplicationTests { @@ -136,4 +138,16 @@ public class DynamicRuleServiceTest extends ProtectionApplicationTests { null,null,null,null); System.out.println(num); } + + @Test + void testUpdateDynamicRuleAuditStatusBatch(){ + Map map = new HashMap<>(); + map.put(101, 1); + map.put(102, 2); + map.put(103, 2); + + + System.out.println(dynamicRuleService.updateAuditStatusBatch(map)); + } + } From 10d95b1417bb6ba33e8cb92af890dacf04c35403 Mon Sep 17 00:00:00 2001 From: PushM <584406942@qq.com> Date: Wed, 24 Apr 2024 12:50:14 +0800 Subject: [PATCH 3/7] =?UTF-8?q?1=E3=80=81DynamicRuleObject=E6=96=B0?= =?UTF-8?q?=E5=A2=9EdynamicRuleAuditStatus=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../entity/rule/dynamicrule/DynamicRuleObject.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java b/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java index e764cbf..9f3b60d 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java +++ b/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java @@ -1,5 +1,6 @@ package com.realtime.protection.configuration.entity.rule.dynamicrule; +import com.alibaba.excel.annotation.ExcelIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.realtime.protection.configuration.entity.defense.object.ProtectObject; import io.swagger.v3.oas.annotations.media.Schema; @@ -95,4 +96,10 @@ public class DynamicRuleObject { @JsonProperty("log_rule_id") @Schema(description = "筛选条件-日志规则id", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) private Long logRuleId; + + + @JsonProperty("dynamic_rule_audit_status") + @ExcelIgnore + @Schema(description = "动态规则审核状态(0为未审核,1为已退回,2为审核通过)", example = "2", accessMode = Schema.AccessMode.READ_ONLY) + private Integer dynamicRuleAuditStatus; } From 0526a1322b916752cc2d2c0cb324ca4aff0fcdf7 Mon Sep 17 00:00:00 2001 From: EnderByEndera <707475564@qq.com> Date: Wed, 24 Apr 2024 14:15:08 +0800 Subject: [PATCH 4/7] =?UTF-8?q?1.=20=E5=9C=A8=E9=9D=99=E6=80=81=E5=92=8C?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E5=AE=9E=E4=BD=93=E7=B1=BB=E4=B8=AD=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E9=AA=8C=E8=AF=81=E5=AE=A1=E6=89=B9=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=96=B9=E6=B3=95=EF=BC=8C=E7=94=A8=E4=BA=8E=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E5=AE=A1=E6=89=B9=E7=8A=B6=E6=80=81=E4=B8=AD?= =?UTF-8?q?=202.=20=E5=9C=A8=E4=BB=BB=E5=8A=A1=E7=8A=B6=E6=80=81=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=87=BD=E6=95=B0=E4=B8=AD=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=8A=A8=E9=9D=99=E6=80=81=E8=A7=84=E5=88=99?= =?UTF-8?q?=E5=AE=A1=E6=89=B9=E7=8A=B6=E6=80=81=E6=96=B9=E6=B3=95=EF=BC=8C?= =?UTF-8?q?=E7=94=A8=E4=BB=A5=E6=9B=B4=E6=96=B0=E8=A7=84=E5=88=99=E5=AE=A1?= =?UTF-8?q?=E6=89=B9=E7=8A=B6=E6=80=81=E4=B8=BA=E4=BD=BF=E7=94=A8=E4=B8=AD?= =?UTF-8?q?/=E5=B7=B2=E5=AE=A1=E6=89=B9=203.=20=E5=9C=A8=E9=83=A8=E5=88=86?= =?UTF-8?q?Mapper=E7=9A=84update=E5=87=BD=E6=95=B0=E4=B8=AD=E4=BF=AE?= =?UTF-8?q?=E6=94=B9modify=5Ftime=E4=B8=BANOW()=204.=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E9=83=A8=E5=88=86NullPointerException=20bug=205.=20=E5=9C=A8?= =?UTF-8?q?=E6=96=B0=E5=BB=BA=E4=BB=BB=E5=8A=A1=E6=97=B6=E7=AB=8B=E5=88=BB?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=89=80=E6=9C=89=E8=A7=84=E5=88=99=E7=9A=84?= =?UTF-8?q?=E5=AE=A1=E6=89=B9=E7=8A=B6=E6=80=81=EF=BC=8C=E5=BF=85=E9=A1=BB?= =?UTF-8?q?=E4=B8=BA=E5=B7=B2=E5=AE=A1=E6=89=B9=E6=89=8D=E5=8F=AF=E4=BB=A5?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=88=B0=E4=BB=BB=E5=8A=A1=E4=B8=AD=206.=20?= =?UTF-8?q?=E5=9C=A8taskService=E4=B8=AD=E6=B7=BB=E5=8A=A0=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=8A=A8=E9=9D=99=E6=80=81=E8=A7=84=E5=88=99=E5=AE=A1?= =?UTF-8?q?=E6=89=B9=E7=8A=B6=E6=80=81=E5=87=BD=E6=95=B0=E3=80=82=E8=AF=A5?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E4=B8=8D=E8=83=BD=E7=94=A8=E4=BA=8E=E9=99=A4?= =?UTF-8?q?=E5=B7=B2=E5=AE=A1=E6=89=B9/=E4=BD=BF=E7=94=A8=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E5=85=B6=E4=BB=96=E5=AE=A1=E6=89=B9=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rule/dynamicrule/DynamicRuleObject.java | 16 +- .../rule/staticrule/StaticRuleObject.java | 16 +- .../entity/task/FiveTupleWithMask.java | 4 +- .../entity/task/TaskCommandInfo.java | 6 + .../rule/staticrule/StaticRuleService.java | 8 +- .../protection/server/task/TaskService.java | 154 +++++++++++++++++- .../server/task/status/StateHandler.java | 41 +++-- .../task/status/states/FailedState.java | 4 +- .../task/status/states/GeneratingState.java | 4 +- .../server/task/status/states/PauseState.java | 6 +- .../task/status/states/PendingState.java | 4 +- .../task/status/states/RunningState.java | 6 +- .../server/task/status/states/StopState.java | 4 +- .../resources/mappers/StaticRuleMapper.xml | 3 +- src/main/resources/mappers/TaskMapper.xml | 10 +- .../staticrule/StaticRuleServiceTest.java | 2 +- .../whitelist/WhiteListServiceTest.java | 2 +- 17 files changed, 242 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java b/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java index 9f3b60d..1c77011 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java +++ b/src/main/java/com/realtime/protection/configuration/entity/rule/dynamicrule/DynamicRuleObject.java @@ -3,6 +3,8 @@ package com.realtime.protection.configuration.entity.rule.dynamicrule; import com.alibaba.excel.annotation.ExcelIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.realtime.protection.configuration.entity.defense.object.ProtectObject; +import com.realtime.protection.configuration.utils.enums.audit.AuditStatusEnum; +import com.realtime.protection.configuration.utils.enums.audit.AuditStatusValidator; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; @@ -101,5 +103,17 @@ public class DynamicRuleObject { @JsonProperty("dynamic_rule_audit_status") @ExcelIgnore @Schema(description = "动态规则审核状态(0为未审核,1为已退回,2为审核通过)", example = "2", accessMode = Schema.AccessMode.READ_ONLY) - private Integer dynamicRuleAuditStatus; + private Integer auditStatus; + + public void checkAuditStatusValidate(AuditStatusEnum newAuditStatus) { + if (!List.of(AuditStatusEnum.AUDITED.getNum(), AuditStatusEnum.USING.getNum()).contains(this.getAuditStatus())) { + throw new IllegalArgumentException("规则《" + this.getDynamicRuleName() + "》原审批状态非法"); + } + + if (!AuditStatusValidator + .setOriginal(this.getAuditStatus()) + .checkValidate(newAuditStatus.getNum())) { + throw new IllegalArgumentException("规则《" + this.getDynamicRuleName() + "》审核状态错误"); + } + } } diff --git a/src/main/java/com/realtime/protection/configuration/entity/rule/staticrule/StaticRuleObject.java b/src/main/java/com/realtime/protection/configuration/entity/rule/staticrule/StaticRuleObject.java index e61b1eb..5dc8cda 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/rule/staticrule/StaticRuleObject.java +++ b/src/main/java/com/realtime/protection/configuration/entity/rule/staticrule/StaticRuleObject.java @@ -3,6 +3,8 @@ package com.realtime.protection.configuration.entity.rule.staticrule; import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import com.fasterxml.jackson.annotation.JsonProperty; +import com.realtime.protection.configuration.utils.enums.audit.AuditStatusEnum; +import com.realtime.protection.configuration.utils.enums.audit.AuditStatusValidator; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; @@ -14,6 +16,7 @@ import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDateTime; +import java.util.List; @Data @Builder @@ -47,7 +50,7 @@ public class StaticRuleObject { @JsonProperty("static_rule_audit_status") @ExcelIgnore @Schema(description = "静态规则审核状态(0为未审核,1为已退回,2为审核通过)", example = "2", accessMode = Schema.AccessMode.READ_ONLY) - private Integer staticRuleAuditStatus; + private Integer auditStatus; @JsonProperty("static_rule_create_depart") @ExcelIgnore @Schema(description = "静态规则创建用户所属部门", accessMode = Schema.AccessMode.READ_ONLY) @@ -142,4 +145,15 @@ public class StaticRuleObject { @Schema(description = "频率,最低为1", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) private Integer staticRuleFrequency; + public void checkAuditStatusValidate(AuditStatusEnum newAuditStatus) { + if (!List.of(AuditStatusEnum.AUDITED.getNum(), AuditStatusEnum.USING.getNum()).contains(this.getAuditStatus())) { + throw new IllegalArgumentException("规则《" + this.getStaticRuleName() + "》原审批状态非法"); + } + + if (!AuditStatusValidator + .setOriginal(this.getAuditStatus()) + .checkValidate(newAuditStatus.getNum())) { + throw new IllegalArgumentException("规则《" + this.getStaticRuleName() + "》审核状态错误"); + } + } } diff --git a/src/main/java/com/realtime/protection/configuration/entity/task/FiveTupleWithMask.java b/src/main/java/com/realtime/protection/configuration/entity/task/FiveTupleWithMask.java index cb8f844..b07c3cb 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/task/FiveTupleWithMask.java +++ b/src/main/java/com/realtime/protection/configuration/entity/task/FiveTupleWithMask.java @@ -87,7 +87,9 @@ public class FiveTupleWithMask { public void setProtocolNum() { ProtocolEnum protocol = ProtocolEnum.getProtocolEnumByProtocol(this.protocol); - assert protocol != null; + if (protocol == null) { + return; + } this.protocolNum = protocol.getNumber(); } diff --git a/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java b/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java index d6b060e..a84807d 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java +++ b/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java @@ -140,10 +140,16 @@ public class TaskCommandInfo { } public void setProtocolNum() { + if (this.fiveTupleWithMask == null) { + return; + } this.fiveTupleWithMask.setProtocolNum(); } public void setMask() { + if (this.fiveTupleWithMask == null) { + return; + } this.fiveTupleWithMask.setMask(); } } diff --git a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java index 2d51188..35801fc 100644 --- a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java +++ b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java @@ -57,7 +57,7 @@ public class StaticRuleService { public Integer newStaticRuleObject(StaticRuleObject object) { object.setStaticRuleCreateTime(LocalDateTime.now()); - object.setStaticRuleAuditStatus(0); + object.setAuditStatus(0); /* 待开发:设置静态规则对象的创建用户、用户所属部门等属性 */ @@ -114,7 +114,7 @@ public class StaticRuleService { throw new IllegalArgumentException("未知的静态规则ID"); } - if (!staticRuleObject.getStaticRuleAuditStatus().equals(AuditStatusEnum.AUDITED.getNum())) { + if (!staticRuleObject.getAuditStatus().equals(AuditStatusEnum.AUDITED.getNum())) { throw new IllegalStateException("无法修改该静态规则,因为其审核状态未处于" + AuditStatusEnum.AUDITED); } @@ -125,7 +125,7 @@ public class StaticRuleService { //判断当前静态规则是否能够修改---是否存在任务选择的静态规则?? //按id查询该静态规则的used_task_id字段,如果不为空,则不能修改 object.setStaticRuleModifyTime(LocalDateTime.now()); - object.setStaticRuleAuditStatus(AuditStatusEnum.PENDING.getNum()); + object.setAuditStatus(AuditStatusEnum.PENDING.getNum()); //修改静态规则 return staticRuleMapper.updateStaticRule(id, object); } @@ -200,7 +200,7 @@ public class StaticRuleService { return; } - if (Objects.equals(staticRuleObject.getStaticRuleAuditStatus(), AuditStatusEnum.USING.getNum())) { + if (Objects.equals(staticRuleObject.getAuditStatus(), AuditStatusEnum.USING.getNum())) { throw new IllegalArgumentException("当前静态规则正在使用,无法删除"); } staticRuleMapper.deleteStaticRuleById(id); diff --git a/src/main/java/com/realtime/protection/server/task/TaskService.java b/src/main/java/com/realtime/protection/server/task/TaskService.java index 860a15e..93afd23 100644 --- a/src/main/java/com/realtime/protection/server/task/TaskService.java +++ b/src/main/java/com/realtime/protection/server/task/TaskService.java @@ -1,6 +1,9 @@ package com.realtime.protection.server.task; +import com.alibaba.excel.util.MapUtils; import com.baomidou.dynamic.datasource.annotation.DS; +import com.realtime.protection.configuration.entity.rule.dynamicrule.DynamicRuleObject; +import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; import com.realtime.protection.configuration.entity.task.DynamicTaskInfo; import com.realtime.protection.configuration.entity.task.Task; import com.realtime.protection.configuration.entity.task.TaskCommandInfo; @@ -8,6 +11,8 @@ import com.realtime.protection.configuration.utils.SqlSessionWrapper; import com.realtime.protection.configuration.utils.enums.StateEnum; import com.realtime.protection.configuration.utils.enums.audit.AuditStatusEnum; import com.realtime.protection.configuration.utils.enums.audit.AuditStatusValidator; +import com.realtime.protection.server.rule.dynamicrule.DynamicRuleMapper; +import com.realtime.protection.server.rule.staticrule.StaticRuleMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -17,17 +22,23 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; +import java.util.stream.Collectors; @Service @Slf4j @DS("mysql") public class TaskService { private final TaskMapper taskMapper; + private final StaticRuleMapper staticRuleMapper; private final SqlSessionWrapper sqlSessionWrapper; + private static final int BATCH_SIZE = 100; + private final DynamicRuleMapper dynamicRuleMapper; - public TaskService(TaskMapper taskMapper,SqlSessionWrapper sqlSessionWrapper) { + public TaskService(TaskMapper taskMapper, StaticRuleMapper staticRuleMapper, SqlSessionWrapper sqlSessionWrapper, DynamicRuleMapper dynamicRuleMapper) { this.taskMapper = taskMapper; + this.staticRuleMapper = staticRuleMapper; this.sqlSessionWrapper = sqlSessionWrapper; + this.dynamicRuleMapper = dynamicRuleMapper; } @Transactional @@ -36,19 +47,146 @@ public class TaskService { task.setTaskCreateUsername("xxx"); task.setTaskCreateDepart("xxx"); - // todo: 添加新建任务时,将动态/静态规则从“已审核”修改为“使用中” - taskMapper.newTask(task); - if (task.getStaticRuleIds() != null && !task.getStaticRuleIds().isEmpty()) + if (task.getStaticRuleIds() != null && !task.getStaticRuleIds().isEmpty()) { + staticRuleMapper.queryStaticRuleByIds(task.getStaticRuleIds()).forEach(staticRuleObject -> { + if (!staticRuleObject.getAuditStatus().equals(AuditStatusEnum.AUDITED.getNum())) { + throw new IllegalArgumentException("部分规则审批状态错误"); + } + if (staticRuleObject.getStaticRuleUsedTaskId() != null) { + throw new IllegalArgumentException("部分静态规则已被其他任务使用"); + } + }); taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds()); + } - if (task.getDynamicRuleIds() != null && !task.getDynamicRuleIds().isEmpty()) + if (task.getDynamicRuleIds() != null && !task.getDynamicRuleIds().isEmpty()) { + dynamicRuleMapper.queryDynamicRuleByIds(task.getDynamicRuleIds()).forEach(dynamicRuleObject -> { + if (!dynamicRuleObject.getAuditStatus().equals(AuditStatusEnum.AUDITED.getNum())) { + throw new IllegalArgumentException("部分规则审批状态错误"); + } + + if (dynamicRuleObject.getDynamicRuleUsedTaskId() != null) { + throw new IllegalArgumentException("部分动态规则已被其他任务使用"); + } + }); taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds()); + } return task.getTaskId(); } + /** + * 更新任务关联的静态规则审批状态,用于任务新建/停止时候,修改审批状态为已使用/已审批,不能用于其他审批状态修改 + * @param task 与静态规则关联的任务 + * @param newAuditStatus 需要修改的审批状态 + */ + public void updateStaticRuleAuditStatusInTask(Task task, AuditStatusEnum newAuditStatus) { + if (task == null) { + return; + } + + // 限制该函数仅能用于将规则修改为已审批/使用中 + if (!List.of(AuditStatusEnum.AUDITED, AuditStatusEnum.USING).contains(newAuditStatus)) { + return; + } + + List staticRuleObjects = staticRuleMapper.queryStaticRuleByIds(task.getStaticRuleIds()); + if (staticRuleObjects == null || staticRuleObjects.isEmpty()) { + throw new IllegalArgumentException("静态规则列表中的ID不存在,请检查静态规则是否真实存在"); + } + + // 检查所有的静态规则审批状态是否正确,如果不正确则报错 + staticRuleObjects.forEach(staticRuleObject -> staticRuleObject.checkAuditStatusValidate(newAuditStatus)); + + Map staticRuleAuditStatusBatch = staticRuleObjects + .stream() + .collect(Collectors.toMap( + StaticRuleObject::getStaticRuleId, + k -> newAuditStatus.getNum(), // 将审核状态全部修改为使用中状态 + (existing, replacement) -> existing)); // 如果有重复字段,默认使用先前值 + + sqlSessionWrapper.startBatchSession( + StaticRuleMapper.class, + + (Function, Void>>) mapper -> staticRuleBatch -> { + Map batchMap = MapUtils.newHashMapWithExpectedSize(BATCH_SIZE); + for (Map.Entry auditStatusEntry : staticRuleBatch.entrySet()) { + batchMap.put(auditStatusEntry.getKey(), auditStatusEntry.getValue()); + if (batchMap.size() < BATCH_SIZE) { + continue; + } + + mapper.updateAuditStatusByIdBatch(batchMap); + batchMap.clear(); + } + + mapper.updateAuditStatusByIdBatch(batchMap); + batchMap.clear(); + + return null; + }, + + staticRuleAuditStatusBatch + ); + } + + /** + * 更新任务关联的动态规则审批状态,用于任务新建/停止时候,修改审批状态为已使用/已审批,不能用于其他审批状态修改 + * @param task 与动态规则关联的任务 + * @param newAuditStatus 需要修改的审批状态 + */ + public void updateDynamicRuleAuditStatusInTask(Task task, AuditStatusEnum newAuditStatus) { + if (task == null) { + return; + } + + // 限制该函数仅能用于将规则修改为已审批/使用中 + if (!List.of(AuditStatusEnum.AUDITED, AuditStatusEnum.USING).contains(newAuditStatus)) { + return; + } + + List dynamicRuleObjects = dynamicRuleMapper.queryDynamicRuleByIds(task.getDynamicRuleIds()); + if (dynamicRuleObjects == null || dynamicRuleObjects.isEmpty()) { + throw new IllegalArgumentException("静态规则列表中的ID不存在,请检查静态规则是否真实存在"); + } + + // 检查所有的动态规则列表的审批状态是否正确,如不正确则报错 + dynamicRuleObjects.forEach(dynamicRuleObject -> dynamicRuleObject.checkAuditStatusValidate(newAuditStatus)); + + Map dynamicRuleAuditStatusBatch = dynamicRuleObjects + .stream() + .collect(Collectors.toMap( + DynamicRuleObject::getDynamicRuleId, + k -> newAuditStatus.getNum(), + (existing, replacement) -> existing)); + + sqlSessionWrapper.startBatchSession( + DynamicRuleMapper.class, + + (Function, Void>>) mapper -> batch -> { + Map batchMap = MapUtils.newHashMapWithExpectedSize(BATCH_SIZE); + for (Map.Entry auditStatusEntry : batch.entrySet()) { + batchMap.put(auditStatusEntry.getKey(), auditStatusEntry.getValue()); + if (batchMap.size() < BATCH_SIZE) { + continue; + } + + mapper.updateAuditStatusByIdBatch(batchMap); + batchMap.clear(); + } + + mapper.updateAuditStatusByIdBatch(batchMap); + batchMap.clear(); + + return null; + }, + + dynamicRuleAuditStatusBatch + ); + } + @Transactional public List queryTasks(Integer taskStatus, Integer taskType, String taskName, String taskCreator, @@ -116,6 +254,12 @@ public class TaskService { } public Boolean deleteTask(Long taskId) { + Task task = taskMapper.queryTask(taskId); + if (task == null) { + return true; + } + + updateStaticRuleAuditStatusInTask(task, AuditStatusEnum.AUDITED); return taskMapper.deleteTask(taskId); } diff --git a/src/main/java/com/realtime/protection/server/task/status/StateHandler.java b/src/main/java/com/realtime/protection/server/task/status/StateHandler.java index 07780a8..90ee668 100644 --- a/src/main/java/com/realtime/protection/server/task/status/StateHandler.java +++ b/src/main/java/com/realtime/protection/server/task/status/StateHandler.java @@ -36,14 +36,14 @@ public class StateHandler { } // 如果审核状态不为已通过审核,则报错 - if (taskAuditStatus != AuditStatusEnum.AUDITED.getNum()) { + if (!taskAuditStatus.equals(AuditStatusEnum.AUDITED.getNum())) { throw new IllegalArgumentException("无效的task_id,因为未通过审核"); } return switch (TaskTypeEnum.getTaskTypeByNum(task.getTaskType())) { - case STATIC -> handleStaticTaskStart(commandService, taskService, taskId); - case DYNAMIC -> handleDynamicTaskStart(taskService, taskId); - case JUDGED -> handleJudgedTaskStart(taskService, taskId); + case STATIC -> handleStaticTaskStart(commandService, taskService, task); + case DYNAMIC -> handleDynamicTaskStart(taskService, task); + case JUDGED -> handleJudgedTaskStart(taskService, task); }; } @@ -57,49 +57,60 @@ public class StateHandler { return true; } - protected Boolean handleStop(CommandService commandService, Long taskId) { + protected Boolean handleStop(CommandService commandService, TaskService taskService, Long taskId) { commandService.removeCommandsByTaskId(taskId); + taskService.updateDynamicRuleAuditStatusInTask(taskService.queryTask(taskId), AuditStatusEnum.AUDITED); + taskService.updateStaticRuleAuditStatusInTask(taskService.queryTask(taskId), AuditStatusEnum.AUDITED); return true; } - protected Boolean handleFinish(CommandService commandService, Long taskId) { + protected Boolean handleFinish(CommandService commandService, TaskService taskService, Long taskId) { commandService.removeCommandsByTaskId(taskId); + taskService.updateDynamicRuleAuditStatusInTask(taskService.queryTask(taskId), AuditStatusEnum.AUDITED); + taskService.updateStaticRuleAuditStatusInTask(taskService.queryTask(taskId), AuditStatusEnum.AUDITED); return true; } - protected Boolean handleFailed(CommandService commandService, Long taskId) { + protected Boolean handleFailed(CommandService commandService, TaskService taskService, Long taskId) { commandService.removeCommandsByTaskId(taskId); + taskService.updateDynamicRuleAuditStatusInTask(taskService.queryTask(taskId), AuditStatusEnum.AUDITED); + taskService.updateStaticRuleAuditStatusInTask(taskService.queryTask(taskId), AuditStatusEnum.AUDITED); return true; } // todo: 如果是实时任务或者研判后处置任务,那么就需要在任务启动之后,立刻向动态规则中指定的系统发送日志筛选请求。 // 筛选完成后,系统返回日志,需要由接收端点提取字段,并且合成一条静态规则,再按照任务开始时间、结束时间和任务类型进行指令创建 - private Boolean handleJudgedTaskStart(TaskService taskService, Long taskId) { - return sendFilters(taskService, taskId); + private Boolean handleJudgedTaskStart(TaskService taskService, Task task) { + return sendFilters(taskService, task); } - private Boolean handleDynamicTaskStart(TaskService taskService, Long taskId) { - return sendFilters(taskService, taskId); + private Boolean handleDynamicTaskStart(TaskService taskService, Task task) { + return sendFilters(taskService, task); } - private Boolean handleStaticTaskStart(CommandService commandService, TaskService taskService, Long taskId) { + private Boolean handleStaticTaskStart(CommandService commandService, TaskService taskService, Task task) { // 如果未能获取staticTaskCommandInfos,需要报错 - List staticTaskCommandInfos = taskService.getStaticCommandInfos(taskId); + List staticTaskCommandInfos = taskService.getStaticCommandInfos(task.getTaskId()); if (staticTaskCommandInfos == null || staticTaskCommandInfos.isEmpty()) { throw new IllegalArgumentException("静态规则列表为空,请至少选择一个静态规则以启动任务"); } + // 将所有关联的静态规则全部设置为已使用状态 + taskService.updateStaticRuleAuditStatusInTask(task, AuditStatusEnum.USING); + commandService.createCommands(staticTaskCommandInfos); return true; } - private Boolean sendFilters(TaskService taskService, Long taskId) { - List dynamicTaskInfos = taskService.getDynamicTaskInfos(taskId); + private Boolean sendFilters(TaskService taskService, Task task) { + List dynamicTaskInfos = taskService.getDynamicTaskInfos(task.getTaskId()); if (dynamicTaskInfos == null || dynamicTaskInfos.isEmpty()) { throw new IllegalArgumentException("动态规则列表为空,请至少选择一个动态规则以启动动态/研判后类型任务"); } + taskService.updateDynamicRuleAuditStatusInTask(task, AuditStatusEnum.AUDITED); + AtomicReference success = new AtomicReference<>(false); Mono mono = client.post() diff --git a/src/main/java/com/realtime/protection/server/task/status/states/FailedState.java b/src/main/java/com/realtime/protection/server/task/status/states/FailedState.java index 3eab4fa..251b0bb 100644 --- a/src/main/java/com/realtime/protection/server/task/status/states/FailedState.java +++ b/src/main/java/com/realtime/protection/server/task/status/states/FailedState.java @@ -11,8 +11,8 @@ public class FailedState extends StateHandler implements State { public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException { return switch (StateEnum.getStateEnumByState(newState)) { case RUNNING -> handleStart(taskService, commandService, taskId); - case STOP -> handleStop(commandService, taskId); - case FINISHED -> handleFinish(commandService, taskId); + case STOP -> handleStop(commandService, taskService, taskId); + case FINISHED -> handleFinish(commandService, taskService, taskId); default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState)); }; } diff --git a/src/main/java/com/realtime/protection/server/task/status/states/GeneratingState.java b/src/main/java/com/realtime/protection/server/task/status/states/GeneratingState.java index 98dd397..47af68d 100644 --- a/src/main/java/com/realtime/protection/server/task/status/states/GeneratingState.java +++ b/src/main/java/com/realtime/protection/server/task/status/states/GeneratingState.java @@ -10,8 +10,8 @@ public class GeneratingState extends StateHandler implements State { public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) { return switch (StateEnum.getStateEnumByState(newState)) { case RUNNING -> true; - case FAILED -> handleFailed(commandService, taskId); - case FINISHED -> handleFinish(commandService, taskId); + case FAILED -> handleFailed(commandService, taskService, taskId); + case FINISHED -> handleFinish(commandService, taskService, taskId); default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState)); }; } diff --git a/src/main/java/com/realtime/protection/server/task/status/states/PauseState.java b/src/main/java/com/realtime/protection/server/task/status/states/PauseState.java index 137b034..3382565 100644 --- a/src/main/java/com/realtime/protection/server/task/status/states/PauseState.java +++ b/src/main/java/com/realtime/protection/server/task/status/states/PauseState.java @@ -10,9 +10,9 @@ public class PauseState extends StateHandler implements State { public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) { return switch (StateEnum.getStateEnumByState(newState)) { case RUNNING -> handleResume(commandService, taskId); - case STOP -> handleStop(commandService, taskId); - case FINISHED -> handleFinish(commandService, taskId); - case FAILED -> handleFailed(commandService, taskId); + case STOP -> handleStop(commandService, taskService, taskId); + case FINISHED -> handleFinish(commandService, taskService, taskId); + case FAILED -> handleFailed(commandService, taskService, taskId); default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState)); }; } diff --git a/src/main/java/com/realtime/protection/server/task/status/states/PendingState.java b/src/main/java/com/realtime/protection/server/task/status/states/PendingState.java index b7f6ec1..6973e63 100644 --- a/src/main/java/com/realtime/protection/server/task/status/states/PendingState.java +++ b/src/main/java/com/realtime/protection/server/task/status/states/PendingState.java @@ -10,9 +10,9 @@ public class PendingState extends StateHandler implements State { @Override public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException { return switch (StateEnum.getStateEnumByState(newState)) { - case FAILED -> handleFailed(commandService, taskId); + case FAILED -> handleFailed(commandService, taskService, taskId); case RUNNING -> handleStart(taskService, commandService, taskId); - case FINISHED -> handleFinish(commandService, taskId); + case FINISHED -> handleFinish(commandService, taskService, taskId); default -> throw new IllegalStateException(taskId + " meets unexpected value: " + StateEnum.getStateEnumByState(newState)); }; diff --git a/src/main/java/com/realtime/protection/server/task/status/states/RunningState.java b/src/main/java/com/realtime/protection/server/task/status/states/RunningState.java index e875d6b..e36ad9a 100644 --- a/src/main/java/com/realtime/protection/server/task/status/states/RunningState.java +++ b/src/main/java/com/realtime/protection/server/task/status/states/RunningState.java @@ -10,9 +10,9 @@ public class RunningState extends StateHandler implements State { public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) { return switch (StateEnum.getStateEnumByState(newState)) { case PAUSED -> handlePause(commandService, taskId); - case STOP -> handleStop(commandService, taskId); - case FINISHED -> handleFinish(commandService, taskId); - case FAILED -> handleFailed(commandService, taskId); + case STOP -> handleStop(commandService, taskService, taskId); + case FINISHED -> handleFinish(commandService, taskService, taskId); + case FAILED -> handleFailed(commandService, taskService, taskId); default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState)); }; } diff --git a/src/main/java/com/realtime/protection/server/task/status/states/StopState.java b/src/main/java/com/realtime/protection/server/task/status/states/StopState.java index 46ef965..f301cba 100644 --- a/src/main/java/com/realtime/protection/server/task/status/states/StopState.java +++ b/src/main/java/com/realtime/protection/server/task/status/states/StopState.java @@ -12,8 +12,8 @@ public class StopState extends StateHandler implements State { public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException { return switch (StateEnum.getStateEnumByState(newState)) { case RUNNING -> handleStart(taskService, commandService, taskId); - case FAILED -> handleFailed(commandService, taskId); - case FINISHED -> handleFinish(commandService, taskId); + case FAILED -> handleFailed(commandService, taskService, taskId); + case FINISHED -> handleFinish(commandService, taskService, taskId); default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState)); }; } diff --git a/src/main/resources/mappers/StaticRuleMapper.xml b/src/main/resources/mappers/StaticRuleMapper.xml index 2025944..dd2c0a3 100644 --- a/src/main/resources/mappers/StaticRuleMapper.xml +++ b/src/main/resources/mappers/StaticRuleMapper.xml @@ -86,7 +86,8 @@ update t_static_rule - set static_rule_audit_status = CASE static_rule_id + set static_rule_modify_time = NOW(), + static_rule_audit_status = CASE static_rule_id WHEN #{id} THEN #{auditStatus} diff --git a/src/main/resources/mappers/TaskMapper.xml b/src/main/resources/mappers/TaskMapper.xml index 4c98aed..a3bc326 100644 --- a/src/main/resources/mappers/TaskMapper.xml +++ b/src/main/resources/mappers/TaskMapper.xml @@ -81,13 +81,13 @@ @@ -272,7 +273,9 @@ + UPDATE t_protect_object diff --git a/src/main/resources/mappers/StaticRuleMapper.xml b/src/main/resources/mappers/StaticRuleMapper.xml index dd2c0a3..5270807 100644 --- a/src/main/resources/mappers/StaticRuleMapper.xml +++ b/src/main/resources/mappers/StaticRuleMapper.xml @@ -22,7 +22,7 @@ #{object.staticRuleMdport}, #{object.staticRuleProtocol}, #{object.staticRuleMprotocol}, #{object.staticRuleDns}, #{object.staticRuleURL}, #{object.staticRulePriority}, #{object.staticRuleRange}, #{object.staticRuleFrequency}, - #{object.staticRuleAuditStatus}) + #{object.auditStatus}) insert into t_static_rule(static_rule_name, static_rule_create_time, @@ -115,7 +115,7 @@ - + @@ -206,5 +206,15 @@ #{id} + + \ No newline at end of file diff --git a/src/main/resources/mappers/TaskMapper.xml b/src/main/resources/mappers/TaskMapper.xml index a3bc326..46a1677 100644 --- a/src/main/resources/mappers/TaskMapper.xml +++ b/src/main/resources/mappers/TaskMapper.xml @@ -257,7 +257,7 @@ - + @@ -266,7 +266,7 @@ + + \ No newline at end of file diff --git a/src/main/resources/mappers/TemplateMapper.xml b/src/main/resources/mappers/TemplateMapper.xml index cb36121..68c83b9 100644 --- a/src/main/resources/mappers/TemplateMapper.xml +++ b/src/main/resources/mappers/TemplateMapper.xml @@ -146,6 +146,17 @@ WHERE strategy_template_name = #{eventName} AND strategy_template_source_system = #{sourceSystem} + + + + UPDATE t_strategy_template diff --git a/src/main/resources/mappers/WhiteListMapper.xml b/src/main/resources/mappers/WhiteListMapper.xml index 05a5dc8..2acecd2 100644 --- a/src/main/resources/mappers/WhiteListMapper.xml +++ b/src/main/resources/mappers/WhiteListMapper.xml @@ -284,5 +284,10 @@ + \ No newline at end of file diff --git a/src/test/java/com/realtime/protection/server/rule/staticrule/StaticRuleServiceTest.java b/src/test/java/com/realtime/protection/server/rule/staticrule/StaticRuleServiceTest.java index 4aa7345..23466c6 100644 --- a/src/test/java/com/realtime/protection/server/rule/staticrule/StaticRuleServiceTest.java +++ b/src/test/java/com/realtime/protection/server/rule/staticrule/StaticRuleServiceTest.java @@ -114,4 +114,6 @@ public class StaticRuleServiceTest extends ProtectionApplicationTests { System.out.println(staticRuleService.updateAuditStatusBatch(map)); } + + } diff --git a/src/test/java/com/realtime/protection/server/task/TaskServiceTest.java b/src/test/java/com/realtime/protection/server/task/TaskServiceTest.java index 5ce7305..63c0aa8 100644 --- a/src/test/java/com/realtime/protection/server/task/TaskServiceTest.java +++ b/src/test/java/com/realtime/protection/server/task/TaskServiceTest.java @@ -3,8 +3,10 @@ package com.realtime.protection.server.task; import com.realtime.protection.ProtectionApplicationTests; import com.realtime.protection.configuration.entity.rule.dynamicrule.DynamicRuleObject; import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; +import com.realtime.protection.configuration.entity.task.DynamicTaskInfo; import com.realtime.protection.configuration.entity.task.Task; import com.realtime.protection.configuration.entity.task.TaskCommandInfo; +import com.realtime.protection.configuration.exception.DorisStartException; import com.realtime.protection.server.rule.dynamicrule.DynamicRuleService; import com.realtime.protection.server.rule.staticrule.StaticRuleService; import com.realtime.protection.server.task.status.StateChangeService; @@ -27,13 +29,15 @@ class TaskServiceTest extends ProtectionApplicationTests { private final TaskService taskService; private final StaticRuleService staticRuleService; private final DynamicRuleService dynamicRuleService; + private final StateChangeService stateChangeService; private Task task; @Autowired - TaskServiceTest(TaskService taskService, StaticRuleService staticRuleService, DynamicRuleService dynamicRuleService) { + TaskServiceTest(TaskService taskService, StaticRuleService staticRuleService, DynamicRuleService dynamicRuleService, StateChangeService stateChangeService) { this.taskService = taskService; this.staticRuleService = staticRuleService; this.dynamicRuleService = dynamicRuleService; + this.stateChangeService = stateChangeService; } @BeforeEach @@ -189,4 +193,15 @@ class TaskServiceTest extends ProtectionApplicationTests { System.out.println(taskService.updateAuditStatusBatch(map)); } + @Test + void testGetDynamicTaskInfos(){ + List dynamicTaskInfos = taskService.getDynamicTaskInfos(43844L); + System.out.println(dynamicTaskInfos); + } + + @Test + void changeTaskstatus() throws DorisStartException { + stateChangeService.changeState(2, 43844L, false); + + } } \ No newline at end of file