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

@@ -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();
}
}