1、重构templateNew,未完成

This commit is contained in:
Hao Miao
2024-05-20 15:17:50 +08:00
parent 3824a5a504
commit 0da25f0bcb
7 changed files with 775 additions and 0 deletions

View File

@@ -0,0 +1,110 @@
package com.realtime.protection.configuration.entity.defense.template;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class TemplateNew {
@JsonProperty("template_id")
@Schema(description = "防御策略模板ID", example = "2", accessMode = Schema.AccessMode.READ_ONLY)
private Integer templateId;
@JsonProperty("template_name")
@NotNull(message = "template_name字段不能为空。")
@Schema(description = "防御策略模板名称(事件类型)", example = "APT攻击事件")
private String templateName;
@JsonProperty("source_system")
@NotNull(message = "source_system字段不能为空。")
@Schema(description = "防御策略模板数据来源系统", example = "BW系统")
private String sourceSystem;
@JsonProperty("event_type")
@NotNull(message = "事件类型字段不能为空。")
@Schema(description = "防御策略模板数据来源系统", example = "BW系统")
private String eventType;
@JsonProperty("protect_level")
@NotNull(message = "防护等级字段不能为空。")
@Schema(description = "防御策略模板数据来源系统", example = "BW系统")
private String protectLevel;
@JsonProperty("description")
@Schema(description = "对策略模板的文字描述。方便用户使用", example = "zd防护对象的全流量")
private String description;
@Schema(description = "该防护等级是否需要提取防护对象IP地址字段")
private Boolean hasProtectObjectIP = false;
@Schema(description = "该防护等级是否需要提取防护对象端口字段")
private Boolean hasProtectObjectPort = false;
@Schema(description = "该防护等级是否需要提取对端IP地址字段")
private Boolean hasPeerIP = false;
@Schema(description = "该防护等级是否需要提取对端端口字段")
private Boolean hasPeerPort = false;
@Schema(description = "该防护等级是否需要提取网络协议字段")
private Boolean hasProtocol = false;
@Schema(description = "该防护等级是否需要提取URL字段")
private Boolean hasURL = false;
@Schema(description = "该防护等级是否需要提取DNS")
private Boolean hasDNS = false;
@Schema(description = "该防护等级是处置防护对象的全流量or单向流量")
private Boolean isFullFlow = false;
@Schema(description = "该防护等级防护对象ip地址是否作为源ip地址")
private Boolean isProtectObjectIPSrc = false;
@JsonProperty("template_used_times")
@Schema(description = "防御策略模板使用次数", example = "20", accessMode = Schema.AccessMode.READ_ONLY)
private Integer usedTimes;
@JsonProperty("running_tasks")
@Schema(description = "防御策略模板已运行的任务数量", example = "30", accessMode = Schema.AccessMode.READ_ONLY)
private Integer runningTasks;
@JsonProperty("create_user_id")
@Schema(description = "防御策略模板创建人ID", example = "1", accessMode = Schema.AccessMode.READ_ONLY)
private Integer createUserId;
@JsonProperty("create_user_name")
@Schema(description = "防御策略模板创建人名称", example = "xxx", accessMode = Schema.AccessMode.READ_ONLY)
private String createUsername;
@JsonProperty("create_user_depart")
@Schema(description = "防御策略模板创建人处室", example = "xxx", accessMode = Schema.AccessMode.READ_ONLY)
private String createDepart;
@JsonProperty("audit_status")
@Schema(description = "防御策略模板审核状态0为未审核1为已退回2为审核通过", example = "1", accessMode = Schema.AccessMode.READ_ONLY)
private String auditStatus;
@JsonProperty("template_display_id")
@Schema(description = "策略模板展示id", accessMode = Schema.AccessMode.READ_ONLY)
private String templateDisplayId;
@JsonProperty("audit_user_name")
@Schema(description = "审核用户名称", example = "user11")
private String auditUserName;
@JsonProperty("audit_user_id")
@Schema(description = "审核用户id", example = "11111")
private String auditUserId;
@JsonProperty("audit_user_depart")
@Schema(description = "审核用户部门", example = "部门1")
private String auditUserDepart;
@JsonProperty("create_time")
@Schema(description = "新建时间")
private String createTime;
@JsonProperty("update_time")
@Schema(description = "更新时间")
private String updateTime;
}

