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:
1 parent
d715073ab2
commit
1523dc566b
12 files changed
+596
-10
No files matched your search
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -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) {
|
||||
|
||||
+2
@@ -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")
|
||||
|
||||
+2
@@ -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")
|
||||
|
||||
+2
@@ -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")
|
||||
|
||||
+2
@@ -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")
|
||||
|
||||
+3
@@ -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) {
|
||||
|
||||
+125
-9
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user