feat: services-log stores, purges and serves admin audit events
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
10f59c5ca8
commit
d715073ab2
10 files changed
+505
-1
No files matched your search
+30
@@ -38,6 +38,11 @@ public class PubSubConfig {
|
||||
|
||||
@Value("${pubsub.response-time-log.subscription}")
|
||||
public String responseTimeLogSubscription;
|
||||
@Value("${pubsub.audit-event.topic}")
|
||||
public String auditEventTopic;
|
||||
|
||||
@Value("${pubsub.audit-event.subscription}")
|
||||
public String auditEventSubscription;
|
||||
@Value("${pubsub.error-log.topic}")
|
||||
public String errorLogTopic;
|
||||
|
||||
@@ -56,6 +61,9 @@ public class PubSubConfig {
|
||||
if (pubSubAdmin.getTopic(responseTimeLogTopic) == null) {
|
||||
pubSubAdmin.createTopic(responseTimeLogTopic);
|
||||
}
|
||||
if (pubSubAdmin.getTopic(auditEventTopic) == null) {
|
||||
pubSubAdmin.createTopic(auditEventTopic);
|
||||
}
|
||||
if (pubSubAdmin.getTopic(errorLogTopic) == null) {
|
||||
pubSubAdmin.createTopic(errorLogTopic);
|
||||
}
|
||||
@@ -82,6 +90,15 @@ public class PubSubConfig {
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
if (pubSubAdmin.getSubscription(auditEventSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + auditEventTopic)
|
||||
.setName(PROJECTS_PREFIX + projectId + SUBSCRIPTIONS_PREFIX + auditEventSubscription)
|
||||
.setRetainAckedMessages(true)
|
||||
.setExpirationPolicy(ExpirationPolicy.newBuilder().setTtl(com.google.protobuf.Duration.newBuilder().setSeconds(31536000)).build())
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
if (pubSubAdmin.getSubscription(errorLogSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + errorLogTopic)
|
||||
@@ -111,6 +128,15 @@ public class PubSubConfig {
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
@Bean
|
||||
public PubSubInboundChannelAdapter auditEventSubscriptionChannelAdapter(
|
||||
@Qualifier("auditEventSubscriptionChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, auditEventSubscription);
|
||||
adapter.setOutputChannel(inputChannel);
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public PubSubInboundChannelAdapter errorLogSubscriptionChannelAdapter(
|
||||
// @Qualifier("errorLogSubscriptionChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
@@ -129,6 +155,10 @@ public class PubSubConfig {
|
||||
public MessageChannel reponseTimeLogSubscriptionChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
@Bean
|
||||
public MessageChannel auditEventSubscriptionChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
// @Bean
|
||||
// public MessageChannel errorLogSubscriptionChannel() {
|
||||
// return new DirectChannel();
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.services.log.controller;
|
||||
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/log/audit")
|
||||
public class AuditEventController {
|
||||
|
||||
public record SearchRequest(String actor, String module, String action, String outcome,
|
||||
String from, String to, Integer page, Integer size) {
|
||||
}
|
||||
|
||||
private final AuditEventLogRepository repository;
|
||||
|
||||
public AuditEventController(AuditEventLogRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@PostMapping("/search")
|
||||
public Map<String, Object> search(@RequestBody SearchRequest r) {
|
||||
int p = r.page() == null || r.page() < 0 ? 0 : r.page();
|
||||
int s = r.size() == null || r.size() < 1 ? 20 : Math.min(r.size(), 100);
|
||||
LocalDateTime from = day(r.from(), 0);
|
||||
LocalDateTime to = day(r.to(), 1);
|
||||
Page<AuditEventLog> page = repository.search(blankToNull(r.actor()), blankToNull(r.module()),
|
||||
blankToNull(r.action()), blankToNull(r.outcome()), from, to,
|
||||
PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "occurredAt", "id")));
|
||||
return Map.of("content", page.getContent(), "totalElements", page.getTotalElements(), "number", p, "size", s);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AuditEventLog get(@PathVariable Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No audit event " + id));
|
||||
}
|
||||
|
||||
private static String blankToNull(String v) {
|
||||
return v == null || v.isBlank() ? null : v;
|
||||
}
|
||||
|
||||
/** yyyy-MM-dd to that day's start plus plusDays; blank is null; malformed is 400. */
|
||||
private static LocalDateTime day(String v, int plusDays) {
|
||||
if (v == null || v.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(v.trim()).plusDays(plusDays).atStartOfDay();
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Dates must be yyyy-MM-dd");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.solvway.services.log.model;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** Maps `service-log`.`audit_event` as created by the OpenSpec change SQL; the app never runs DDL. */
|
||||
@Entity
|
||||
@Table(name = "audit_event")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AuditEventLog {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private Long companyId;
|
||||
private LocalDateTime occurredAt;
|
||||
private String actor;
|
||||
private String module;
|
||||
private String action;
|
||||
private String httpMethod;
|
||||
private String pathTemplate;
|
||||
private String targetId;
|
||||
private String outcome;
|
||||
private Integer httpStatus;
|
||||
private String clientIp;
|
||||
private String changes;
|
||||
}
|
||||
+42
@@ -4,7 +4,10 @@ import com.google.cloud.spring.pubsub.support.BasicAcknowledgeablePubsubMessage;
|
||||
import com.google.cloud.spring.pubsub.support.GcpPubSubHeaders;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.model.BackOfficeAccessLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import com.solvway.services.log.model.ResponseTime;
|
||||
import com.solvway.services.log.repo.BackOfficeAccessLogRepository;
|
||||
import com.solvway.services.log.service.ResponseTimeService;
|
||||
@@ -70,6 +73,45 @@ public class PubSubListener {
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "auditEventSubscriptionChannel")
|
||||
public MessageHandler auditEventMessageReceiver(AuditEventLogRepository repository) {
|
||||
return message -> {
|
||||
try {
|
||||
pubSubUtil.checkMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
AuditEvent e = pubSubUtil.convertToOriginalObject(message.getPayload(), AuditEvent.class);
|
||||
AuditEventLog row = new AuditEventLog();
|
||||
row.setCompanyId(e.getCompanyId());
|
||||
row.setOccurredAt(e.getOccurredAt());
|
||||
row.setActor(clip(e.getActor(), 191));
|
||||
row.setModule(clip(e.getModule(), 64));
|
||||
row.setAction(clip(e.getAction(), 128));
|
||||
row.setHttpMethod(clip(e.getHttpMethod(), 16));
|
||||
row.setPathTemplate(clip(e.getPathTemplate(), 255));
|
||||
row.setTargetId(clip(e.getTargetId(), 128));
|
||||
row.setOutcome(clip(e.getOutcome(), 16));
|
||||
row.setHttpStatus(e.getHttpStatus());
|
||||
row.setClientIp(clip(e.getClientIp(), 64));
|
||||
row.setChanges(e.getChanges());
|
||||
repository.save(row);
|
||||
} catch (Exception ex) {
|
||||
// Class only: the payload carries actors and IPs.
|
||||
log.error("Audit event not stored: {}", ex.getClass().getName());
|
||||
} finally {
|
||||
BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders()
|
||||
.get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
|
||||
if (originalMessage != null) {
|
||||
originalMessage.ack();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Column widths of audit_event: over-long text is cut so the insert cannot fail. */
|
||||
private static String clip(String v, int max) {
|
||||
return v == null || v.length() <= max ? v : v.substring(0, max);
|
||||
}
|
||||
|
||||
private void updateAppSession(ResponseTime bean) {
|
||||
try {
|
||||
if (bean.getSourcePlatform().equals(GeneralEnum.CmsPlatform.APP)
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.solvway.services.log.repo;
|
||||
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public interface AuditEventLogRepository extends JpaRepository<AuditEventLog, Long> {
|
||||
|
||||
/** A null filter is ignored; {@code to} is exclusive. */
|
||||
@Query("select e from AuditEventLog e where (:actor is null or e.actor = :actor)"
|
||||
+ " and (:module is null or e.module = :module) and (:action is null or e.action = :action)"
|
||||
+ " and (:outcome is null or e.outcome = :outcome)"
|
||||
+ " and (:from is null or e.occurredAt >= :from)"
|
||||
+ " and (:to is null or e.occurredAt < :to)")
|
||||
Page<AuditEventLog> search(@Param("actor") String actor, @Param("module") String module,
|
||||
@Param("action") String action, @Param("outcome") String outcome,
|
||||
@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, Pageable pageable);
|
||||
|
||||
/** Deletes up to {@code limit} old rows; each call is its own transaction. */
|
||||
@Transactional
|
||||
@Modifying
|
||||
@Query(value = "DELETE FROM audit_event WHERE occurred_at < :cutoff LIMIT :limit", nativeQuery = true)
|
||||
int deleteBatchOlderThan(@Param("cutoff") LocalDateTime cutoff, @Param("limit") int limit);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.solvway.services.log.service;
|
||||
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Component
|
||||
public class AuditEventLogPurge {
|
||||
private static final Logger log = LoggerFactory.getLogger(AuditEventLogPurge.class);
|
||||
private static final int BATCH = 5000;
|
||||
|
||||
private final AuditEventLogRepository repository;
|
||||
private final int retentionDays;
|
||||
|
||||
public AuditEventLogPurge(AuditEventLogRepository repository,
|
||||
@Value("${audit.retention-days:${AUDIT_RETENTION_DAYS:730}}") int retentionDays) {
|
||||
this.repository = repository;
|
||||
this.retentionDays = retentionDays;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0 30 3 * * *")
|
||||
public void purge() {
|
||||
LocalDateTime cutoff = LocalDateTime.now().minusDays(retentionDays);
|
||||
long total = 0;
|
||||
int n;
|
||||
do {
|
||||
n = repository.deleteBatchOlderThan(cutoff, BATCH);
|
||||
total += n;
|
||||
} while (n > 0);
|
||||
log.info("Audit purge deleted {} rows older than {}", total, cutoff);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.solvway.services.log.controller;
|
||||
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuditEventControllerTest {
|
||||
|
||||
private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class);
|
||||
private final AuditEventController controller = new AuditEventController(repository);
|
||||
|
||||
private ArgumentCaptor<Pageable> pageable = ArgumentCaptor.forClass(Pageable.class);
|
||||
private ArgumentCaptor<LocalDateTime> from = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
private ArgumentCaptor<LocalDateTime> to = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
|
||||
private Map<String, Object> search(AuditEventController.SearchRequest r) {
|
||||
AuditEventLog row = new AuditEventLog();
|
||||
Page<AuditEventLog> page = new PageImpl<>(List.of(row));
|
||||
when(repository.search(any(), any(), any(), any(), any(), any(), any())).thenReturn(page);
|
||||
return controller.search(r);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesExactFiltersAndInclusiveDateRange() {
|
||||
Map<String, Object> res = search(new AuditEventController.SearchRequest(
|
||||
"a@x.com", "LEADS", "lead.update", "FAILURE", "2026-11-01", "2026-11-30", 2, 50));
|
||||
|
||||
verify(repository).search(org.mockito.ArgumentMatchers.eq("a@x.com"), org.mockito.ArgumentMatchers.eq("LEADS"),
|
||||
org.mockito.ArgumentMatchers.eq("lead.update"), org.mockito.ArgumentMatchers.eq("FAILURE"),
|
||||
from.capture(), to.capture(), pageable.capture());
|
||||
assertThat(from.getValue()).isEqualTo(LocalDateTime.of(2026, 11, 1, 0, 0));
|
||||
assertThat(to.getValue()).isEqualTo(LocalDateTime.of(2026, 12, 1, 0, 0));
|
||||
assertThat(pageable.getValue().getPageNumber()).isEqualTo(2);
|
||||
assertThat(pageable.getValue().getPageSize()).isEqualTo(50);
|
||||
assertThat(pageable.getValue().getSort())
|
||||
.isEqualTo(Sort.by(Sort.Direction.DESC, "occurredAt").and(Sort.by(Sort.Direction.DESC, "id")));
|
||||
assertThat(res).containsEntry("totalElements", 1L).containsEntry("number", 2).containsEntry("size", 50);
|
||||
assertThat((List<?>) res.get("content")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankFiltersAreIgnoredAndPagingDefaults() {
|
||||
search(new AuditEventController.SearchRequest(" ", "", null, "", "", null, -3, 0));
|
||||
|
||||
verify(repository).search(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), pageable.capture());
|
||||
assertThat(pageable.getValue().getPageNumber()).isZero();
|
||||
assertThat(pageable.getValue().getPageSize()).isEqualTo(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeIsCappedAtOneHundred() {
|
||||
search(new AuditEventController.SearchRequest(null, null, null, null, null, null, null, 5000));
|
||||
|
||||
verify(repository).search(any(), any(), any(), any(), any(), any(), pageable.capture());
|
||||
assertThat(pageable.getValue().getPageSize()).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedDateAnswers400() {
|
||||
assertThatThrownBy(() -> controller.search(
|
||||
new AuditEventController.SearchRequest(null, null, null, null, "30/11/2026", null, 0, 20)))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailUnknownIdAnswers404() {
|
||||
when(repository.findById(9L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> controller.get(9L))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturnsTheRow() {
|
||||
AuditEventLog row = new AuditEventLog();
|
||||
when(repository.findById(1L)).thenReturn(Optional.of(row));
|
||||
|
||||
assertThat(controller.get(1L)).isSameAs(row);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package com.solvway.services.log.pubsub;
|
||||
|
||||
import com.google.cloud.spring.pubsub.support.BasicAcknowledgeablePubsubMessage;
|
||||
import com.google.cloud.spring.pubsub.support.GcpPubSubHeaders;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import com.solvway.services.log.util.RedisUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageHandler;
|
||||
import org.springframework.messaging.support.MessageBuilder;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuditEventListenerTest {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private final RedisUtil<String> redisUtil = mock(RedisUtil.class);
|
||||
private final PubSubUtil pubSubUtil = mock(PubSubUtil.class);
|
||||
private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class);
|
||||
private final BasicAcknowledgeablePubsubMessage original = mock(BasicAcknowledgeablePubsubMessage.class);
|
||||
private final MessageHandler handler =
|
||||
new PubSubListener(redisUtil, pubSubUtil).auditEventMessageReceiver(repository);
|
||||
|
||||
private Message<byte[]> message() {
|
||||
return MessageBuilder.withPayload(new byte[0]).setHeader(GcpPubSubHeaders.ORIGINAL_MESSAGE, original).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void savesEveryFieldAndAcks() {
|
||||
AuditEvent e = new AuditEvent();
|
||||
e.setCompanyId(7L);
|
||||
e.setOccurredAt(LocalDateTime.of(2026, 11, 30, 10, 0));
|
||||
e.setActor("admin@x.com");
|
||||
e.setModule("LEADS");
|
||||
e.setAction("lead.update");
|
||||
e.setHttpMethod("PUT");
|
||||
e.setPathTemplate("/api/admin/leads/{id}");
|
||||
e.setTargetId("42");
|
||||
e.setOutcome(AuditEvent.OUTCOME_SUCCESS);
|
||||
e.setHttpStatus(200);
|
||||
e.setClientIp("10.0.0.1");
|
||||
e.setChanges("{\"fields\":[\"name\"]}");
|
||||
when(pubSubUtil.convertToOriginalObject(any(), any())).thenReturn(e);
|
||||
|
||||
handler.handleMessage(message());
|
||||
|
||||
ArgumentCaptor<AuditEventLog> c = ArgumentCaptor.forClass(AuditEventLog.class);
|
||||
verify(repository).save(c.capture());
|
||||
AuditEventLog r = c.getValue();
|
||||
assertThat(r.getCompanyId()).isEqualTo(7L);
|
||||
assertThat(r.getOccurredAt()).isEqualTo(e.getOccurredAt());
|
||||
assertThat(r.getActor()).isEqualTo("admin@x.com");
|
||||
assertThat(r.getModule()).isEqualTo("LEADS");
|
||||
assertThat(r.getAction()).isEqualTo("lead.update");
|
||||
assertThat(r.getHttpMethod()).isEqualTo("PUT");
|
||||
assertThat(r.getPathTemplate()).isEqualTo("/api/admin/leads/{id}");
|
||||
assertThat(r.getTargetId()).isEqualTo("42");
|
||||
assertThat(r.getOutcome()).isEqualTo("SUCCESS");
|
||||
assertThat(r.getHttpStatus()).isEqualTo(200);
|
||||
assertThat(r.getClientIp()).isEqualTo("10.0.0.1");
|
||||
assertThat(r.getChanges()).isEqualTo("{\"fields\":[\"name\"]}");
|
||||
verify(original).ack();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cutsOversizeStringsToColumnWidth() {
|
||||
AuditEvent e = new AuditEvent();
|
||||
e.setActor("a".repeat(300));
|
||||
e.setAction("b".repeat(300));
|
||||
e.setPathTemplate("p".repeat(300));
|
||||
e.setClientIp("i".repeat(100));
|
||||
when(pubSubUtil.convertToOriginalObject(any(), any())).thenReturn(e);
|
||||
|
||||
handler.handleMessage(message());
|
||||
|
||||
ArgumentCaptor<AuditEventLog> c = ArgumentCaptor.forClass(AuditEventLog.class);
|
||||
verify(repository).save(c.capture());
|
||||
assertThat(c.getValue().getActor()).hasSize(191);
|
||||
assertThat(c.getValue().getAction()).hasSize(128);
|
||||
assertThat(c.getValue().getPathTemplate()).hasSize(255);
|
||||
assertThat(c.getValue().getClientIp()).hasSize(64);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acksEvenWhenSaveFails() {
|
||||
when(pubSubUtil.convertToOriginalObject(any(), any())).thenReturn(new AuditEvent());
|
||||
when(repository.save(any())).thenThrow(new IllegalStateException("db down"));
|
||||
|
||||
handler.handleMessage(message());
|
||||
|
||||
verify(original).ack();
|
||||
verify(original, never()).nack();
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.solvway.services.log.service;
|
||||
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuditEventLogPurgeTest {
|
||||
|
||||
private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class);
|
||||
|
||||
private LocalDateTime purgeCutoff(int retentionDays) {
|
||||
when(repository.deleteBatchOlderThan(any(), org.mockito.ArgumentMatchers.anyInt())).thenReturn(0);
|
||||
new AuditEventLogPurge(repository, retentionDays).purge();
|
||||
ArgumentCaptor<LocalDateTime> c = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
verify(repository).deleteBatchOlderThan(c.capture(), org.mockito.ArgumentMatchers.anyInt());
|
||||
return c.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cutoffIsNowMinusConfiguredRetention() {
|
||||
for (int days : new int[] {730, 30}) {
|
||||
org.mockito.Mockito.reset(repository);
|
||||
LocalDateTime expected = LocalDateTime.now().minusDays(days);
|
||||
assertThat(Duration.between(purgeCutoff(days), expected).abs()).isLessThan(Duration.ofSeconds(5));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletesInBatchesUntilNoRowsLeft() {
|
||||
when(repository.deleteBatchOlderThan(any(), org.mockito.ArgumentMatchers.anyInt()))
|
||||
.thenReturn(5000, 5000, 120, 0);
|
||||
|
||||
new AuditEventLogPurge(repository, 730).purge();
|
||||
|
||||
verify(repository, times(4)).deleteBatchOlderThan(any(), org.mockito.ArgumentMatchers.anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retentionComesFromTheAuditRetentionDaysProperty() throws Exception {
|
||||
var ctor = AuditEventLogPurge.class.getDeclaredConstructors()[0];
|
||||
var value = ctor.getParameters()[1].getAnnotation(org.springframework.beans.factory.annotation.Value.class);
|
||||
assertThat(value.value()).isEqualTo("${audit.retention-days:${AUDIT_RETENTION_DAYS:730}}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user