View File

@@ -0,0 +1,208 @@
package com.realtime.protection.server.defense.templatenew;
import com.realtime.protection.configuration.entity.defense.template.TemplateNew;
import com.realtime.protection.configuration.response.ResponseResult;
import com.realtime.protection.configuration.utils.enums.audit.AuditStatusEnum;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/templatenew/")
public class TemplateController implements TemplateNewCpntrollerApi{
private final TemplateService templateService;
public TemplateController(TemplateService templateService) {
this.templateService = templateService;
}
// @Override
@PostMapping("/new")
public ResponseResult newTemplate(@RequestBody @Valid TemplateNew template) {
Integer templateId = templateService.newTemplate(template);
if (templateId > 0) {
return ResponseResult.ok()
.setData("template_id", templateId)
.setData("success", true);
}
return ResponseResult.error()
.setData("template_id", null)
.setData("success", false);
}
/*
删 改 查 审核。。。
*/
@Override
@GetMapping("/query")
public ResponseResult queryTemplates(@RequestParam(value = "template_name", required = false) String templateName,
@RequestParam(value = "source_system", required = false) String sourceSystem,
@RequestParam(value = "create_user_name", required = false) String createUserName,
@RequestParam(value = "template_id", required = false) Integer templateId,
@RequestParam(value = "audit_status", required = false) Integer auditStatus,
@RequestParam(value = "event_type", required = false) String eventType,
@RequestParam(value = "protect_level", required = false) Integer protectLevel,
@RequestParam("page") @Min(1) Integer page,
@RequestParam("page_size") @Min(1) Integer pageSize) {
List<TemplateNew> templates = templateService.queryTemplates(
templateName, sourceSystem, createUserName, templateId,
auditStatus,eventType,protectLevel,
page, pageSize
);
return ResponseResult.ok()
.setData("templates", templates)
.setData("total_num", templateService.queryTemplateTotalNum(
templateName, sourceSystem, createUserName, templateId,
auditStatus, eventType, protectLevel));
}
@Override
@GetMapping("/{templateId}/query")
public ResponseResult queryTemplate(@PathVariable Integer templateId) {
TemplateNew template = templateService.queryTemplate(templateId);
if (template == null) {
return ResponseResult.invalid()
.setMessage("无效的策略模板ID也许该模板不存在");
}
return ResponseResult.ok().setData("template", template);
}
// @Override
// @GetMapping("/query/level")
// public ResponseResult queryTemplateProtectLevels() {
// List<Template> templates = templateService.queryTemplatesShort();
// return ResponseResult.ok().setData("templates", templates);
// }
@Override
@PostMapping("/{templateId}/update")
public ResponseResult updateTemplate(@PathVariable @Min(1) Integer templateId,
@RequestBody @Valid TemplateNew template) {
Boolean success = templateService.updateTemplate(templateId, template);
return ResponseResult.ok()
.setData("template_id", templateId)
.setData("success", success);
}
@Override
@DeleteMapping("/{templateId}/delete")
public ResponseResult deleteTemplate(@PathVariable @Min(1) Integer templateId) {
return ResponseResult.ok()
.setData("template_id", templateId)
.setData("success", templateService.deleteTemplate(templateId));
}
@Override
@GetMapping("/query/source_system")
public ResponseResult querySourceSystem() {
return ResponseResult.ok()
.setData("source_system", templateService.querySourceSystem());
}
@Override
@GetMapping("/query/event_name/{sourceSystem}")
public ResponseResult queryEventName(@PathVariable String sourceSystem) {
return ResponseResult.ok()
.setData("event_name", templateService.queryEventName(sourceSystem));
}
// @Override
// @PostMapping("/query/templateId")
// public ResponseResult queryTemplateId(@RequestBody Map<String,String> map) {
// String sourceSystem = map.get("source_system");
// String eventName = map.get("event_name");
// return ResponseResult.ok()
// .setData("template_id", templateService.queryTemplateId(sourceSystem, eventName));
// }
/*
策略模板数据统计
*/
@Override
@GetMapping("/statistics")
public ResponseResult statisticsTemplate() {
return ResponseResult.ok()
.setData("template_num", templateService.queryTemplateTotalNum(null, null, null, null, null, null, null))
.setData("template_used_num", templateService.queryUsedTemplateTotalNum())
.setData("template_audit_num", templateService.queryAuditTemplateTotalNum(
AuditStatusEnum.getNumByState(AuditStatusEnum.AUDITED.getState())
))
.setData("template_unaudit_num", templateService.queryAuditTemplateTotalNum(
AuditStatusEnum.getNumByState(AuditStatusEnum.PENDING.getState())
));
}
/**
* 审批
*/
@Override
@GetMapping("/{id}/audit/{auditStatus}")
public ResponseResult updateTemplateAuditStatus(@PathVariable Integer id, @PathVariable Integer auditStatus) {
if (id <= 0 || auditStatus < 0 || auditStatus > 2) {
return new ResponseResult(400, "id or status is invalid")
.setData("template_id", id)
.setData("success", false);
}
return ResponseResult.ok()
.addDataMap(templateService.updateAuditStatus(id, auditStatus))
.setData("template_id", id);
}
/**
* 批量修改审核状态
*/
@Override
@PostMapping("/auditbatch")
public ResponseResult updateWhiteListAuditStatusBatch(@RequestBody Map<Integer, Integer> idsWithAuditStatusMap) {
List<Integer> errorIds = new ArrayList<>();
for (Map.Entry<Integer, Integer> 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("id", errorIds)
.setData("success", false);
}
return ResponseResult.ok()
.setData("success", templateService.updateAuditStatusBatch(idsWithAuditStatusMap));
}
/*
修改审批信息
*/
@Override
@PostMapping("/auditInfo/{ids}")
public ResponseResult updateAuditInfo(@PathVariable List<Integer> ids,
@RequestBody Map<String, String> auditInfo) {
if (auditInfo.get("auditInfo") == null || auditInfo.get("auditInfo").isEmpty()) {
return ResponseResult.ok();
}
return ResponseResult.ok()
.setData("success", templateService.updateAuditInfo(ids, auditInfo.get("auditInfo")));
}
@Override
@GetMapping("/auditInfo/{id}")
public ResponseResult queryAuditInfo(@PathVariable Integer id) {
return ResponseResult.ok()
.setData("auditInfo", templateService.queryAuditInfo(id));
}
}

