feat: mobile-api records admin writes and sensitive reads as 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:
ngqileandClaude Opus 5.5 committed 2026-11-30 16:10:14 +08:00
1 parent d715073ab2
commit 1523dc566b
12 files changed
+596 -10

No files matched your search

@@ -31,7 +31,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
## 3. mobile-api
- [ ] 3.1 Recording in `AppAccessAspect`, with `Audited` and `AuditChanges` (design decisions 3, 4 and 6).
- [x] 3.1 Recording in `AppAccessAspect`, with `Audited` and `AuditChanges` (design decisions 3, 4 and 6).
- Add annotations on the lead export, the event-lead export, the email detail (sensitive) and event-lead `match` (skip).
- Tests first:
- a write records every field: actor, module, action, method, template, target, outcome and IP;
@@ -27,6 +27,9 @@ public class PubSubConfig {
@Value("${pubsub.response-time-log.topic}")
public String responseTimeLogTopic;
@Value("${pubsub.audit-event.topic}")
public String auditEventTopic;
@Value("${pubsub.email.save-request.topic}")
public String emailSaveRequestTopic;
@@ -35,6 +38,7 @@ public class PubSubConfig {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, responseTimeLogTopic));
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, emailSaveRequestTopic));
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, auditEventTopic));
}
}
}
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminEmailService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@@ -34,6 +35,7 @@ public class AdminEmailController {
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size));
}
@Audited(action = "EMAIL_VIEW")
@AppAuth
@GetMapping("/emails/{id}")
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
import com.solvway.mobile.api.service.AdminEventLeadService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@@ -48,6 +49,7 @@ public class AdminEventLeadController {
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
}
@Audited(skip = true)
@AppAuth
@AdminModule("BO_EVENT_LEADS")
@PostMapping("/{eventUuid}/match")
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminEventLeadService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.RestController;
public class AdminEventLeadExportController {
private final AdminEventLeadService adminEventLeadService;
@Audited(action = "EVENT_LEAD_EXPORT")
@AppAuth
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_EVENT_LEADS")
@GetMapping("/{eventUuid}/export")
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
import com.solvway.mobile.api.service.AdminLeadService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -34,6 +35,7 @@ public class AdminLeadController {
return ResponseEntity.ok(adminLeadService.list(q, page, size));
}
@Audited(action = "LEAD_EXPORT")
@AppAuth
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_LEADS")
@GetMapping("/export")
@@ -7,6 +7,7 @@ import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
import com.solvway.mobile.api.service.AdminAclService;
import com.solvway.mobile.api.service.AdminRoleService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -52,6 +53,7 @@ public class AdminRoleController {
public ResponseEntity<List<AdminModuleGrant>> getModules(@PathVariable Long id) {
return ResponseEntity.ok(adminAclService.getGrantTree(id));
}
@Audited(action = "ROLE_SET_MODULES")
@AppAuth
@AdminModule("BO_ROLES")
@PutMapping("/roles/{id}/modules")
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
import com.solvway.mobile.api.service.AdminUserService;
import com.solvway.mobile.api.useraccess.AdminModule;
import com.solvway.mobile.api.useraccess.Audited;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -49,12 +50,14 @@ public class AdminUserController {
return ResponseEntity.ok(adminUserService.update(id, request));
}
@Audited(action = "USER_SEND_PASSWORD_RESET")
@AppAuth
@PostMapping("/users/{id}/resetPassword")
public ResponseEntity<Map<String, Object>> resetPassword(@PathVariable Long id) {
return ResponseEntity.ok(Map.of("updated", adminUserService.resetPassword(id)));
}
@Audited(action = "USER_SET_TEMPORARY_PASSWORD")
@AppAuth
@PostMapping("/users/{id}/password")
public ResponseEntity<Void> setPassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
@@ -1,10 +1,12 @@
package com.solvway.mobile.api.useraccess;
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.core.annotation.AppAuth;
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
import com.solvway.core.model.AuditEvent;
import com.solvway.core.model.Role;
import com.solvway.core.model.ResponseTime;
import com.solvway.core.model.User;
@@ -15,6 +17,7 @@ import com.solvway.core.utils.SnowflakeIdWorker;
import com.solvway.core.utils.StackTraceUtil;
import com.solvway.mobile.api.config.AuthAppKeyConfig;
import com.solvway.mobile.api.config.PubSubConfig;
import com.solvway.mobile.api.controller.admin.AdminAuthController;
import com.solvway.mobile.api.service.AuthenticationService;
import com.solvway.mobile.api.service.MemberService;
import com.solvway.mobile.api.service.UserService;
@@ -29,6 +32,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
@@ -40,6 +44,7 @@ import org.springframework.web.servlet.HandlerMapping;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@@ -102,29 +107,139 @@ public class AppAccessAspect {
maskKey(apiKey), authAppKey.getList().size());
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'");
}
User[] admin = new User[1];
Object result = null;
Throwable thrown = null;
try {
if(!shouldSkipAuth(joinPoint)){
String jwt = validateJwt();
requireAdminAccess(joinPoint, jwt);
requireAdminAccess(joinPoint, jwt, admin);
requireVerifiedPhoneForCp(joinPoint, apiKey);
}
return joinPoint.proceed();
result = joinPoint.proceed();
return result;
} catch (ResponseStatusException ex) {
thrown = ex;
log.warn("[AppAccessAspect] REJECT: {} for method={}", ex.getReason(), methodSig);
throw ex;
} catch (Exception ex) {
thrown = ex;
log.error(StackTraceUtil.getStackTraceAsJsonString(ex));
throw ex;
} catch (Error err) {
thrown = err;
throw err;
} finally {
long executionTime = System.currentTimeMillis() - start;
long uuid = SnowflakeIdWorker.getUUID();
String username = getUsernameFromJwt();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
publishLogSafely(logBean);
try {
long executionTime = System.currentTimeMillis() - start;
long uuid = SnowflakeIdWorker.getUUID();
String username = getUsernameFromJwt();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
publishLogSafely(logBean);
publishAudit(joinPoint, admin[0], result, thrown);
} finally {
AuditChanges.clear(); // pooled threads: never leave one request's changes for the next
}
}
}
/**
* Best-effort audit event for an admin call (add-admin-audit-log). Never throws: a failure is logged at WARN
* with the exception class only and the response is unaffected.
*/
private void publishAudit(ProceedingJoinPoint joinPoint, User admin, Object result, Throwable thrown) {
try {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
if (!isAdminPath() || !isAudited(method, requestOrNull().getMethod())) {
return;
}
int status = auditStatus(result, thrown);
String actor = admin != null ? admin.getUsername() : null;
if (actor == null && admin == null && status == HttpStatus.FORBIDDEN.value()) {
// Refused before the user was loaded (PASSWORD_RESET_REQUIRED): the actor is the admin token's user.
String jwt = HttpReqRespUtils.getJwtToken();
if ("A".equals(userTypeClaim(jwt))) {
actor = authenticationService.getUsernameFromToken(jwt);
}
}
if (actor == null) {
return;
}
HttpServletRequest request = requestOrNull();
AuditEvent event = new AuditEvent();
event.setCompanyId(admin != null ? admin.getCompanyId() : null);
event.setOccurredAt(LocalDateTime.now());
event.setActor(actor);
AdminModule onMethod = method.getAnnotation(AdminModule.class);
AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class);
event.setModule(declared == null || Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)
? null : String.join(",", declared.value()));
Audited audited = method.getAnnotation(Audited.class);
event.setAction(audited != null && StringUtils.hasText(audited.action()) ? audited.action()
: defaultAuditAction(method.getDeclaringClass().getSimpleName(), method.getName()));
event.setHttpMethod(request.getMethod());
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
event.setPathTemplate(pattern == null ? null : pattern.toString());
if (request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) instanceof Map<?, ?> vars
&& !vars.isEmpty()) {
event.setTargetId(String.valueOf(vars.values().iterator().next()));
}
event.setHttpStatus(status);
event.setOutcome(status >= 200 && status < 300 ? AuditEvent.OUTCOME_SUCCESS : AuditEvent.OUTCOME_FAILURE);
String ip = request.getHeader("X-Client-Ip");
event.setClientIp(ip == null || ip.length() <= 64 ? ip : ip.substring(0, 64));
Map<String, Object> changes = AuditChanges.current();
if (changes != null && !changes.isEmpty()) {
event.setChanges(AUDIT_JSON.writeValueAsString(changes));
}
pubSubUtil.publishMessage(pubSubTemplate, pubSubConfig.auditEventTopic, event);
} catch (Exception ex) {
log.warn("[AppAccessAspect] audit event dropped: {}", ex.getClass().getSimpleName());
}
}
private static final ObjectMapper AUDIT_JSON = new ObjectMapper();
private static HttpServletRequest requestOrNull() {
return RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs
? attrs.getRequest() : null;
}
/** Writes, and GETs marked {@code @Audited}, unless skipped; login, logout and the like are never recorded. */
private static boolean isAudited(Method method, String httpMethod) {
Audited audited = method.getAnnotation(Audited.class);
if (audited != null && audited.skip()) {
return false;
}
if (method.getDeclaringClass() == AdminAuthController.class && !"firstLogin".equals(method.getName())) {
return false;
}
return !"GET".equalsIgnoreCase(httpMethod) || audited != null;
}
/** {@code AdminUserController.update} becomes {@code USER_UPDATE}. */
static String defaultAuditAction(String simpleClassName, String methodName) {
String type = simpleClassName.replaceFirst("^Admin(?=.)", "").replaceFirst("(?<=.)Controller$", "");
return upperSnake(type) + "_" + upperSnake(methodName);
}
private static String upperSnake(String camel) {
return camel.replaceAll("([a-z0-9])([A-Z])", "$1_$2")
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
.toUpperCase(java.util.Locale.ROOT);
}
private static int auditStatus(Object result, Throwable thrown) {
if (thrown instanceof ResponseStatusException rse) {
return rse.getStatusCode().value();
}
if (thrown != null) {
return HttpStatus.INTERNAL_SERVER_ERROR.value();
}
return result instanceof ResponseEntity<?> entity ? entity.getStatusCode().value() : HttpStatus.OK.value();
}
private String getUsernameFromJwt() {
String username = "APP_PUBLIC";
String jwt = HttpReqRespUtils.getJwtToken();
@@ -235,7 +350,7 @@ public class AppAccessAspect {
private static final long INJECTED_ROLE_ADMIN_ID = 2L;
/** Admin paths: admin token, live and enabled session, and a granted BO module. Fails closed. */
private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt) {
private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt, User[] adminOut) {
if (!isAdminPath()) {
return;
}
@@ -247,6 +362,7 @@ public class AppAccessAspect {
AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class);
// allowPendingReset is honoured on the method only, so it never opens a whole controller.
User admin = adminSessionGuard.check(jwt, onMethod != null && onMethod.allowPendingReset());
adminOut[0] = admin;
if (declared != null && Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)) {
return;
}
@@ -0,0 +1,49 @@
package com.solvway.mobile.api.useraccess;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* What an audited handler changed, collected for the current request thread and attached to its audit event by
* {@link AppAccessAspect}, which always clears it afterwards. Callers pass allow-listed fields only: never
* passwords, tokens or identity numbers.
*/
public final class AuditChanges {
private static final ThreadLocal<Map<String, Object>> CURRENT = new ThreadLocal<>();
private AuditChanges() {
}
/** One allow-listed field's value before and after the change. */
public static void put(String field, Object before, Object after) {
Map<String, Object> changes = CURRENT.get();
if (changes == null) {
changes = new LinkedHashMap<>();
CURRENT.set(changes);
}
Map<String, Object> change = new LinkedHashMap<>();
change.put("before", before);
change.put("after", after);
changes.put(field, change);
}
/** Names of the fields that changed, without values. */
public static void fields(String... names) {
Map<String, Object> changes = CURRENT.get();
if (changes == null) {
changes = new LinkedHashMap<>();
CURRENT.set(changes);
}
changes.put("fields", List.of(names));
}
static Map<String, Object> current() {
return CURRENT.get();
}
static void clear() {
CURRENT.remove();
}
}
@@ -0,0 +1,22 @@
package com.solvway.mobile.api.useraccess;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Audit marking for an {@code /api/admin/**} handler, read by {@link AppAccessAspect}. Every non-GET handler is
* audited by default; this annotation names the action, makes a sensitive GET audited, or {@code skip = true}
* excludes a read-only POST.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Audited {
/** Stable action key; empty means derived from the controller and method name. */
String action() default "";
/** Never audit this handler (read-only POST). */
boolean skip() default false;
}
@@ -0,0 +1,382 @@
package com.solvway.mobile.api.useraccess;
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
import com.solvway.core.model.AuditEvent;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.core.utils.JwtTokenUtil;
import com.solvway.core.utils.PubSubUtil;
import com.solvway.mobile.api.config.AuthAppKeyConfig;
import com.solvway.mobile.api.config.PubSubConfig;
import com.solvway.mobile.api.controller.admin.AdminAuthController;
import com.solvway.mobile.api.service.AuthenticationService;
import com.solvway.mobile.api.service.MemberService;
import com.solvway.mobile.api.service.UserService;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.HandlerMapping;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-admin-audit-log: what AppAccessAspect records for /api/admin/** calls. */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class AppAccessAspectAuditTest {
private static final String API_KEY = "valid-api-key";
private static final String TOK = "admin-tok";
private static final String TOPIC = "audit-event-topic";
@Mock private PubSubTemplate pubSubTemplate;
@Mock private PubSubUtil pubSubUtil;
@Mock private AuthenticationService authenticationService;
@Mock private JwtTokenUtil jwtTokenUtil;
@Mock private ProceedingJoinPoint joinPoint;
@Mock private MethodSignature methodSignature;
@Mock private AdminSessionGuard guard;
@Mock private RestTemplateCustomUtil rest;
private AppAccessAspect aspect;
private MockHttpServletRequest req;
@AdminModule("BO_USERS")
static class AdminUserController {
@AdminModule("BO_ROLES")
public void update() {
}
public void classModule() {
}
@Audited(action = "USER_SET_TEMPORARY_PASSWORD")
public void setPassword() {
}
@Audited(action = "LEAD_EXPORT")
public void export() {
}
@Audited(skip = true)
public void match() {
}
}
@BeforeEach
void setUp() {
AuthAppKeyConfig cfg = new AuthAppKeyConfig();
cfg.setList(List.of(API_KEY));
PubSubConfig pubSubConfig = mock(PubSubConfig.class);
pubSubConfig.auditEventTopic = TOPIC;
aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), pubSubConfig,
pubSubTemplate, pubSubUtil, cfg, authenticationService, jwtTokenUtil, guard, rest);
req = new MockHttpServletRequest("PUT", "/api/admin/users/42");
req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/admin/users/{id}");
Map<String, String> vars = new LinkedHashMap<>();
vars.put("id", "42");
req.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, vars);
req.addHeader("X-Client-Ip", "203.0.113.7");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
}
@AfterEach
void clear() {
RequestContextHolder.resetRequestAttributes();
AuditChanges.clear();
}
private void handler(Class<?> type, String name) {
Method m = Arrays.stream(type.getMethods()).filter(x -> x.getName().equals(name)).findFirst().orElseThrow();
when(joinPoint.getSignature()).thenReturn(methodSignature);
when(methodSignature.getMethod()).thenReturn(m);
when(methodSignature.toShortString()).thenReturn(type.getSimpleName() + "." + name + "()");
}
private User admin(Long... roleIds) {
User u = new User();
u.setEnabled(true);
u.setUsername("alice");
u.setCompanyId(7L);
for (Long id : roleIds) {
Role r = new Role();
r.setId(id);
u.getRoles().add(r);
}
when(guard.check(eq(TOK), any(Boolean.class))).thenReturn(u);
return u;
}
private Object call() throws Throwable {
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY);
h.when(HttpReqRespUtils::getJwtToken).thenReturn(TOK);
when(jwtTokenUtil.isTokenExpired(TOK)).thenReturn(false);
when(jwtTokenUtil.getCustomClaimFromToken(TOK, JwtCustomClaim.USERTYPE)).thenReturn("A");
return aspect.appAccessAuthCheck(joinPoint);
}
}
private AuditEvent published() {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
verify(pubSubUtil).publishMessage(eq(pubSubTemplate), eq(TOPIC), captor.capture());
return (AuditEvent) captor.getValue();
}
private void notPublished() {
verify(pubSubUtil, never()).publishMessage(any(PubSubTemplate.class), eq(TOPIC), any());
}
@Test
void write_recordsEveryField() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenReturn(ResponseEntity.ok("x"));
call();
AuditEvent e = published();
assertThat(e.getActor()).isEqualTo("alice");
assertThat(e.getCompanyId()).isEqualTo(7L);
assertThat(e.getModule()).isEqualTo("BO_ROLES");
assertThat(e.getAction()).isEqualTo("USER_UPDATE");
assertThat(e.getHttpMethod()).isEqualTo("PUT");
assertThat(e.getPathTemplate()).isEqualTo("/api/admin/users/{id}");
assertThat(e.getTargetId()).isEqualTo("42");
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_SUCCESS);
assertThat(e.getHttpStatus()).isEqualTo(200);
assertThat(e.getClientIp()).isEqualTo("203.0.113.7");
assertThat(e.getOccurredAt()).isNotNull();
assertThat(e.getChanges()).isNull();
}
@Test
void module_fallsBackToClassLevel() throws Throwable {
handler(AdminUserController.class, "classModule");
admin(1L);
call();
assertThat(published().getModule()).isEqualTo("BO_USERS");
}
@Test
void actionCodes_derivedAndExplicit() throws Throwable {
assertThat(AppAccessAspect.defaultAuditAction("AdminUserController", "update")).isEqualTo("USER_UPDATE");
assertThat(AppAccessAspect.defaultAuditAction("AdminEventLeadController", "putModules"))
.isEqualTo("EVENT_LEAD_PUT_MODULES");
assertThat(AppAccessAspect.defaultAuditAction("LeadThing", "exportPDF")).isEqualTo("LEAD_THING_EXPORT_PDF");
req.setMethod("GET");
handler(AdminUserController.class, "export");
admin(1L);
call();
assertThat(published().getAction()).isEqualTo("LEAD_EXPORT");
}
@Test
void nonSuccessResponseEntity_recordsFailureWithStatus() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenReturn(ResponseEntity.status(HttpStatus.CONFLICT).build());
call();
AuditEvent e = published();
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
assertThat(e.getHttpStatus()).isEqualTo(409);
}
@Test
void redirectResponseEntity_isNotASuccess() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenReturn(ResponseEntity.status(HttpStatus.FOUND).build());
call();
AuditEvent e = published();
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
assertThat(e.getHttpStatus()).isEqualTo(302);
}
@Test
void anyAdminHandler_recordsNoModule() throws Throwable {
req.setMethod("POST");
handler(AdminAuthController.class, "firstLogin");
admin(1L);
call();
assertThat(published().getModule()).isNull();
}
@Test
void auditChanges_areClearedEvenWhenTheLogStepThrows() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenAnswer(i -> {
AuditChanges.fields("phone");
return ResponseEntity.ok("x");
});
try (MockedStatic<com.solvway.core.utils.SnowflakeIdWorker> ids = mockStatic(com.solvway.core.utils.SnowflakeIdWorker.class)) {
ids.when(com.solvway.core.utils.SnowflakeIdWorker::getUUID).thenThrow(new RuntimeException("clock moved backwards"));
assertThatThrownBy(this::call).isInstanceOf(RuntimeException.class);
}
assertThat(AuditChanges.current()).isNull();
}
@Test
void thrownResponseStatusException_recordsFailureWithStatus() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "bad"));
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
AuditEvent e = published();
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
assertThat(e.getHttpStatus()).isEqualTo(400);
}
@Test
void otherException_recordsFailure500() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenThrow(new IllegalStateException("boom"));
assertThatThrownBy(this::call).isInstanceOf(IllegalStateException.class);
AuditEvent e = published();
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
assertThat(e.getHttpStatus()).isEqualTo(500);
}
@Test
void moduleNotGranted_isRecordedAsFailure403() throws Throwable {
handler(AdminUserController.class, "update");
admin(5L); // not super admin, no grants
when(rest.getURLforApiService(any())).thenReturn("http://system/x");
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
verify(joinPoint, never()).proceed();
AuditEvent e = published();
assertThat(e.getActor()).isEqualTo("alice");
assertThat(e.getCompanyId()).isEqualTo(7L);
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
assertThat(e.getHttpStatus()).isEqualTo(403);
}
@Test
void passwordResetRequired_actorFromToken_isRecordedAsFailure403() throws Throwable {
handler(AdminUserController.class, "update");
when(guard.check(eq(TOK), any(Boolean.class)))
.thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "PASSWORD_RESET_REQUIRED"));
when(authenticationService.getUsernameFromToken(TOK)).thenReturn("alice");
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
AuditEvent e = published();
assertThat(e.getActor()).isEqualTo("alice");
assertThat(e.getHttpStatus()).isEqualTo(403);
}
@Test
void plainGet_isNotRecorded() throws Throwable {
req.setMethod("GET");
handler(AdminUserController.class, "update");
admin(1L);
call();
notPublished();
}
@Test
void skippedPost_isNotRecorded() throws Throwable {
req.setMethod("POST");
handler(AdminUserController.class, "match");
admin(1L);
call();
notPublished();
}
@Test
void authControllerEndpoints_notRecorded_exceptFirstLogin() throws Throwable {
req.setMethod("POST");
admin(1L);
for (String name : List.of("changePassword", "logout", "refresh")) {
handler(AdminAuthController.class, name);
call();
}
notPublished();
handler(AdminAuthController.class, "firstLogin");
call();
assertThat(published().getAction()).isEqualTo("AUTH_FIRST_LOGIN");
}
@Test
void noValidToken_isNotRecorded() throws Throwable {
handler(AdminUserController.class, "update");
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY);
h.when(HttpReqRespUtils::getJwtToken).thenReturn("");
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint)).isInstanceOf(ResponseStatusException.class);
}
notPublished();
}
@Test
void invalidAdminSession_401_isNotRecorded() throws Throwable {
handler(AdminUserController.class, "update");
when(guard.check(eq(TOK), any(Boolean.class)))
.thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token"));
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
notPublished();
}
@Test
void publishFailure_doesNotChangeTheResponse() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
ResponseEntity<String> ok = ResponseEntity.ok("x");
when(joinPoint.proceed()).thenReturn(ok);
doThrow(new IllegalStateException("pubsub down")).when(pubSubUtil)
.publishMessage(any(PubSubTemplate.class), eq(TOPIC), any());
assertThat(call()).isSameAs(ok);
}
@Test
void auditChanges_landInChangesJson_andAreClearedAfterwards() throws Throwable {
handler(AdminUserController.class, "update");
admin(1L);
when(joinPoint.proceed()).thenAnswer(inv -> {
AuditChanges.put("enabled", true, false);
AuditChanges.fields("name");
return ResponseEntity.ok("x");
});
call();
AuditEvent e = published();
assertThat(e.getChanges()).contains("\"enabled\":{\"before\":true,\"after\":false}")
.contains("\"fields\":[\"name\"]");
org.mockito.Mockito.clearInvocations(pubSubUtil);
org.mockito.Mockito.doReturn(ResponseEntity.ok("y")).when(joinPoint).proceed(); // when(..) would re-run the answer above
call();
assertThat(published().getChanges()).isNull();
}
}