From 39708224ad62d202f2e5ef14c6e4f5d727a17742 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 13:43:42 +0800 Subject: [PATCH] feat: lock check and login history on admin sign-in and sign-out Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../specs/admin-login-security/spec.md | 2 +- .../changes/add-admin-login-security/tasks.md | 2 +- .../api/RestApiSystemServiceConstants.java | 4 + .../controller/admin/AdminAuthController.java | 20 +- .../service/AdminAuthenticationService.java | 39 ++++ .../AdminAuthControllerLoginSecurityTest.java | 179 ++++++++++++++++++ ...uthenticationServiceLoginSecurityTest.java | 106 +++++++++++ 7 files changed, 349 insertions(+), 3 deletions(-) create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerLoginSecurityTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceLoginSecurityTest.java diff --git a/openspec/changes/add-admin-login-security/specs/admin-login-security/spec.md b/openspec/changes/add-admin-login-security/specs/admin-login-security/spec.md index 3ff134d..d002c1a 100644 --- a/openspec/changes/add-admin-login-security/specs/admin-login-security/spec.md +++ b/openspec/changes/add-admin-login-security/specs/admin-login-security/spec.md @@ -2,7 +2,7 @@ ### Requirement: Login history -The system SHALL record every admin sign-in attempt, sign-out, unlock and own password change, with the time, username as typed, event, client IP, user agent and, for a known username, the user's company. Events: `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED`. Recording SHALL be best-effort and MUST NOT change the sign-in answer. A blank username or password SHALL NOT be recorded. +The system SHALL record every admin sign-in attempt, sign-out, unlock and own password change, with the time, trimmed username, event, client IP, user agent and, for a known username, the user's company. Events: `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED`. Recording SHALL be best-effort and MUST NOT change the sign-in answer. A blank username or password SHALL NOT be recorded. #### Scenario: Successful sign-in is recorded diff --git a/openspec/changes/add-admin-login-security/tasks.md b/openspec/changes/add-admin-login-security/tasks.md index 189e7c0..4fc9a65 100644 --- a/openspec/changes/add-admin-login-security/tasks.md +++ b/openspec/changes/add-admin-login-security/tasks.md @@ -47,7 +47,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before. ## 3. mobile-api -- [ ] 3.1 Sign-in and sign-out enforcement and recording (design decisions 5 and 6). +- [x] 3.1 Sign-in and sign-out enforcement and recording (design decisions 5 and 6). - **Tests first:** - blank fields record nothing; - locked returns 401 `ACCOUNT_LOCKED`, records `LOGIN_LOCKED`, and never calls services-auth; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 56d8a1c..93d25bc 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -91,6 +91,10 @@ public class RestApiSystemServiceConstants { public static final String API_REST_GENERIC_POST_FIND_BY_UUID = "/system/genericPost/findByUuid/{uuid}"; public static final String API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE = "/system/genericPost/content/findByPostUuidAndLocale/{uuid}/{locale}"; + //LoginSecurity (admin sign-in lock check and history) + public static final String API_REST_LOGIN_SECURITY_IS_LOCKED = "/loginSecurity/isLocked/{username}"; + public static final String API_REST_LOGIN_SECURITY_RECORD = "/loginSecurity/record"; + //Message public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}"; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java index 5c91606..49f7028 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java @@ -34,6 +34,8 @@ import java.util.Map; public class AdminAuthController { private static final Map BAD_LOGIN = Map.of("result", "false", "message", "Invalid username or password"); + private static final Map ACCOUNT_LOCKED = Map.of("result", "false", "code", "ACCOUNT_LOCKED", + "message", "Too many failed sign-ins. Try again later or ask an administrator to unlock your account."); private final AdminAuthenticationService adminAuthenticationService; private final AuthenticationService authenticationService; @@ -44,6 +46,11 @@ public class AdminAuthController { if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN); } + String username = request.getUsername().trim(); + if (adminAuthenticationService.isLocked(username)) { + adminAuthenticationService.record(username, "LOGIN_LOCKED", null); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ACCOUNT_LOCKED); + } String token; User u; try { @@ -60,8 +67,10 @@ public class AdminAuthController { token = null; } if (u == null) { + adminAuthenticationService.record(username, "LOGIN_FAIL", null); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN); } + adminAuthenticationService.record(username, "LOGIN_SUCCESS", null); return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(), GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false")); } @@ -105,7 +114,16 @@ public class AdminAuthController { @AppAuth @PostMapping("/auth/logout") public ResponseEntity> logout() { - authenticationService.logoutToken(HttpReqRespUtils.getJwtToken()); + String token = HttpReqRespUtils.getJwtToken(); + try { + User u = adminAuthenticationService.loadUserByToken(token); // before the token is revoked + if (u != null) { + adminAuthenticationService.record(u.getUsername(), "LOGOUT", null); + } + } catch (Exception e) { + log.warn("Logout history skipped: {}", e.getClass().getSimpleName()); + } + authenticationService.logoutToken(token); return ResponseEntity.ok(Map.of("result", "true")); } 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 index 9167b38..ff612e1 100644 --- 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 @@ -5,16 +5,22 @@ import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants; import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; import com.solvway.mobile.api.model.AuthRequest; import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import java.util.HashMap; import java.util.List; import java.util.Map; @Service @RequiredArgsConstructor +@Slf4j public class AdminAuthenticationService { private final RestTemplateCustomUtil restTemplateUtil; @@ -65,4 +71,37 @@ public class AdminAuthenticationService { Integer.class, Map.of("username", username, "email", email)); return ent.getBody() == null ? 0 : ent.getBody(); } + + /** True when services-system says the account is locked; fails open (false) on any error so a fault never blocks sign-in. */ + public boolean isLocked(String username) { + try { + ResponseEntity ent = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_IS_LOCKED), + Map.class, username); + return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null + && Boolean.TRUE.equals(ent.getBody().get("locked")); + } catch (Exception e) { + log.warn("Login lock check failed, allowing sign-in: {}", e.getClass().getSimpleName()); + return false; + } + } + + /** Best-effort login history entry with the caller's X-Client-IP and User-Agent; never throws. */ + public void record(String username, String event, String message) { + try { + HttpServletRequest req = RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes a + ? a.getRequest() : null; + Map body = new HashMap<>(); + body.put("username", username); + body.put("event", event); + body.put("ip", req == null ? null : req.getHeader("X-Client-IP")); + body.put("userAgent", req == null ? null : req.getHeader("User-Agent")); + body.put("message", message); + restTemplateUtil.postForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_RECORD), + String.class, body); + } catch (Exception e) { + log.warn("Login history record failed: {}", e.getClass().getSimpleName()); + } + } } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerLoginSecurityTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerLoginSecurityTest.java new file mode 100644 index 0000000..006f437 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerLoginSecurityTest.java @@ -0,0 +1,179 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.service.AdminAuthenticationService; +import com.solvway.mobile.api.service.AuthenticationService; +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.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminAuthControllerLoginSecurityTest { + + @Mock private AdminAuthenticationService auth; + @Mock private AuthenticationService authenticationService; + @InjectMocks private AdminAuthController controller; + + private MockMvc mvc; + private MockedStatic http; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + } + + @AfterEach + void close() { http.close(); } + + private User user(boolean enabled) { + User u = new User(); + u.setId(9L); + u.setName("Admin User"); + u.setUsername("admin"); + u.setEnabled(enabled); + u.setLogin(GeneralEnum.LoginStatus.Y); + u.setRoles(List.of(new Role("ROLE_ADMIN"))); + return u; + } + + private ResultActions login(String username, String password) throws Exception { + return mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}")); + } + + @Test + void blankFields_recordNothing_andSkipLockCheck() throws Exception { + login("admin", "").andExpect(status().isUnauthorized()); + login(" ", "pw").andExpect(status().isUnauthorized()); + verify(auth, never()).isLocked(anyString()); + verify(auth, never()).record(any(), any(), any()); + } + + @Test + void locked_is401AccountLocked_recordsLocked_andSkipsServicesAuth() throws Exception { + when(auth.isLocked("admin")).thenReturn(true); + + login("admin", "pw").andExpect(status().isUnauthorized()) + .andExpect(content().json("{\"result\":\"false\",\"code\":\"ACCOUNT_LOCKED\",\"message\":" + + "\"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.\"}")); + verify(auth).record("admin", "LOGIN_LOCKED", null); + verify(auth, never()).getToken(any()); + } + + @Test + void wrongPassword_recordsFail() throws Exception { + when(auth.getToken(any())).thenReturn(""); + + login("admin", "pw").andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("Invalid username or password")); + verify(auth).record("admin", "LOGIN_FAIL", null); + } + + @Test + void unknownUser_noToken_recordsFail() throws Exception { + when(auth.getToken(any())).thenReturn(null); + + login("ghost", "pw").andExpect(status().isUnauthorized()); + verify(auth).record("ghost", "LOGIN_FAIL", null); + } + + @Test + void userNull_recordsFail() throws Exception { + when(auth.getToken(any())).thenReturn("t"); + when(auth.loadUserByToken("t")).thenReturn(null); + + login("admin", "pw").andExpect(status().isUnauthorized()); + verify(auth).record("admin", "LOGIN_FAIL", null); + } + + @Test + void disabledUser_recordsFail() throws Exception { + when(auth.getToken(any())).thenReturn("t"); + when(auth.loadUserByToken("t")).thenReturn(user(false)); + + login("admin", "pw").andExpect(status().isUnauthorized()); + verify(auth).record("admin", "LOGIN_FAIL", null); + } + + @Test + void restClientException_recordsFail() throws Exception { + when(auth.getToken(any())).thenThrow(new org.springframework.web.client.ResourceAccessException("down")); + + login("admin", "pw").andExpect(status().isUnauthorized()); + verify(auth).record("admin", "LOGIN_FAIL", null); + } + + @Test + void success_recordsSuccess() throws Exception { + when(auth.getToken(any())).thenReturn("t"); + when(auth.loadUserByToken("t")).thenReturn(user(true)); + + login("admin", "pw").andExpect(status().isOk()).andExpect(jsonPath("$.token").value("t")); + verify(auth).record("admin", "LOGIN_SUCCESS", null); + } + + @Test + void username_isTrimmedForLockCheckAndRecord() throws Exception { + when(auth.getToken(any())).thenReturn("t"); + when(auth.loadUserByToken("t")).thenReturn(user(true)); + + login(" admin ", "pw").andExpect(status().isOk()); + verify(auth).isLocked("admin"); + verify(auth).record("admin", "LOGIN_SUCCESS", null); + } + + @Test + void logout_recordsLogoutForTokenUser_beforeRevoking() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(user(true)); + + mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk()) + .andExpect(content().json("{\"result\":\"true\"}")); + verify(auth).record("admin", "LOGOUT", null); + verify(authenticationService).logoutToken("tok"); + } + + @Test + void logout_nullUser_recordsNothing() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(null); + + mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk()); + verify(auth, never()).record(any(), any(), any()); + verify(authenticationService).logoutToken("tok"); + } + + @Test + void logout_loadUserThrows_stillReturns200() throws Exception { + when(auth.loadUserByToken("tok")).thenThrow(new IllegalStateException("down")); + + mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk()) + .andExpect(content().json("{\"result\":\"true\"}")); + verify(authenticationService).logoutToken("tok"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceLoginSecurityTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceLoginSecurityTest.java new file mode 100644 index 0000000..02e1f4d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceLoginSecurityTest.java @@ -0,0 +1,106 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +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 java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminAuthenticationServiceLoginSecurityTest { + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + service = new AdminAuthenticationService(rest); + when(rest.getURLforApiService(any())).thenReturn("http://gw/loginSecurity/x"); + } + + @AfterEach + void clear() { RequestContextHolder.resetRequestAttributes(); } + + @Test + void isLocked_true() { + when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1"))) + .thenReturn(ResponseEntity.ok(Map.of("locked", true))); + assertThat(service.isLocked("sales1")).isTrue(); + } + + @Test + void isLocked_false() { + when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1"))) + .thenReturn(ResponseEntity.ok(Map.of("locked", false))); + assertThat(service.isLocked("sales1")).isFalse(); + } + + @Test + void isLocked_exception_failsOpen() { + when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1"))) + .thenThrow(new IllegalStateException("down")); + assertThat(service.isLocked("sales1")).isFalse(); + } + + @Test + void isLocked_non200_failsOpen() { + when(rest.getForEntity(any(String.class), eq(Map.class), eq("sales1"))) + .thenReturn(new ResponseEntity<>(HttpStatus.NO_CONTENT)); + assertThat(service.isLocked("sales1")).isFalse(); + } + + @Test + void record_swallowsExceptions() { + when(rest.postForEntity(any(String.class), eq(String.class), any())) + .thenThrow(new IllegalStateException("down")); + assertThatCode(() -> service.record("sales1", "LOGIN_FAIL", null)).doesNotThrowAnyException(); + } + + @Test + void record_sendsClientIpAndUserAgentFromRequest() { + MockHttpServletRequest req = new MockHttpServletRequest(); + req.addHeader("X-Client-IP", "203.0.113.7"); + req.addHeader("User-Agent", "JUnit"); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req)); + when(rest.postForEntity(any(String.class), eq(String.class), any())).thenReturn(ResponseEntity.ok("")); + + service.record("sales1", "LOGIN_FAIL", "why"); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(any(String.class), eq(String.class), body.capture()); + assertThat((Map) body.getValue()).containsOnly( + Map.entry("username", "sales1"), Map.entry("event", "LOGIN_FAIL"), Map.entry("ip", "203.0.113.7"), + Map.entry("userAgent", "JUnit"), Map.entry("message", "why")); + } + + @Test + void record_noHeaders_sendsNullIpAndUserAgent() { + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest())); + when(rest.postForEntity(any(String.class), eq(String.class), any())).thenReturn(ResponseEntity.ok("")); + + service.record("sales1", "LOGOUT", null); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(any(String.class), eq(String.class), body.capture()); + Map m = (Map) body.getValue(); + assertThat(m.get("ip")).isNull(); + assertThat(m.get("userAgent")).isNull(); + assertThat(m).containsEntry("event", "LOGOUT"); + } +}