diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 0062123..d04e049 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -14,7 +14,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 3. mobile-api admin guard -- [ ] 3.1 Port `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin branch of babyboo's `AppAccessAspect` (admin-path detection, admin-token check via `/auth/findUserByToken/BO/{token}`, revocation, deactivated and pending-reset handling, `requireAdminModule` with super-admin bypass, fail closed) into Co-Lite's `AppAccessAspect`, without country scope or audit. Port babyboo's tests for these classes and add tests for every `admin-access` "Admin endpoint guard" and "Logout" scenario plus: deactivated token gives 401, pending reset gives 403 except first-login and logout, undeclared handler denied to non-super admin. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 3.1 Port `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin branch of babyboo's `AppAccessAspect` (admin-path detection, admin-token check via `/auth/findUserByToken/BO/{token}`, revocation, deactivated and pending-reset handling, `requireAdminModule` with super-admin bypass, fail closed) into Co-Lite's `AppAccessAspect`, without country scope or audit. Port babyboo's tests for these classes and add tests for every `admin-access` "Admin endpoint guard" and "Logout" scenario plus: deactivated token gives 401, pending reset gives 403 except first-login and logout, undeclared handler denied to non-super admin. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: `solvway-mobile-api/src/main/java/**/useraccess/**`, `solvway-mobile-api/src/test/java/**/useraccess/**`, `solvway-mobile-api/src/main/resources/application*.yml` ## 4. mobile-api admin auth diff --git a/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java b/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java index 7d6d24a..2db3ab4 100644 --- a/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java +++ b/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java @@ -8,7 +8,7 @@ public class GeneralEnum { @Getter public enum Area { - A("ADMIN"), M("MEMBER"), P("PUBLIC"), B("STOCKIST"), AP("APPS"); + A("ADMIN"), M("MEMBER"), P("PUBLIC"), B("STOCKIST"), AP("APPS"), BO("BACKOFFICE_PORTAL"); private final String name; Area(String name) { diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java new file mode 100644 index 0000000..0cfedc5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java @@ -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; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java new file mode 100644 index 0000000..6819ced --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java @@ -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 ent = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_SYSTEM_GET_USER_BYTOKEN), + User.class, "BO", token); + return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java new file mode 100644 index 0000000..5f54f2e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java @@ -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; +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java new file mode 100644 index 0000000..33ffb11 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java @@ -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 roleIds, String... moduleNames) { + if (moduleNames.length == 0) { + return false; + } + Set wanted = Set.of(moduleNames); + ResponseEntity>> ent = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(MODULES_BY_AREA), + new ParameterizedTypeReference>>() {}, "BO"); + List> 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()))); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java new file mode 100644 index 0000000..394f6e5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java @@ -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; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index 68932d3..252e6a2 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -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 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) { diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java new file mode 100644 index 0000000..9e7101e --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java @@ -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(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java new file mode 100644 index 0000000..7f79662 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java @@ -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(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java new file mode 100644 index 0000000..ab69289 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java @@ -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(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java new file mode 100644 index 0000000..6517a90 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java @@ -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")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java new file mode 100644 index 0000000..a6be84b --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java @@ -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 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 h = mockStatic(HttpReqRespUtils.class)) { + http(h, "", "A"); + expect(HttpStatus.UNAUTHORIZED); + } + } + + @Test + void memberToken_isForbidden_adminAccessRequired() throws Throwable { + target(Target.class, "anyAdmin"); + try (MockedStatic 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 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 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 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 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 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 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 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 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 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 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 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 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 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 h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } +} diff --git a/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java b/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java index 2b2b57b..c29f7e5 100644 --- a/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java +++ b/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java @@ -380,6 +380,10 @@ public class JwtAuthenticationController { @RequestMapping({ "/findUserByToken/{area}/{token}" }) public User findUserByToken(@PathVariable("area") Area area, @PathVariable("token") String token) { + // A logged-out token (see logoutToken) resolves to no user. + if (redisUtil.getValue(token) != null) { + return null; + } String username = jwtTokenUtil.getUsernameFromToken(token); User user = null; diff --git a/solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java b/solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java new file mode 100644 index 0000000..9a27ff3 --- /dev/null +++ b/solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java @@ -0,0 +1,35 @@ +package com.solvway.services.auth.controller; + +import com.solvway.core.enums.GeneralEnum.Area; +import com.solvway.services.auth.service.SystemService; +import com.solvway.services.auth.util.RedisUtil; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FindUserByTokenRevocationTest { + + @Mock + private RedisUtil redisUtil; + @Mock + private SystemService systemService; + @InjectMocks + private JwtAuthenticationController controller; + + @Test + void loggedOutTokenResolvesToNoUser() { + when(redisUtil.getValue("tok")).thenReturn("tok"); + + assertThat(controller.findUserByToken(Area.BO, "tok")).isNull(); + verify(systemService, never()).findUserByUsernameWithPassword(any()); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java b/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java index 9a24552..007bcc7 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java @@ -7,7 +7,7 @@ public class SystemConstants { @Getter public enum Area { - A("ADMIN"),M("MEMBER"),P("PUBLIC"),B("STOCKIST"), AP("APPS"); + A("ADMIN"),M("MEMBER"),P("PUBLIC"),B("STOCKIST"), AP("APPS"), BO("BACKOFFICE_PORTAL"); private final String name; Area(String name) { this.name=name;