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

@@ -17,7 +17,7 @@ Verify commands:
- Depends on: 1
- Scope: `solvway-services-counter/**`, `solvway-services-system/**`, `solvway-mobile-api/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter,solvway-services-system,solvway-mobile-api verify`
- [ ] 3. Password rules backend:
- [x] 3. Password rules backend:
- Switched-on admin rules `[{param, value}]` from system.
- mobile-api `GET /api/admin/password-rules/active` (any signed-in admin) and `GET /api/public/password-rules` (public, per-IP limited, gateway and public-path exemptions exact).
- The named refusal: `PASSWORD_RULE` with `param` and `value` on every admin password path (create user, set temporary, change own, first login, reset by link).
@@ -55,7 +55,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
publicPath(HttpMethod.POST, "/counter/eventGuest/register"),
publicPath(HttpMethod.GET, "/counter/checkin/findEvent/[A-Za-z0-9_-]{22}"),
publicPath(HttpMethod.POST, "/counter/checkin/lookup"),
publicPath(HttpMethod.POST, "/counter/checkin/byGuest"));
publicPath(HttpMethod.POST, "/counter/checkin/byGuest"),
// Password hint on public password screens: switched-on rule names and numbers only, no user data
publicPath(HttpMethod.GET, "/passwordRule/adminActive"));
private static Map.Entry<HttpMethod, Pattern> publicPath(HttpMethod method, String regex) {
return Map.entry(method, Pattern.compile(regex));
@@ -0,0 +1,74 @@
package com.solvway.gateway.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.gateway.model.AuthAppKey;
import com.solvway.gateway.model.AuthAppKeyMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.util.ReflectionTestUtils;
import reactor.core.publisher.Mono;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
/** The public password hint opens exactly GET /passwordRule/adminActive without a user token; nothing else opens. */
class JWTAuthFilterPasswordRulePathTest {
private static final String KEY = "gateway-test-key";
private JWTAuthFilter filter;
@BeforeEach
void setUp() throws Exception {
AuthAppKey key = new ObjectMapper().readValue(
"{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}",
AuthAppKey.class);
AuthAppKeyMap map = new AuthAppKeyMap();
map.add(KEY, key);
filter = new JWTAuthFilter();
ReflectionTestUtils.setField(filter, "authAppKeyMap", map);
}
private MockServerWebExchange call(HttpMethod method, String path) {
return MockServerWebExchange.from(MockServerHttpRequest.method(method, path)
.header("api-key", KEY)
.remoteAddress(new InetSocketAddress("127.0.0.1", 40000)));
}
private boolean passes(MockServerWebExchange exchange) {
AtomicBoolean called = new AtomicBoolean(false);
GatewayFilterChain chain = ex -> {
called.set(true);
return Mono.empty();
};
filter.filter(exchange, chain).block();
return called.get();
}
@Test
void adminActiveRulesNeedNoUserToken() {
assertThat(passes(call(HttpMethod.GET, "/passwordRule/adminActive"))).isTrue();
}
@Test
void everythingElseOnTheRuleControllerStillNeedsAToken() {
for (String[] c : new String[][] {
{"POST", "/passwordRule/adminActive"},
{"GET", "/passwordRule/adminActive/x"},
{"GET", "/passwordRule/adminActive/"},
{"GET", "/passwordRule/adminActiveX"},
{"GET", "/passwordRule/findByType/ADMIN_PWD_FORMAT"},
{"POST", "/passwordRule/save"} }) {
MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]);
assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse();
assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED);
}
}
}
@@ -56,6 +56,8 @@ public class RestApiSystemServiceConstants {
//Race
public static final String API_REST_SYSTEM_ADMIN_ACTIVE_PASSWORD_RULES = "/passwordRule/adminActive";
//Message
public static final String API_REST_SYSTEM_MESSAGE_JSON_BY_AREA_AND_LOCALE = "/message/getMessageJsonByAreaAndLocale/{area}/{locale}";
@@ -0,0 +1,31 @@
package com.solvway.mobile.api.controller;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.PasswordRuleHintService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/** Switched-on admin password rules. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequiredArgsConstructor
public class PasswordRuleController {
private final PasswordRuleHintService rules;
@AdminModule(AdminModule.ANY_ADMIN)
@AppAuth
@GetMapping("/api/admin/password-rules/active")
public List<Map<String, Object>> adminActive() {
return rules.active();
}
@AppAuth(skipValidate = true)
@GetMapping("/api/public/password-rules")
public List<Map<String, Object>> publicActive() {
return rules.publicActive();
}
}
@@ -104,6 +104,7 @@ public class AdminAuthController {
return ResponseEntity.badRequest().body(Map.of("message", "New password is required."));
}
if (!adminAuthenticationService.firstTimeLogin(u.getId(), request.newPassword())) {
adminAuthenticationService.requirePasswordRules(request.newPassword()); // throws PASSWORD_RULE naming the rule
return ResponseEntity.badRequest().body(Map.of("message", "New password does not meet the password policy."));
}
return ResponseEntity.ok(Map.of("result", "true"));
@@ -140,7 +141,10 @@ public class AdminAuthController {
throw coded(HttpStatus.BAD_REQUEST, "Current password is incorrect", "CURRENT_PASSWORD_WRONG");
}
case "PASSWORD_SAME" -> throw coded(HttpStatus.BAD_REQUEST, "The new password must differ from the current one", "PASSWORD_SAME");
case "PASSWORD_POLICY" -> throw coded(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY");
case "PASSWORD_POLICY" -> {
adminAuthenticationService.requirePasswordRules(request.newPassword()); // throws PASSWORD_RULE naming the rule
throw coded(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY");
}
default -> throw coded(HttpStatus.INTERNAL_SERVER_ERROR, "The password was not changed", "SAVE_FAILED");
}
}
@@ -5,6 +5,7 @@ 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 com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -56,6 +57,18 @@ public class AdminAuthenticationService {
return ent.getBody() != null && ent.getBody().isEmpty();
}
/** Throws 400 PASSWORD_RULE naming the first failed rule (param, value) when the password breaks a switched-on rule. */
public void requirePasswordRules(String password) {
ResponseEntity<List> ent = restTemplateUtil.postForEntity(
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_VALIDATE_PASSWORD_RULES),
List.class, Map.of("password", password));
if (ent.getBody() == null || ent.getBody().isEmpty() || !(ent.getBody().get(0) instanceof Map<?, ?> first)) return;
CodedResponseStatusException e = new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "PASSWORD_RULE", "PASSWORD_RULE");
e.getBody().setProperty("param", first.get("param"));
e.getBody().setProperty("value", first.get("value"));
throw e;
}
/** Stores an admin-typed password with a forced change at next login; returns rows updated (0 = refused). */
public int setAdminPassword(Long id, String password) {
ResponseEntity<Integer> ent = restTemplateUtil.postForEntity(
@@ -218,6 +218,7 @@ public class AdminUserService {
if (!StringUtils.hasText(password)) throw error(HttpStatus.BAD_REQUEST, "Password is required", "REQUIRED_FIELD");
if (!password.equals(confirmPassword)) throw error(HttpStatus.BAD_REQUEST, "Passwords do not match", "PASSWORD_MISMATCH");
if (!adminAuthenticationService.passesAdminPasswordRules(password)) {
adminAuthenticationService.requirePasswordRules(password); // throws PASSWORD_RULE naming the rule
throw error(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY");
}
}
@@ -0,0 +1,33 @@
package com.solvway.mobile.api.service;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/** The switched-on admin password rules, for the hint on password screens. */
@Service
@RequiredArgsConstructor
public class PasswordRuleHintService {
private static final ParameterizedTypeReference<List<Map<String, Object>>> RULES = new ParameterizedTypeReference<>() {};
private static final int PUBLIC_LIMIT = 60;
private final RestTemplateCustomUtil rest;
private final PublicRegistrationService limiter;
public List<Map<String, Object>> active() {
List<Map<String, Object>> body = rest.getForEntity(
rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_ACTIVE_PASSWORD_RULES), RULES).getBody();
return body == null ? List.of() : body;
}
/** Same list with no sign-in, counted per IP in the registration limiter (fixed 10-minute window). */
public List<Map<String, Object>> publicActive() {
limiter.limit("pwr:" + PublicRegistrationService.ip(), PUBLIC_LIMIT, "Too many requests from this device. Try again later.");
return active();
}
}
@@ -0,0 +1,53 @@
package com.solvway.mobile.api.controller;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.PasswordRuleHintService;
import com.solvway.mobile.api.useraccess.AdminModule;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class PasswordRuleControllerTest {
private final PasswordRuleHintService service = mock(PasswordRuleHintService.class);
private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new PasswordRuleController(service)).build();
private static Method handler(String name) {
return Arrays.stream(PasswordRuleController.class.getDeclaredMethods()).filter(m -> m.getName().equals(name)).findFirst().orElseThrow();
}
@Test
void adminRoute_needsASignedInAdmin_noModule() throws Exception {
Method m = handler("adminActive");
assertThat(m.getAnnotation(AppAuth.class).skipValidate()).isFalse();
assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly(AdminModule.ANY_ADMIN);
when(service.active()).thenReturn(List.of(Map.of("param", "INPUT_LENGTH_MIN", "value", "8")));
mvc.perform(get("/api/admin/password-rules/active")).andExpect(status().isOk())
.andExpect(jsonPath("$[0].param").value("INPUT_LENGTH_MIN")).andExpect(jsonPath("$[0].value").value("8"));
}
@Test
void publicRoute_skipsSignIn_andGoesThroughTheRateLimitedService() throws Exception {
assertThat(handler("publicActive").getAnnotation(AppAuth.class).skipValidate()).isTrue();
assertThat(handler("publicActive").getAnnotation(AdminModule.class)).isNull();
when(service.publicActive()).thenReturn(List.of(Map.of("param", "SPACE_NOT_ALLOWED")));
mvc.perform(get("/api/public/password-rules")).andExpect(status().isOk())
.andExpect(jsonPath("$[0].param").value("SPACE_NOT_ALLOWED"));
verify(service).publicActive();
}
}
@@ -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);
}
}
@@ -25,6 +25,11 @@ public class PasswordRuleController {
return systemProperties;
}
@RequestMapping("/adminActive")
public List<PasswordRuleService.ActiveRule> adminActive() {
return passwordRuleService.adminActive();
}
@RequestMapping("/findById/{id}")
public Optional<PasswordRuleProperty> findById(@PathVariable("id") Long id) {
Optional<PasswordRuleProperty> systemProperty = passwordRuleService.findById(id);
@@ -15,6 +15,16 @@ public class PasswordRuleService {
@Autowired
private PasswordRuleRepository passwordRuleRepository;
public record ActiveRule(String param, String value) {}
/** Switched-on admin rules (status Y) as param and value; value is null for flag rules. */
public List<ActiveRule> adminActive() {
return passwordRuleRepository.findByType("ADMIN_PWD_FORMAT").stream()
.filter(r -> "Y".equals(r.getStatus()))
.map(r -> new ActiveRule(r.getParam(), r.getValue()))
.toList();
}
public List<PasswordRuleProperty> findByType(String name){
return passwordRuleRepository.findByType(name);
}
@@ -0,0 +1,44 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.PasswordRuleProperty;
import com.solvway.services.system.repo.PasswordRuleRepository;
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 java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/** The admin password hint lists only the switched-on ADMIN rules, in the order the check runs them. */
@ExtendWith(MockitoExtension.class)
class PasswordRuleServiceAdminActiveTest {
@Mock private PasswordRuleRepository repo;
@InjectMocks private PasswordRuleService service;
private static PasswordRuleProperty rule(String param, String status, String value) {
PasswordRuleProperty r = new PasswordRuleProperty();
r.setParam(param);
r.setStatus(status);
r.setValue(value);
return r;
}
@Test
void adminActive_onlyYRules_withValues_nullForFlags() {
when(repo.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(
rule("INPUT_LENGTH_MIN", "Y", "8"),
rule("INPUT_LENGTH_MAX", "N", "20"),
rule("SYMBOLIC_LENGTH_MIN", "Y", "2"),
rule("SPACE_NOT_ALLOWED", "Y", null)));
assertThat(service.adminActive()).containsExactly(
new PasswordRuleService.ActiveRule("INPUT_LENGTH_MIN", "8"),
new PasswordRuleService.ActiveRule("SYMBOLIC_LENGTH_MIN", "2"),
new PasswordRuleService.ActiveRule("SPACE_NOT_ALLOWED", null));
}
}