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:
ngqileandClaude Opus 5.5 committed 2026-11-26 19:44:03 +08:00
1 parent 72b724f468
commit 0a990cbcaf
16 files changed
+850 -8

No files matched your search

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