feat: login history and lockout rule in services-system
LoginSecurityService derives the admin lock from login_audit and the ADMIN_LOGIN_BLOCK settings; /loginSecurity exposes lock check, record, history, locked list, unlock, lockout settings and password rules. The gateway routes /loginSecurity/** and lets the lock check and record through without a user token for the sign-in path. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
a0146be325
commit
f7ec74c7f0
11 files changed
+1074
-2
No files matched your search
+161
@@ -0,0 +1,161 @@
|
||||
package com.solvway.services.system.controller;
|
||||
|
||||
import com.solvway.services.system.service.LoginSecurityService;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Config;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Rule;
|
||||
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.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
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.get;
|
||||
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 LoginSecurityControllerTest {
|
||||
|
||||
@Mock private LoginSecurityService service;
|
||||
@InjectMocks private LoginSecurityController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder json(String url, String body) {
|
||||
return post(url).contentType(MediaType.APPLICATION_JSON).content(body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isLockedReturnsFlag() throws Exception {
|
||||
when(service.isLocked("admin")).thenReturn(true);
|
||||
|
||||
mvc.perform(get("/loginSecurity/isLocked/admin")).andExpect(status().isOk()).andExpect(jsonPath("$.locked").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordPassesFieldsAndReturnsEmpty200() throws Exception {
|
||||
mvc.perform(json("/loginSecurity/record",
|
||||
"{\"username\":\"bob\",\"event\":\"LOGIN_FAIL\",\"ip\":\"1.2.3.4\",\"userAgent\":\"ua\",\"message\":\"m\"}"))
|
||||
.andExpect(status().isOk()).andExpect(content().string(""));
|
||||
|
||||
verify(service).record("bob", "LOGIN_FAIL", "1.2.3.4", "ua", "m");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordRefusalIsA400WithMessage() throws Exception {
|
||||
doThrow(new IllegalArgumentException("username is required")).when(service).record(any(), any(), any(), any(), any());
|
||||
|
||||
mvc.perform(json("/loginSecurity/record", "{\"username\":\" \",\"event\":\"LOGIN_FAIL\"}"))
|
||||
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("username is required"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditParsesDatesAndPassesFilters() throws Exception {
|
||||
when(service.audit(any(), any(), any(), any(), any(), any())).thenReturn(Map.of("content", List.of(), "totalElements", 0L, "number", 1, "size", 100));
|
||||
|
||||
mvc.perform(json("/loginSecurity/audit",
|
||||
"{\"username\":\"bo\",\"event\":\"LOGOUT\",\"from\":\"2025-06-01\",\"to\":\"2025-06-02\",\"page\":1,\"size\":500}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size").value(100)).andExpect(jsonPath("$.totalElements").value(0));
|
||||
|
||||
verify(service).audit("bo", "LOGOUT", LocalDate.of(2025, 6, 1), LocalDate.of(2025, 6, 2), 1, 500);
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditWithBadDateIs400() throws Exception {
|
||||
mvc.perform(json("/loginSecurity/audit", "{\"from\":\"01/06/2025\"}")).andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.message").exists());
|
||||
|
||||
verify(service, never()).audit(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedListIsReturned() throws Exception {
|
||||
when(service.lockedUsers()).thenReturn(List.of(new LoginSecurityService.Locked("a", 3,
|
||||
LocalDateTime.of(2025, 6, 15, 11, 59), LocalDateTime.of(2025, 6, 15, 12, 5))));
|
||||
|
||||
mvc.perform(get("/loginSecurity/locked")).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].username").value("a")).andExpect(jsonPath("$[0].failures").value(3))
|
||||
.andExpect(jsonPath("$[0].lastFailure").exists()).andExpect(jsonPath("$[0].lockedUntil").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockPassesUsernameAndBy() throws Exception {
|
||||
mvc.perform(json("/loginSecurity/unlock", "{\"username\":\"bob\",\"by\":\"admin\"}")).andExpect(status().isOk());
|
||||
|
||||
verify(service).unlock("bob", "admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockBlankIs400() throws Exception {
|
||||
doThrow(new IllegalArgumentException("username is required")).when(service).unlock(any(), any());
|
||||
|
||||
mvc.perform(json("/loginSecurity/unlock", "{\"username\":\"\",\"by\":\"admin\"}")).andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void configIsReadAndSaved() throws Exception {
|
||||
when(service.config()).thenReturn(new Config(true, 5, 10, "M"));
|
||||
when(service.saveConfig(new Config(false, 3, 2, "H"))).thenReturn(new Config(false, 3, 2, "H"));
|
||||
|
||||
mvc.perform(get("/loginSecurity/config")).andExpect(jsonPath("$.enabled").value(true))
|
||||
.andExpect(jsonPath("$.maxAttempts").value(5)).andExpect(jsonPath("$.period").value(10)).andExpect(jsonPath("$.unit").value("M"));
|
||||
mvc.perform(json("/loginSecurity/config", "{\"enabled\":false,\"maxAttempts\":3,\"period\":2,\"unit\":\"H\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.unit").value("H"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidConfigIs400WithMessage() throws Exception {
|
||||
when(service.saveConfig(any())).thenThrow(new IllegalArgumentException("unit must be S, M, H or D"));
|
||||
|
||||
mvc.perform(json("/loginSecurity/config", "{\"enabled\":true,\"maxAttempts\":3,\"period\":2,\"unit\":\"X\"}"))
|
||||
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("unit must be S, M, H or D"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordRulesAreReadAndSaved() throws Exception {
|
||||
when(service.passwordRules()).thenReturn(List.of(new Rule(2L, "INPUT_LENGTH_MIN", "Y", "8")));
|
||||
when(service.savePasswordRules(eq(List.of(new Rule(2L, null, "N", "12"))))).thenReturn(List.of(new Rule(2L, "INPUT_LENGTH_MIN", "N", "12")));
|
||||
|
||||
mvc.perform(get("/loginSecurity/passwordRules")).andExpect(jsonPath("$[0].param").value("INPUT_LENGTH_MIN"));
|
||||
mvc.perform(json("/loginSecurity/passwordRules", "[{\"id\":2,\"status\":\"N\",\"value\":\"12\"}]"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$[0].status").value("N"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidPasswordRulesAre400() throws Exception {
|
||||
when(service.savePasswordRules(any())).thenThrow(new IllegalArgumentException("status must be Y or N"));
|
||||
|
||||
mvc.perform(json("/loginSecurity/passwordRules", "[{\"id\":2,\"status\":\"X\"}]")).andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOrMissingBodyIs400WithMessage() throws Exception {
|
||||
for (String url : List.of("/loginSecurity/record", "/loginSecurity/audit", "/loginSecurity/unlock",
|
||||
"/loginSecurity/config", "/loginSecurity/passwordRules")) {
|
||||
mvc.perform(json(url, "null")).andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").exists());
|
||||
mvc.perform(post(url).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.message").exists());
|
||||
}
|
||||
}
|
||||
}
|
||||
+450
@@ -0,0 +1,450 @@
|
||||
package com.solvway.services.system.service;
|
||||
|
||||
import com.solvway.services.system.model.LoginAudit;
|
||||
import com.solvway.services.system.model.PasswordRuleProperty;
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.repo.LoginAuditRepository;
|
||||
import com.solvway.services.system.repo.PasswordRuleRepository;
|
||||
import com.solvway.services.system.repo.UserRepository;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Config;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Locked;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Rule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
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.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class LoginSecurityServiceTest {
|
||||
|
||||
private static final LocalDateTime NOW = LocalDateTime.of(2025, 6, 15, 12, 0);
|
||||
|
||||
@Mock private LoginAuditRepository audits;
|
||||
@Mock private UserRepository users;
|
||||
@Mock private PasswordRuleRepository properties;
|
||||
private LoginSecurityService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new LoginSecurityService(audits, users, properties);
|
||||
service.clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
private static PasswordRuleProperty prop(Long id, String param, String type, String status, String value) {
|
||||
PasswordRuleProperty p = new PasswordRuleProperty();
|
||||
p.setId(id);
|
||||
p.setParam(param);
|
||||
p.setType(type);
|
||||
p.setStatus(status);
|
||||
p.setValue(value);
|
||||
return p;
|
||||
}
|
||||
|
||||
private void settings(String status, String period, String max, String unit) {
|
||||
when(properties.findByType("ADMIN_LOGIN_BLOCK")).thenReturn(List.of(
|
||||
prop(1L, "ADMIN_LOGIN_BLOCK_PERIOD", "ADMIN_LOGIN_BLOCK", status, period),
|
||||
prop(2L, "ADMIN_LOGIN_MAX_ATTEMPT", "ADMIN_LOGIN_BLOCK", "Y", max)));
|
||||
when(properties.findByType("ADMIN_LOGIN_BLOCK_TIME_UNIT")).thenReturn(List.of(
|
||||
prop(3L, "ADMIN_LOGIN_BLOCK_TIME_UNIT", "ADMIN_LOGIN_BLOCK_TIME_UNIT", "Y", unit)));
|
||||
}
|
||||
|
||||
private static LoginAudit row(String event, LocalDateTime at) {
|
||||
LoginAudit a = new LoginAudit();
|
||||
a.setUsername("admin");
|
||||
a.setEvent(event);
|
||||
a.setDatetime(at);
|
||||
return a;
|
||||
}
|
||||
|
||||
/** Behaves like the DB query: only rows strictly after {@code since}, in the given (oldest first) order. */
|
||||
private void failures(String username, LocalDateTime... times) {
|
||||
when(audits.findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(eq(username), eq("LOGIN_FAIL"), any()))
|
||||
.thenAnswer(i -> java.util.Arrays.stream(times)
|
||||
.filter(t -> t.isAfter(i.getArgument(2))).map(t -> row("LOGIN_FAIL", t)).toList());
|
||||
}
|
||||
|
||||
private LocalDateTime sinceUsed() {
|
||||
ArgumentCaptor<LocalDateTime> c = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
verify(audits).findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(anyString(), eq("LOGIN_FAIL"), c.capture());
|
||||
return c.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedAtMaxFailuresInsidePeriod() {
|
||||
settings("Y", "10", "3", "M");
|
||||
failures("admin", NOW.minusMinutes(5), NOW.minusMinutes(3), NOW.minusMinutes(1));
|
||||
|
||||
assertThat(service.isLocked("admin")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void notLockedWhenOlderFailuresFallOutsidePeriod() {
|
||||
settings("Y", "10", "3", "M");
|
||||
failures("admin", NOW.minusMinutes(30), NOW.minusMinutes(20), NOW.minusMinutes(1));
|
||||
|
||||
assertThat(service.isLocked("admin")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void usernameIsTrimmed() {
|
||||
settings("Y", "10", "1", "M");
|
||||
failures("admin", NOW.minusMinutes(1));
|
||||
|
||||
assertThat(service.isLocked(" admin ")).isTrue();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"LOGIN_SUCCESS", "UNLOCK_RESET", "PASSWORD_CHANGED"})
|
||||
void resetEventsRestartTheCount(String event) {
|
||||
settings("Y", "10", "3", "M");
|
||||
failures("admin", NOW.minusMinutes(5), NOW.minusMinutes(4), NOW.minusMinutes(3), NOW.minusMinutes(1));
|
||||
LocalDateTime resetAt = NOW.minusMinutes(2);
|
||||
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq("admin"), anyList()))
|
||||
.thenAnswer(i -> ((java.util.Collection<?>) i.getArgument(1)).contains(event)
|
||||
? Optional.of(row(event, resetAt)) : Optional.empty());
|
||||
|
||||
assertThat(service.isLocked("admin")).isFalse();
|
||||
assertThat(sinceUsed()).isEqualTo(resetAt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logoutAndLoginLockedDoNotResetTheCount() {
|
||||
settings("Y", "10", "3", "M");
|
||||
failures("admin", NOW.minusMinutes(5), NOW.minusMinutes(4), NOW.minusMinutes(3));
|
||||
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq("admin"), anyList()))
|
||||
.thenAnswer(i -> ((java.util.Collection<?>) i.getArgument(1)).stream()
|
||||
.anyMatch(e -> e.equals("LOGOUT") || e.equals("LOGIN_LOCKED"))
|
||||
? Optional.of(row("LOGOUT", NOW.minusMinutes(2))) : Optional.empty());
|
||||
|
||||
assertThat(service.isLocked("admin")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetOlderThanThePeriodDoesNotMoveTheWindow() {
|
||||
settings("Y", "10", "1", "M");
|
||||
failures("admin", NOW.minusMinutes(1));
|
||||
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq("admin"), anyList()))
|
||||
.thenReturn(Optional.of(row("LOGIN_SUCCESS", NOW.minusHours(5))));
|
||||
|
||||
assertThat(service.isLocked("admin")).isTrue();
|
||||
assertThat(sinceUsed()).isEqualTo(NOW.minusMinutes(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockoutOffNeverLocks() {
|
||||
settings("N", "10", "1", "M");
|
||||
failures("admin", NOW.minusMinutes(1), NOW.minusMinutes(2));
|
||||
|
||||
assertThat(service.isLocked("admin")).isFalse();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"abc,3,M", "10,,M", "10,3,X", "0,3,M", "10,0,M"})
|
||||
void badSettingsMeanLockoutOff(String period, String max, String unit) {
|
||||
settings("Y", period, max, unit);
|
||||
failures("admin", NOW.minusSeconds(1), NOW.minusSeconds(2), NOW.minusSeconds(3));
|
||||
|
||||
assertThat(service.isLocked("admin")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingSettingsMeanLockoutOff() {
|
||||
failures("admin", NOW.minusSeconds(1));
|
||||
|
||||
assertThat(service.isLocked("admin")).isFalse();
|
||||
assertThat(service.lockedUsers()).isEmpty();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"S,PT2S", "M,PT2M", "H,PT2H", "D,PT48H"})
|
||||
void unitIsConvertedToThePeriod(String unit, Duration expected) {
|
||||
settings("Y", "2", "1", unit);
|
||||
failures("admin", NOW.minusSeconds(1));
|
||||
|
||||
assertThat(service.isLocked("admin")).isTrue();
|
||||
assertThat(sinceUsed()).isEqualTo(NOW.minus(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedUntilIsOldestFailureKeepingTheCountPlusPeriod() {
|
||||
settings("Y", "10", "2", "M");
|
||||
failures("admin", NOW.minusMinutes(9), NOW.minusMinutes(5), NOW.minusMinutes(1));
|
||||
|
||||
assertThat(service.lockedUsers().size()).isZero(); // no candidates yet
|
||||
when(audits.findUsernamesWithFailuresAfter(NOW.minusMinutes(10))).thenReturn(List.of("admin"));
|
||||
|
||||
List<Locked> locked = service.lockedUsers();
|
||||
|
||||
assertThat(locked).containsExactly(new Locked("admin", 3, NOW.minusMinutes(1), NOW.plusMinutes(5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedListReturnsOnlyLockedUsernames() {
|
||||
settings("Y", "10", "2", "M");
|
||||
when(audits.findUsernamesWithFailuresAfter(NOW.minusMinutes(10))).thenReturn(List.of("a", "b"));
|
||||
failures("a", NOW.minusMinutes(2), NOW.minusMinutes(1));
|
||||
failures("b", NOW.minusMinutes(1));
|
||||
|
||||
assertThat(service.lockedUsers()).extracting(Locked::username).containsExactly("a");
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedListIsEmptyWhenLockoutOff() {
|
||||
settings("N", "10", "2", "M");
|
||||
|
||||
assertThat(service.lockedUsers()).isEmpty();
|
||||
verify(audits, never()).findUsernamesWithFailuresAfter(any());
|
||||
}
|
||||
|
||||
private LoginAudit saved() {
|
||||
ArgumentCaptor<LoginAudit> c = ArgumentCaptor.forClass(LoginAudit.class);
|
||||
verify(audits).save(c.capture());
|
||||
return c.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockWritesUnlockResetRowWithCompany() {
|
||||
User u = new User();
|
||||
u.setCompanyId(7L);
|
||||
when(users.findByUsername("admin")).thenReturn(u);
|
||||
|
||||
service.unlock(" admin ", "boss");
|
||||
|
||||
LoginAudit a = saved();
|
||||
assertThat(a.getUsername()).isEqualTo("admin");
|
||||
assertThat(a.getEvent()).isEqualTo("UNLOCK_RESET");
|
||||
assertThat(a.getMessage()).isEqualTo("unlocked by boss");
|
||||
assertThat(a.getCompanyId()).isEqualTo(7L);
|
||||
assertThat(a.getDatetime()).isEqualTo(NOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockRefusesBlankUsername() {
|
||||
assertThatThrownBy(() -> service.unlock(" ", "boss")).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(audits, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordCutsLongValuesAndFillsCompanyForKnownUser() {
|
||||
User u = new User();
|
||||
u.setCompanyId(9L);
|
||||
when(users.findByUsername("bob")).thenReturn(u);
|
||||
|
||||
service.record(" bob ", "LOGIN_FAIL", "i".repeat(80), "u".repeat(600), "m".repeat(300));
|
||||
|
||||
LoginAudit a = saved();
|
||||
assertThat(a.getUsername()).isEqualTo("bob");
|
||||
assertThat(a.getIpAddress()).hasSize(64);
|
||||
assertThat(a.getUserAgent()).hasSize(512);
|
||||
assertThat(a.getMessage()).hasSize(255);
|
||||
assertThat(a.getCompanyId()).isEqualTo(9L);
|
||||
assertThat(a.getDatetime()).isEqualTo(NOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordCutsUsernameTo191AndLeavesCompanyNullForUnknownUser() {
|
||||
service.record("n".repeat(250), "LOGOUT", null, null, null);
|
||||
|
||||
LoginAudit a = saved();
|
||||
assertThat(a.getUsername()).hasSize(191);
|
||||
assertThat(a.getCompanyId()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordRefusesBlankUsernameAndUnknownEvent() {
|
||||
assertThatThrownBy(() -> service.record(" ", "LOGIN_FAIL", null, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.record(null, "LOGIN_FAIL", null, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.record("bob", "NOPE", null, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
verify(audits, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditMapsFiltersAndCapsSizeAt100() {
|
||||
when(audits.search(any(), any(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(row("LOGIN_FAIL", NOW))));
|
||||
|
||||
Map<String, Object> r = service.audit(" bo ", "LOGIN_FAIL", LocalDate.of(2025, 6, 1), LocalDate.of(2025, 6, 2), 2, 500);
|
||||
|
||||
ArgumentCaptor<Pageable> p = ArgumentCaptor.forClass(Pageable.class);
|
||||
verify(audits).search(eq("%bo%"), eq("LOGIN_FAIL"), eq(LocalDateTime.of(2025, 6, 1, 0, 0)),
|
||||
eq(LocalDateTime.of(2025, 6, 3, 0, 0)), p.capture());
|
||||
assertThat(p.getValue().getPageSize()).isEqualTo(100);
|
||||
assertThat(p.getValue().getPageNumber()).isEqualTo(2);
|
||||
assertThat(p.getValue().getSort().toString()).isEqualTo("datetime: DESC,id: DESC");
|
||||
assertThat(r).containsEntry("totalElements", 1L).containsEntry("number", 2).containsEntry("size", 100);
|
||||
assertThat((List<?>) r.get("content")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditDefaultsToPageZeroSize20AndNoFilters() {
|
||||
when(audits.search(any(), any(), any(), any(), any())).thenReturn(Page.empty());
|
||||
|
||||
Map<String, Object> r = service.audit(null, " ", null, null, null, null);
|
||||
|
||||
verify(audits).search(eq(null), eq(null), eq(null), eq(null), any(Pageable.class));
|
||||
assertThat(r).containsEntry("number", 0).containsEntry("size", 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void configIsReadFromTheRows() {
|
||||
settings("Y", "15", "4", "H");
|
||||
|
||||
assertThat(service.config()).isEqualTo(new Config(true, 4, 15, "H"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"0,5,M", "3,0,M", "3,5,X"})
|
||||
void invalidConfigIsRejectedAndNothingSaved(int max, int period, String unit) {
|
||||
assertThatThrownBy(() -> service.saveConfig(new Config(true, max, period, unit)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
verify(properties, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validConfigUpdatesThreeRowsAndEnabledSetsPeriodStatus() {
|
||||
settings("Y", "15", "4", "H");
|
||||
|
||||
service.saveConfig(new Config(false, 6, 20, "D"));
|
||||
|
||||
ArgumentCaptor<PasswordRuleProperty> c = ArgumentCaptor.forClass(PasswordRuleProperty.class);
|
||||
verify(properties, org.mockito.Mockito.times(3)).save(c.capture());
|
||||
assertThat(c.getAllValues()).extracting("param", "status", "value").containsExactlyInAnyOrder(
|
||||
org.assertj.core.groups.Tuple.tuple("ADMIN_LOGIN_BLOCK_PERIOD", "N", "20"),
|
||||
org.assertj.core.groups.Tuple.tuple("ADMIN_LOGIN_MAX_ATTEMPT", "Y", "6"),
|
||||
org.assertj.core.groups.Tuple.tuple("ADMIN_LOGIN_BLOCK_TIME_UNIT", "Y", "D"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordRulesAreOrderedById() {
|
||||
when(properties.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(
|
||||
prop(5L, "B", "ADMIN_PWD_FORMAT", "Y", "2"), prop(2L, "A", "ADMIN_PWD_FORMAT", "N", "1")));
|
||||
|
||||
assertThat(service.passwordRules()).extracting(Rule::id).containsExactly(2L, 5L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordRulesUpdateOnlyStatusAndValue() {
|
||||
PasswordRuleProperty r = prop(2L, "INPUT_LENGTH_MIN", "ADMIN_PWD_FORMAT", "Y", "8");
|
||||
when(properties.findById(2L)).thenReturn(Optional.of(r));
|
||||
when(properties.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(r));
|
||||
|
||||
service.savePasswordRules(List.of(new Rule(2L, "HACKED", "N", "12")));
|
||||
|
||||
assertThat(r.getStatus()).isEqualTo("N");
|
||||
assertThat(r.getValue()).isEqualTo("12");
|
||||
assertThat(r.getParam()).isEqualTo("INPUT_LENGTH_MIN");
|
||||
verify(properties).saveAll(List.of(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordRulesRefuseAnIdOfAnotherTypeAndSaveNothing() {
|
||||
PasswordRuleProperty good = prop(2L, "A", "ADMIN_PWD_FORMAT", "Y", "1");
|
||||
when(properties.findById(2L)).thenReturn(Optional.of(good));
|
||||
when(properties.findById(9L)).thenReturn(Optional.of(prop(9L, "X", "USER_PWD_FORMAT", "Y", "1")));
|
||||
|
||||
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(2L, null, "N", "5"), new Rule(9L, null, "Y", "5"))))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
assertThat(good.getStatus()).isEqualTo("Y");
|
||||
verify(properties, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordRulesRefuseUnknownIdAndBadStatusAndSaveNothing() {
|
||||
PasswordRuleProperty good = prop(2L, "A", "ADMIN_PWD_FORMAT", "Y", "1");
|
||||
when(properties.findById(2L)).thenReturn(Optional.of(good));
|
||||
|
||||
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(404L, null, "Y", null))))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(2L, null, "X", "5"))))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
assertThat(good.getValue()).isEqualTo("1");
|
||||
verify(properties, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingUnitRowMeansLockoutOff() {
|
||||
when(properties.findByType("ADMIN_LOGIN_BLOCK")).thenReturn(List.of(
|
||||
prop(1L, "ADMIN_LOGIN_BLOCK_PERIOD", "ADMIN_LOGIN_BLOCK", "Y", "10"),
|
||||
prop(2L, "ADMIN_LOGIN_MAX_ATTEMPT", "ADMIN_LOGIN_BLOCK", "Y", "1")));
|
||||
failures("admin", NOW.minusSeconds(1));
|
||||
|
||||
assertThat(service.isLocked("admin")).isFalse();
|
||||
assertThat(service.lockedUsers()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordRefusesUnlockResetButAcceptsTheOtherEvents() {
|
||||
assertThatThrownBy(() -> service.record("bob", "UNLOCK_RESET", null, null, null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
verify(audits, never()).save(any());
|
||||
for (String e : List.of("LOGIN_SUCCESS", "LOGIN_FAIL", "LOGIN_LOCKED", "LOGOUT", "PASSWORD_CHANGED")) {
|
||||
service.record("bob", e, null, null, null);
|
||||
}
|
||||
verify(audits, org.mockito.Mockito.times(5)).save(any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"INPUT_LENGTH_MIN,abc", "INPUT_LENGTH_MIN,-1", "INPUT_LENGTH_MIN,''", "UPPER_CASE_MAX,1.5"})
|
||||
void minMaxRulesRefuseNonIntegerValuesAndSaveNothing(String param, String value) {
|
||||
when(properties.findById(2L)).thenReturn(Optional.of(prop(2L, param, "ADMIN_PWD_FORMAT", "Y", "1")));
|
||||
|
||||
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(2L, null, "Y", value))))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
verify(properties, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherRulesAllowEmptyValue() {
|
||||
PasswordRuleProperty r = prop(3L, "SPACE_NOT_ALLOWED", "ADMIN_PWD_FORMAT", "Y", "x");
|
||||
when(properties.findById(3L)).thenReturn(Optional.of(r));
|
||||
when(properties.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(r));
|
||||
|
||||
service.savePasswordRules(List.of(new Rule(3L, null, "Y", "")));
|
||||
|
||||
verify(properties).saveAll(List.of(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullInputsAreRefusedAsIllegalArgument() {
|
||||
assertThatThrownBy(() -> service.savePasswordRules(null)).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.savePasswordRules(java.util.Arrays.asList((Rule) null))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.savePasswordRules(List.of(new Rule(null, null, "Y", "1")))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.saveConfig(null)).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(properties, never()).saveAll(any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user