feat: switched-on password rules for the hint, named refusals

The system exposes the switched-on admin password rules. mobile-api
serves them to signed-in admins and, rate limited, on an exact public
route for the first-login screen. Every admin password path now refuses
with PASSWORD_RULE naming the first rule broken.

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-12-02 02:25:10 +08:00
1 parent 0b201a51ca
commit 5e68478670
15 files changed
+494 -3

No files matched your search

@@ -0,0 +1,54 @@
package com.solvway.mobile.api.service;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
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 PasswordRuleHintServiceTest {
private final RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
private final PublicRegistrationService reg = mock(PublicRegistrationService.class);
private final PasswordRuleHintService service = new PasswordRuleHintService(rest, reg);
PasswordRuleHintServiceTest() {
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
when(rest.getForEntity(eq("/passwordRule/adminActive"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok(List.of(Map.of("param", "INPUT_LENGTH_MIN", "value", "8"))));
}
@Test
void active_readsTheSwitchedOnAdminRules() {
assertThat(service.active()).containsExactly(Map.of("param", "INPUT_LENGTH_MIN", "value", "8"));
}
@Test
void publicActive_isRateLimitedPerIp_beforeAnyRead() {
service.publicActive();
verify(reg).limit(startsWith("pwr:"), eq(60), anyString());
}
@Test
void active_nullBodyIsEmptyList() {
when(rest.getForEntity(eq("/passwordRule/adminActive"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok().build());
assertThat(service.active()).isEmpty();
}
private static String startsWith(String p) {
return org.mockito.ArgumentMatchers.startsWith(p);
}
}
@@ -0,0 +1,165 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.controller.admin.AdminAuthController;
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
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.MockedStatic;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.HashMap;
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.mock;
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;
/**
* Spec: symbol rule on with value 2 and a password with one symbol -> 400 PASSWORD_RULE naming
* SYMBOLIC_LENGTH_MIN and 2, on every admin password path. The real AdminAuthenticationService runs
* over a mocked services-system, which refuses the password (setAdminPassword 0 / firstTimeLogin false /
* changeAdminPassword PASSWORD_POLICY) and lists the failing rules.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
class PasswordRuleRefusalTest {
private static final String PW = "Onesymbol#1";
private RestTemplateCustomUtil rest;
private AdminAuthenticationService auth;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
auth = new AdminAuthenticationService(rest);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
// services-system lists the failing rules: the symbol rule first, then a later one
when(rest.postForEntity(eq("/user/validatePasswordFromRulesForAdmin"), eq(List.class), any()))
.thenReturn(ResponseEntity.ok(List.of(
Map.of("param", "SYMBOLIC_LENGTH_MIN", "value", "2"),
Map.of("param", "INPUT_LENGTH_MIN", "value", "12"))));
}
@AfterEach
void close() { http.close(); }
private static void assertRule(Throwable t) {
assertThat(t).isInstanceOf(CodedResponseStatusException.class);
CodedResponseStatusException e = (CodedResponseStatusException) t;
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo("PASSWORD_RULE");
assertThat(e.getBody().getDetail()).isEqualTo("PASSWORD_RULE");
assertThat(e.getBody().getProperties()).containsEntry("param", "SYMBOLIC_LENGTH_MIN").containsEntry("value", "2");
}
@Test
void requirePasswordRules_namesTheFirstFailedRule() {
assertThatThrownBy(() -> auth.requirePasswordRules(PW)).satisfies(PasswordRuleRefusalTest::assertRule);
}
@Test
void requirePasswordRules_passesWhenNoRuleFails() {
when(rest.postForEntity(eq("/user/validatePasswordFromRulesForAdmin"), eq(List.class), any()))
.thenReturn(ResponseEntity.ok(List.of()));
auth.requirePasswordRules(PW); // no throw
}
@Test
void createUser_withPassword_isRefusedByName() {
AdminUserService users = new AdminUserService(rest, auth);
AdminUserRequest req = new AdminUserRequest("N", null, "n", "n@x.com", true, List.of(new AdminRoleRef(4L, "ROLE_SALES")),
PW, PW, null, null);
assertThatThrownBy(() -> users.create(req)).satisfies(PasswordRuleRefusalTest::assertRule);
}
@Test
void setTemporaryPassword_isRefusedByName() {
AdminAuthenticationService spy = org.mockito.Mockito.spy(auth);
User boss = new User();
boss.setId(1L);
com.solvway.core.model.Role superRole = new com.solvway.core.model.Role();
superRole.setId(1L);
boss.setRoles(List.of(superRole));
org.mockito.Mockito.doReturn(boss).when(spy).loadUserByToken("tok");
Map<String, Object> row = new HashMap<>(Map.of("id", 5L, "type", "A", "username", "u", "enabled", true));
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(5L)))
.thenReturn(ResponseEntity.ok(row));
AdminUserService users = new AdminUserService(rest, spy);
assertThatThrownBy(() -> users.setTemporaryPassword(5L, PW, PW)).satisfies(PasswordRuleRefusalTest::assertRule);
}
@Test
void changeOwnPassword_policyRefusal_isNamed() throws Exception {
User u = new User();
u.setId(9L);
u.setUsername("admin.user");
AdminAuthenticationService spy = org.mockito.Mockito.spy(auth);
org.mockito.Mockito.doReturn(u).when(spy).loadUserByToken("tok");
org.mockito.Mockito.doReturn(false).when(spy).isLocked("admin.user");
when(rest.postForEntity(eq("/user/changeAdminPassword"), eq(String.class), any()))
.thenReturn(ResponseEntity.ok("PASSWORD_POLICY"));
MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminAuthController(spy, mock(AuthenticationService.class))).build();
Exception ex = mvc.perform(post("/api/admin/auth/change-password").contentType(MediaType.APPLICATION_JSON)
.content("{\"currentPassword\":\"old\",\"newPassword\":\"" + PW + "\",\"confirmPassword\":\"" + PW + "\"}"))
.andReturn().getResolvedException();
assertRule(ex);
}
@Test
void changeOwnPassword_wrongCurrent_keepsItsReason() throws Exception {
User u = new User();
u.setId(9L);
u.setUsername("admin.user");
AdminAuthenticationService spy = org.mockito.Mockito.spy(auth);
org.mockito.Mockito.doReturn(u).when(spy).loadUserByToken("tok");
org.mockito.Mockito.doReturn(false).when(spy).isLocked("admin.user");
org.mockito.Mockito.doNothing().when(spy).record(any(), any(), any());
when(rest.postForEntity(eq("/user/changeAdminPassword"), eq(String.class), any()))
.thenReturn(ResponseEntity.ok("CURRENT_PASSWORD_WRONG"));
MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminAuthController(spy, mock(AuthenticationService.class))).build();
Exception ex = mvc.perform(post("/api/admin/auth/change-password").contentType(MediaType.APPLICATION_JSON)
.content("{\"currentPassword\":\"old\",\"newPassword\":\"" + PW + "\",\"confirmPassword\":\"" + PW + "\"}"))
.andReturn().getResolvedException();
assertThat(((CodedResponseStatusException) ex).getCode()).isEqualTo("CURRENT_PASSWORD_WRONG");
verify(rest, never()).postForEntity(eq("/user/validatePasswordFromRulesForAdmin"), any(Class.class), any());
}
@Test
void firstLogin_isRefusedByName() throws Exception {
User u = new User();
u.setId(9L);
u.setLogin(com.solvway.core.enums.GeneralEnum.LoginStatus.N);
AdminAuthenticationService spy = org.mockito.Mockito.spy(auth);
org.mockito.Mockito.doReturn(u).when(spy).loadUserByToken("tok");
when(rest.postForEntity(eq("/user/firstTimeLogin"), eq(Boolean.class), any())).thenReturn(ResponseEntity.ok(false));
MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminAuthController(spy, mock(AuthenticationService.class))).build();
Exception ex = mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON)
.content("{\"newPassword\":\"" + PW + "\"}")).andReturn().getResolvedException();
assertRule(ex);
}
}