View File

@@ -0,0 +1,66 @@
package com.realtime.protection.server.defense.templatenew;
import com.realtime.protection.configuration.entity.defense.template.ProtectLevel;
import com.realtime.protection.configuration.entity.defense.template.Template;
import com.realtime.protection.configuration.entity.defense.template.TemplateNew;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface TemplateMapper {
void newTemplate(TemplateNew template);
List<TemplateNew> queryTemplates(@Param("template_name") String templateName,
@Param("source_system") String sourceSystem,
@Param("create_username") String createUsername,
@Param("template_id")Integer templateId,
@Param("audit_status")Integer auditStatus,
@Param("event_type")String eventType,
@Param("protect_level")Integer protectLevel,
@Param("page") Integer page,
@Param("page_size") Integer pageSize);
Boolean updateTemplateInformation(@Param("template") TemplateNew template);
TemplateNew queryTemplate(@Param("template_id") Integer templateId);
@Delete("DELETE FROM t_strategy_template WHERE strategy_template_id = #{template_id}")
Boolean deleteTemplate(@Param("template_id") Integer templateId);
Integer queryTemplateTotalNum(@Param("template_name") String templateName,
@Param("source_system") String sourceSystem,
@Param("create_username") String createUsername,
@Param("template_id")Integer templateId,
@Param("audit_status")Integer auditStatus,
@Param("event_type")String eventType,
@Param("protect_level")Integer protectLevel
);
List<String> querySourceSystem();
List<String> queryEventName(String sourceSystem);
// Integer queryTemplateId(String sourceSystem, String eventName);
Integer queryUsedTemplateTotalNum();
Integer queryAuditTemplateTotalNum(Integer auditState);
Integer queryAuditStatusById(Integer id);
Boolean updateAuditStatusById(Integer id, Integer auditStatus);
List<Integer> queryAuditStatusByIds(@Param("idsWithAuditStatusMap") Map<Integer, Integer> idsWithAuditStatusMap);
void updateAuditStatusByIdBatch(@Param("idWithAuditStatusBatch") Map<Integer, Integer> idWithAuditStatusBatch);
Boolean updateAuditInfo(List<Integer> ids, String auditInfo);
String queryAuditInfo(Integer id);
}

