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) {
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.mobile.api.useraccess.AppAccessAspect;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** Controllers in controller subpackages (admin controllers live in controller.admin) must pass the access aspect. */
|
||||
class AdminControllerPointcutTest {
|
||||
|
||||
static class ProbeController {
|
||||
public String handler() {
|
||||
return "ok";
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessAspectCoversControllerSubpackages() throws Exception {
|
||||
Method advice = AppAccessAspect.class.getMethod("appAccessAuthCheck", org.aspectj.lang.ProceedingJoinPoint.class);
|
||||
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
|
||||
pointcut.setExpression(advice.getAnnotation(Around.class).value());
|
||||
|
||||
Method handler = ProbeController.class.getMethod("handler");
|
||||
assertThat(pointcut.matches(handler, ProbeController.class)).isTrue();
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
class AdminAuthenticationServiceTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
service = new AdminAuthenticationService(rest);
|
||||
when(rest.getURLforApiService(any())).thenReturn("http://auth/findUserByToken/{area}/{token}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void liveToken_loadsUserInBoArea() {
|
||||
User u = new User();
|
||||
when(rest.getForEntity(any(String.class), eq(User.class), eq("BO"), eq("tok")))
|
||||
.thenReturn(ResponseEntity.ok(u));
|
||||
assertThat(service.loadUserByToken("tok")).isSameAs(u);
|
||||
}
|
||||
|
||||
@Test
|
||||
void non200_returnsNull() {
|
||||
when(rest.getForEntity(any(String.class), eq(User.class), eq("BO"), eq("tok")))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.NO_CONTENT));
|
||||
assertThat(service.loadUserByToken("tok")).isNull();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
class AdminModuleAccessTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
when(rest.getURLforApiService(any())).thenReturn("http://system/module/findAllByArea/{area}");
|
||||
when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO")))
|
||||
.thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("name", "BO_LEADS", "roles", List.of(Map.of("id", 5), Map.of("id", 6L))),
|
||||
Map.of("name", "BO_USERS", "roles", List.of(Map.of("id", 9))),
|
||||
Map.of("name", "BO_EMPTY"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleGrantedModule_isGranted() {
|
||||
assertThat(AdminModuleAccess.grantedAny(rest, Set.of(6L), "BO_LEADS")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anyOfSeveralModules_isGranted() {
|
||||
assertThat(AdminModuleAccess.grantedAny(rest, Set.of(9L), "BO_LEADS", "BO_USERS")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleWithoutGrant_isDenied() {
|
||||
assertThat(AdminModuleAccess.grantedAny(rest, Set.of(9L), "BO_LEADS")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleWithNoRoles_orUnknownModule_isDenied() {
|
||||
assertThat(AdminModuleAccess.grantedAny(rest, Set.of(5L), "BO_EMPTY")).isFalse();
|
||||
assertThat(AdminModuleAccess.grantedAny(rest, Set.of(5L), "NOPE")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noModulesDeclared_isDenied() {
|
||||
assertThat(AdminModuleAccess.grantedAny(rest, Set.of(5L))).isFalse();
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.LoginStatus;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AdminSessionGuardTest {
|
||||
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminSessionGuard guard;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
guard = new AdminSessionGuard(auth);
|
||||
}
|
||||
|
||||
private static User user(boolean enabled, LoginStatus login) {
|
||||
User u = new User();
|
||||
u.setEnabled(enabled);
|
||||
u.setLogin(login);
|
||||
return u;
|
||||
}
|
||||
|
||||
private void assertStatus(boolean allowPending, HttpStatus expected) {
|
||||
assertThatThrownBy(() -> guard.check("tok", allowPending))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrRevokedToken_lookupNull_isUnauthorized() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(null);
|
||||
assertStatus(false, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deactivatedAdmin_isUnauthorized() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(false, LoginStatus.Y));
|
||||
assertStatus(false, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingPasswordChange_isForbidden() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(true, LoginStatus.N));
|
||||
assertStatus(false, HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingPasswordChange_allowedWhenHandlerOptsIn() {
|
||||
User u = user(true, LoginStatus.N);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
assertThat(guard.check("tok", true)).isSameAs(u);
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeAdmin_returnsUser() {
|
||||
User u = user(true, LoginStatus.Y);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
assertThat(guard.check("tok", false)).isSameAs(u);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deactivatedAdmin_withPendingReset_stillUnauthorized() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(false, LoginStatus.N));
|
||||
assertStatus(true, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingPasswordChange_carriesCodeForThePortal() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(true, LoginStatus.N));
|
||||
assertThatThrownBy(() -> guard.check("tok", false))
|
||||
.isInstanceOf(org.springframework.web.server.ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((org.springframework.web.server.ResponseStatusException) ex)
|
||||
.getBody().getProperties()).containsEntry("code", "PASSWORD_RESET_REQUIRED"));
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
|
||||
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.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.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.core.ParameterizedTypeReference;
|
||||
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.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.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Admin guard on /api/admin/** paths: token type, session state, module authorisation. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
@SuppressWarnings("unchecked")
|
||||
class AppAccessAspectAdminTest {
|
||||
|
||||
private static final String API_KEY = "valid-api-key";
|
||||
private static final String TOK = "admin-tok";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private PubSubConfig pubSubConfig;
|
||||
@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;
|
||||
|
||||
@AdminModule("BO_LEADS")
|
||||
static class Target {
|
||||
@AppAuth
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
public void anyAdmin() {
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_USERS")
|
||||
public void methodWins() {
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
public void classLevel() {
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
|
||||
public void firstLogin() {
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
public void publicLogin() {
|
||||
}
|
||||
}
|
||||
|
||||
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
|
||||
static class PendingAtClassLevel {
|
||||
@AppAuth
|
||||
public void handler() {
|
||||
}
|
||||
}
|
||||
|
||||
static class Undeclared {
|
||||
@AppAuth
|
||||
public void handler() {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuthAppKeyConfig cfg = new AuthAppKeyConfig();
|
||||
cfg.setList(List.of(API_KEY));
|
||||
aspect = new AppAccessAspect(memberService, userService, pubSubConfig, pubSubTemplate, pubSubUtil, cfg,
|
||||
authenticationService, jwtTokenUtil, guard, rest);
|
||||
when(rest.getURLforApiService(any())).thenReturn("http://system/module/findAllByArea/{area}");
|
||||
when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO")))
|
||||
.thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("name", "BO_LEADS", "roles", List.of(Map.of("id", 5))),
|
||||
Map.of("name", "BO_USERS", "roles", List.of(Map.of("id", 9), Map.of("id", 2))))));
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/admin/things");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clear() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
private void target(Class<?> type, String name) throws Exception {
|
||||
Method m = type.getMethod(name);
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.getMethod()).thenReturn(m);
|
||||
when(methodSignature.getDeclaringType()).thenReturn(type);
|
||||
when(methodSignature.toShortString()).thenReturn(type.getSimpleName() + "." + name + "()");
|
||||
}
|
||||
|
||||
private void http(MockedStatic<HttpReqRespUtils> h, String jwt, String userType) {
|
||||
h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY);
|
||||
h.when(HttpReqRespUtils::getJwtToken).thenReturn(jwt);
|
||||
when(jwtTokenUtil.isTokenExpired(jwt)).thenReturn(false);
|
||||
when(jwtTokenUtil.getCustomClaimFromToken(jwt, JwtCustomClaim.USERTYPE)).thenReturn(userType);
|
||||
}
|
||||
|
||||
private static User admin(Long... roleIds) {
|
||||
User u = new User();
|
||||
u.setEnabled(true);
|
||||
for (Long id : roleIds) {
|
||||
Role r = new Role();
|
||||
r.setId(id);
|
||||
u.getRoles().add(r);
|
||||
}
|
||||
return u;
|
||||
}
|
||||
|
||||
private void expect(HttpStatus status) throws Throwable {
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(status));
|
||||
verify(joinPoint, never()).proceed();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noToken_isUnauthorized() throws Throwable {
|
||||
target(Target.class, "anyAdmin");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, "", "A");
|
||||
expect(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberToken_isForbidden_adminAccessRequired() throws Throwable {
|
||||
target(Target.class, "anyAdmin");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, "member-tok", "M");
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, ex -> {
|
||||
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(ex.getReason()).isEqualTo("Admin access required");
|
||||
});
|
||||
verify(guard, never()).check(any(), org.mockito.ArgumentMatchers.anyBoolean());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminClaimWithRevokedOrUnknownToken_isUnauthorized() throws Throwable {
|
||||
target(Target.class, "anyAdmin");
|
||||
when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token"));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deactivatedAdmin_isUnauthorized() throws Throwable {
|
||||
target(Target.class, "anyAdmin");
|
||||
when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Account disabled"));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingPasswordChange_isForbidden() throws Throwable {
|
||||
target(Target.class, "anyAdmin");
|
||||
when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "PASSWORD_RESET_REQUIRED"));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingPasswordChange_handlerThatAllowsItIsPassedTheFlag() throws Throwable {
|
||||
target(Target.class, "firstLogin");
|
||||
when(guard.check(TOK, true)).thenReturn(admin(5L));
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anyAdmin_passesForNonSuperAdminWithoutModuleLookup() throws Throwable {
|
||||
target(Target.class, "anyAdmin");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(77L));
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
verify(rest, never()).getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void methodModule_winsOverClassModule() throws Throwable {
|
||||
target(Target.class, "methodWins");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(5L)); // role 5 holds BO_LEADS (class), not BO_USERS (method)
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void classModule_appliesWhenMethodUndeclared_andGrantedRolePasses() throws Throwable {
|
||||
target(Target.class, "classLevel");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(5L));
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminRole1_bypassesModuleCheck() throws Throwable {
|
||||
target(Target.class, "methodWins");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(1L));
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void undeclaredHandler_isForbiddenForNonSuperAdmin() throws Throwable {
|
||||
target(Undeclared.class, "handler");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(5L));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleLookupFailure_failsClosed() throws Throwable {
|
||||
target(Target.class, "classLevel");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(5L));
|
||||
when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO")))
|
||||
.thenThrow(new IllegalStateException("system down"));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipValidateHandler_onAdminPath_isNotGuarded() throws Throwable {
|
||||
target(Target.class, "publicLogin");
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, "", "A");
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
verify(guard, never()).check(any(), org.mockito.ArgumentMatchers.anyBoolean());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonAdminPath_isNotAffected() throws Throwable {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/members");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
|
||||
target(Undeclared.class, "handler");
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, "member-tok", "M");
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
verify(guard, never()).check(any(), org.mockito.ArgumentMatchers.anyBoolean());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowPendingReset_isIgnoredAtClassLevel() throws Throwable {
|
||||
target(PendingAtClassLevel.class, "handler");
|
||||
when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "PASSWORD_RESET_REQUIRED"));
|
||||
when(guard.check(TOK, true)).thenReturn(admin(5L));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void injectedRoleAdmin2_doesNotGrantModules() throws Throwable {
|
||||
// services-auth adds ROLE_ADMIN (id 2) to every admin, so a grant to role 2 must not count.
|
||||
target(Target.class, "methodWins");
|
||||
when(guard.check(TOK, false)).thenReturn(admin(2L, 77L));
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
http(h, TOK, "A");
|
||||
expect(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user