feat(mobile-api): admin guard on /api/admin/** (admin token, session state, module grants)
Ported from babyboo: @AdminModule, AdminModuleAccess, AdminSessionGuard and the admin branch of AppAccessAspect. Adds the BO area, and services-auth findUserByToken now returns no user for a logged-out token. 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
72b724f468
commit
0a990cbcaf
16 files changed
+850
-8
No files matched your search
+24
@@ -0,0 +1,24 @@
|
||||
package com.solvway.mobile.api.errorhandler;
|
||||
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
/**
|
||||
* A {@link ResponseStatusException} carrying a machine-readable {@code code} on its ProblemDetail
|
||||
* body, so the admin portal can act on it (e.g. {@code PASSWORD_RESET_REQUIRED} sends the user to
|
||||
* the password-change page). Ported from babyboo, without the details map.
|
||||
*/
|
||||
public class CodedResponseStatusException extends ResponseStatusException {
|
||||
|
||||
private final String code;
|
||||
|
||||
public CodedResponseStatusException(HttpStatusCode status, String reason, String code) {
|
||||
super(status, reason);
|
||||
this.code = code;
|
||||
getBody().setProperty("code", code);
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuthenticationService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
/** Admin user for a live token, or null (services-auth returns null for a logged-out token). */
|
||||
public User loadUserByToken(String token) {
|
||||
ResponseEntity<User> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_SYSTEM_GET_USER_BYTOKEN),
|
||||
User.class, "BO", token);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Declares which BO module(s) an {@code /api/admin/**} handler needs. {@code AppAccessAspect}
|
||||
* allows a caller holding any one of them (or super-admin, role id 1). A method-level
|
||||
* declaration wins over the class-level one; an undeclared handler grants nothing to non-super
|
||||
* admins. {@link #ANY_ADMIN} means any authenticated admin.
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
public @interface AdminModule {
|
||||
|
||||
String ANY_ADMIN = "ANY_ADMIN";
|
||||
|
||||
String[] value();
|
||||
|
||||
/**
|
||||
* Lets an admin whose first-login password change is pending ({@code login = N}) through. Only
|
||||
* for the first-login and logout handlers; every other admin handler answers 403 while pending.
|
||||
* Read from the method annotation only; ignored on a class.
|
||||
*/
|
||||
boolean allowPendingReset() default false;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public final class AdminModuleAccess {
|
||||
|
||||
private static final String MODULES_BY_AREA = "/module/findAllByArea/{area}";
|
||||
|
||||
private AdminModuleAccess() {
|
||||
}
|
||||
|
||||
/** True when one of {@code roleIds} is granted any of the named BO modules. */
|
||||
public static boolean grantedAny(RestTemplateCustomUtil restTemplateUtil, Set<Long> roleIds, String... moduleNames) {
|
||||
if (moduleNames.length == 0) {
|
||||
return false;
|
||||
}
|
||||
Set<String> wanted = Set.of(moduleNames);
|
||||
ResponseEntity<List<Map<String, Object>>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(MODULES_BY_AREA),
|
||||
new ParameterizedTypeReference<List<Map<String, Object>>>() {}, "BO");
|
||||
List<Map<String, Object>> modules = ent.getBody() != null ? ent.getBody() : List.of();
|
||||
return modules.stream()
|
||||
.filter(m -> m.get("name") instanceof String name && wanted.contains(name))
|
||||
.anyMatch(m -> m.get("roles") instanceof List<?> roles && roles.stream()
|
||||
.anyMatch(r -> r instanceof Map<?, ?> rm && rm.get("id") instanceof Number n
|
||||
&& roleIds.contains(n.longValue())));
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.LoginStatus;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
/** Per-request admin session state. Not cached, so logout and deactivation bite on the next call. */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AdminSessionGuard {
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public User check(String jwt, boolean allowPendingReset) {
|
||||
User user = adminAuthenticationService.loadUserByToken(jwt);
|
||||
if (user == null) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token");
|
||||
}
|
||||
if (!user.isEnabled()) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Account disabled");
|
||||
}
|
||||
if (user.getLogin() == LoginStatus.N && !allowPendingReset) {
|
||||
throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Password change required", "PASSWORD_RESET_REQUIRED");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
+105
-5
@@ -4,6 +4,8 @@ import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
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.Role;
|
||||
import com.solvway.core.model.ResponseTime;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
@@ -17,13 +19,14 @@ 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.HeaderRedactionUtil;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
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.stereotype.Component;
|
||||
@@ -32,12 +35,18 @@ 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.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AppAccessAspect {
|
||||
|
||||
@@ -49,7 +58,36 @@ public class AppAccessAspect {
|
||||
private final AuthAppKeyConfig authAppKey;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final JwtTokenUtil jwtTokenUtil;
|
||||
@Around("execution(* com.solvway.mobile.api.controller.*.*(..))")
|
||||
private final AdminSessionGuard adminSessionGuard;
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
@Autowired
|
||||
public AppAccessAspect(MemberService memberService, UserService userService, PubSubConfig pubSubConfig,
|
||||
PubSubTemplate pubSubTemplate, PubSubUtil pubSubUtil, AuthAppKeyConfig authAppKey,
|
||||
AuthenticationService authenticationService, JwtTokenUtil jwtTokenUtil,
|
||||
AdminSessionGuard adminSessionGuard, RestTemplateCustomUtil restTemplateUtil) {
|
||||
this.memberService = memberService;
|
||||
this.userService = userService;
|
||||
this.pubSubConfig = pubSubConfig;
|
||||
this.pubSubTemplate = pubSubTemplate;
|
||||
this.pubSubUtil = pubSubUtil;
|
||||
this.authAppKey = authAppKey;
|
||||
this.authenticationService = authenticationService;
|
||||
this.jwtTokenUtil = jwtTokenUtil;
|
||||
this.adminSessionGuard = adminSessionGuard;
|
||||
this.restTemplateUtil = restTemplateUtil;
|
||||
}
|
||||
|
||||
// ponytail: pre-admin-guard signature kept so the existing non-admin tests compile unchanged;
|
||||
// admin paths fail closed without the guard. Drop it once those tests take the full constructor.
|
||||
AppAccessAspect(MemberService memberService, UserService userService, PubSubConfig pubSubConfig,
|
||||
PubSubTemplate pubSubTemplate, PubSubUtil pubSubUtil, AuthAppKeyConfig authAppKey,
|
||||
AuthenticationService authenticationService, JwtTokenUtil jwtTokenUtil) {
|
||||
this(memberService, userService, pubSubConfig, pubSubTemplate, pubSubUtil, authAppKey,
|
||||
authenticationService, jwtTokenUtil, null, null);
|
||||
}
|
||||
|
||||
@Around("execution(* com.solvway.mobile.api.controller..*.*(..))")
|
||||
public Object appAccessAuthCheck(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
long start = System.currentTimeMillis();
|
||||
String methodSig = joinPoint.getSignature().toShortString();
|
||||
@@ -66,7 +104,8 @@ public class AppAccessAspect {
|
||||
}
|
||||
try {
|
||||
if(!shouldSkipAuth(joinPoint)){
|
||||
validateJwt();
|
||||
String jwt = validateJwt();
|
||||
requireAdminAccess(joinPoint, jwt);
|
||||
requireVerifiedPhoneForCp(joinPoint, apiKey);
|
||||
}
|
||||
return joinPoint.proceed();
|
||||
@@ -175,7 +214,7 @@ public class AppAccessAspect {
|
||||
};
|
||||
}
|
||||
|
||||
private void validateJwt() {
|
||||
private String validateJwt() {
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
if (!StringUtils.hasLength(jwt)) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'Authorization'");
|
||||
@@ -189,6 +228,67 @@ public class AppAccessAspect {
|
||||
if (isTokenExpired) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Expired Token");
|
||||
}
|
||||
return jwt;
|
||||
}
|
||||
|
||||
private static final long SUPER_ADMIN_ROLE_ID = 1L;
|
||||
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) {
|
||||
if (!isAdminPath()) {
|
||||
return;
|
||||
}
|
||||
if (!"A".equals(userTypeClaim(jwt))) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Admin access required");
|
||||
}
|
||||
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
|
||||
AdminModule onMethod = method.getAnnotation(AdminModule.class);
|
||||
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());
|
||||
if (declared != null && Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)) {
|
||||
return;
|
||||
}
|
||||
Set<Long> roleIds = admin.getRoles() == null ? Set.of() : admin.getRoles().stream()
|
||||
.map(Role::getId).filter(Objects::nonNull)
|
||||
// services-auth findUserByToken adds ROLE_ADMIN to every admin, so it never grants a module.
|
||||
.filter(id -> id != INJECTED_ROLE_ADMIN_ID)
|
||||
.collect(Collectors.toSet());
|
||||
if (roleIds.contains(SUPER_ADMIN_ROLE_ID)) {
|
||||
return;
|
||||
}
|
||||
boolean granted = false;
|
||||
if (declared != null) {
|
||||
try {
|
||||
granted = AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, declared.value());
|
||||
} catch (Exception ex) {
|
||||
log.error("[AppAccessAspect] admin module lookup failed, failing closed: {}", ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
if (!granted) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Admin module access denied");
|
||||
}
|
||||
}
|
||||
|
||||
private String userTypeClaim(String jwt) {
|
||||
try {
|
||||
Object type = jwtTokenUtil.getCustomClaimFromToken(jwt, JwtCustomClaim.USERTYPE);
|
||||
return type == null ? null : type.toString();
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isAdminPath() {
|
||||
if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) {
|
||||
return false;
|
||||
}
|
||||
HttpServletRequest request = attrs.getRequest();
|
||||
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
String path = pattern != null ? pattern.toString()
|
||||
: (StringUtils.hasLength(request.getServletPath()) ? request.getServletPath() : request.getRequestURI());
|
||||
return path != null && path.startsWith("/api/admin/");
|
||||
}
|
||||
|
||||
private String maskKey(String key) {
|
||||
|
||||
Reference in new issue
Block a user