View File

@@ -0,0 +1,67 @@
package com.realtime.protection.server.defense.templatenew;
import com.realtime.protection.configuration.entity.defense.template.Template;
import com.realtime.protection.configuration.entity.defense.template.TemplateNew;
import com.realtime.protection.configuration.response.ResponseResult;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
public interface TemplateNewCpntrollerApi {
@GetMapping("/query")
ResponseResult queryTemplates(@RequestParam(value = "template_name", required = false) String templateName,
@RequestParam(value = "source_system", required = false) String sourceSystem,
@RequestParam(value = "create_user_name", required = false) String createUserName,
@RequestParam(value = "template_id", required = false) Integer templateId,
@RequestParam(value = "audit_status", required = false) Integer auditStatus,
@RequestParam(value = "event_type", required = false) String eventType,
@RequestParam(value = "protect_level", required = false) Integer protectLevel,
@RequestParam("page") @Min(1) Integer page,
@RequestParam("page_size") @Min(1) Integer pageSize);
@GetMapping("/{templateId}/query")
ResponseResult queryTemplate(@PathVariable Integer templateId);
@PostMapping("/{templateId}/update")
ResponseResult updateTemplate(@PathVariable @Min(1) Integer templateId,
@RequestBody @Valid TemplateNew template);
@DeleteMapping("/{templateId}/delete")
ResponseResult deleteTemplate(@PathVariable @Min(1) Integer templateId);
@GetMapping("/query/source_system")
ResponseResult querySourceSystem();
@GetMapping("/query/event_name/{sourceSystem}")
ResponseResult queryEventName(@PathVariable String sourceSystem);
/*
策略模板数据统计
*/
@GetMapping("/statistics")
ResponseResult statisticsTemplate();
@GetMapping("/{id}/audit/{auditStatus}")
ResponseResult updateTemplateAuditStatus(@PathVariable Integer id, @PathVariable Integer auditStatus);
@PostMapping("/auditbatch")
ResponseResult updateWhiteListAuditStatusBatch(@RequestBody Map<Integer, Integer> idsWithAuditStatusMap);
/*
修改审批信息
*/
@PostMapping("/auditInfo/{ids}")
ResponseResult updateAuditInfo(@PathVariable List<Integer> ids,
@RequestBody Map<String, String> auditInfo);
@GetMapping("/auditInfo/{id}")
ResponseResult queryAuditInfo(@PathVariable Integer id);
}

View File

@@ -0,0 +1,169 @@
package com.realtime.protection.server.defense.templatenew;
import com.realtime.protection.configuration.entity.defense.template.Template;
import com.realtime.protection.configuration.entity.defense.template.TemplateNew;
import com.realtime.protection.configuration.utils.Counter;
import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import com.realtime.protection.configuration.utils.enums.audit.AuditStatusValidator;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@Service
public class TemplateService {
private final TemplateMapper templateMapper;
private final Counter counter;
private final SqlSessionWrapper sqlSessionWrapper;
public TemplateService(TemplateMapper templateMapper, Counter counter, SqlSessionWrapper sqlSessionWrapper) {
this.templateMapper = templateMapper;
this.counter = counter;
this.sqlSessionWrapper = sqlSessionWrapper;
}
public Integer newTemplate( TemplateNew template) {
template.setTemplateDisplayId(
"CLMB-"
+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
+ "-"
+ String.format("%06d", counter.generateId("strategy_template"))
);
templateMapper.newTemplate(template);
if (template.getTemplateId() == null) {
return 0;
}
return template.getTemplateId();
}
public List<TemplateNew> queryTemplates(String templateName, String sourceSystem, String createUserName,
Integer templateId, Integer auditStatus,
String eventType, Integer protectLevel,
Integer page, Integer pageSize) {
return templateMapper.queryTemplates(templateName, sourceSystem, createUserName,
templateId, auditStatus,eventType, protectLevel, page, pageSize);
}
public Boolean updateTemplate(Integer templateId, TemplateNew template) {
template.setTemplateId(templateId);
return templateMapper.updateTemplateInformation(template);
}
public TemplateNew queryTemplate(Integer templateId) {
return templateMapper.queryTemplate(templateId);
}
public Boolean deleteTemplate(Integer templateId) {
return templateMapper.deleteTemplate(templateId);
}
public Integer queryTemplateTotalNum(
String templateName, String sourceSystem, String createUserName,
Integer templateId, Integer auditStatus,
String eventType, Integer protectLevel) {
return templateMapper.queryTemplateTotalNum(templateName, sourceSystem, createUserName,
templateId,auditStatus,eventType, protectLevel );
}
public List<String> querySourceSystem() {
return templateMapper.querySourceSystem();
}
public List<String> queryEventName(String sourceSystem) {
return templateMapper.queryEventName(sourceSystem);
}
public Integer queryUsedTemplateTotalNum() {
return templateMapper.queryUsedTemplateTotalNum();
}
public Integer queryAuditTemplateTotalNum(Integer auditState) {
return templateMapper.queryAuditTemplateTotalNum(auditState);
}
public Map<String, Object> updateAuditStatus(Integer id, Integer auditStatus) {
Integer originalAuditStatus = templateMapper.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 = templateMapper.updateAuditStatusById(id, auditStatus);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("success", success);
resultMap.put("audit_status", auditStatus);
return resultMap;
}
public Boolean updateAuditStatusBatch(Map<Integer, Integer> idsWithAuditStatusMap) {
//校验id和status是否合法
List<Integer> originalAuditStatusList = templateMapper.queryAuditStatusByIds(idsWithAuditStatusMap);
if (originalAuditStatusList == null || originalAuditStatusList.size() != idsWithAuditStatusMap.size()) {
throw new IllegalArgumentException("策略模板部分不存在");
}
int index = 0;
List<Integer> errorIds = new ArrayList<>();
for(Map.Entry<Integer, Integer> entry: idsWithAuditStatusMap.entrySet()) {
Integer id = entry.getKey();
Integer auditStatus = entry.getValue();
Integer originalAuditStatus = originalAuditStatusList.get(index);
index++;
if (!AuditStatusValidator.setOriginal(originalAuditStatus).checkValidate(auditStatus)) {
errorIds.add(id);
}
}
if (!errorIds.isEmpty()){
throw new IllegalArgumentException("策略模板无法修改为对应审核状态, 错误id: " + errorIds);
}
Function<com.realtime.protection.server.defense.template.TemplateMapper, Function<Map<Integer, Integer>, Boolean>> updateTemplateAuditStatusFunction =
mapper -> map -> {
if (map == null || map.isEmpty()) {
return false;
}
Map<Integer, Integer> idWithAuditStatusBatch = new HashMap<>();
for (Map.Entry<Integer, Integer> 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(com.realtime.protection.server.defense.template.TemplateMapper.class, updateTemplateAuditStatusFunction, idsWithAuditStatusMap);
}
public Boolean updateAuditInfo(List<Integer> ids, String auditInfo) {
return templateMapper.updateAuditInfo(ids, auditInfo);
}
public String queryAuditInfo(Integer id) {
return templateMapper.queryAuditInfo(id);
}
}