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
@@ -68,7 +68,7 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe
|
||||
- Then the existing check:
|
||||
- an unknown, wrong, disabled or upstream-failed check records `LOGIN_FAIL`;
|
||||
- a success records `LOGIN_SUCCESS`.
|
||||
- Recording goes through `LoginAuditClient.record(...)`, which catches and logs every exception.
|
||||
- The lock check and recording are methods on `AdminAuthenticationService` (`isLocked`, which fails open, and `record`, which catches and logs every exception). No new class, so the existing controller tests and their mocks stay unchanged.
|
||||
- Logout records `LOGOUT` for the token's user.
|
||||
|
||||
6. **Client IP and user agent:**
|
||||
|
||||
@@ -17,7 +17,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
|
||||
## 2. services-system
|
||||
|
||||
- [ ] 2.1 `LoginAudit` entity and repository, `LoginSecurityService` and `LoginSecurityController` (design decisions 2 and 3), plus the gateway route `/loginSecurity/**` to services-system.
|
||||
- [x] 2.1 `LoginAudit` entity and repository, `LoginSecurityService` and `LoginSecurityController` (design decisions 2 and 3), plus the gateway route `/loginSecurity/**` to services-system.
|
||||
- Before coding: check how mobile-api reaches services-system before a user has a token (the forgot-password path). Match that for `isLocked` and `record`, and note the finding in the task report.
|
||||
- **Tests first:**
|
||||
- locked at `max` failures inside the period;
|
||||
|
||||
@@ -133,6 +133,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered {
|
||||
|| url.contains("/member/forgetPassword")
|
||||
// Co-Lite admin forgot password (public; answers the same whether or not details match)
|
||||
|| url.equals("/user/resetAdminPassword")
|
||||
// Co-Lite admin sign-in: lock check and its recording run before the user has a token
|
||||
|| (url.matches("/loginSecurity/isLocked/[^/]+") && !url.contains(".."))
|
||||
|| url.equals("/loginSecurity/record")
|
||||
|| url.contains("/geoLocationHierarchy/findByFirstLevelLocation")
|
||||
|| url.contains("/geoLocationHierarchy/findAllByParentId")
|
||||
// public content - no JWT required
|
||||
|
||||
@@ -148,6 +148,10 @@ spring:
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
- Path=/blockLoginPeriod/**
|
||||
- id: loginSecurity
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
- Path=/loginSecurity/**
|
||||
- id: passwordAging
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
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.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 admin sign-in lock check and its recording run before the user has a token; the rest of /loginSecurity needs one. */
|
||||
class JWTAuthFilterLoginSecurityPathTest {
|
||||
|
||||
private static final String KEY = "gateway-test-key";
|
||||
|
||||
private JWTAuthFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Built the way AuthAppKeyConfig loads appkeys.json (the constructor is not public).
|
||||
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 post(String path) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest.post(path)
|
||||
.header("api-key", KEY)
|
||||
.remoteAddress(new InetSocketAddress("127.0.0.1", 40000)));
|
||||
}
|
||||
|
||||
private MockServerWebExchange get(String path) {
|
||||
return MockServerWebExchange.from(MockServerHttpRequest.get(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 lockCheckNeedsNoUserToken() {
|
||||
assertThat(passes(get("/loginSecurity/isLocked/sales1"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordNeedsNoUserToken() {
|
||||
assertThat(passes(post("/loginSecurity/record"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherLoginSecurityEndpointsStillNeedAToken() {
|
||||
for (MockServerWebExchange exchange : new MockServerWebExchange[] {
|
||||
post("/loginSecurity/unlock"), get("/loginSecurity/locked"), post("/loginSecurity/config"),
|
||||
post("/loginSecurity/audit"), post("/loginSecurity/passwordRules"),
|
||||
post("/loginSecurity/record/../unlock"), get("/x/loginSecurity/isLocked/a"), get("/loginSecurity/isLocked/../locked"),
|
||||
get("/loginSecurity/isLocked/a/b") }) {
|
||||
assertThat(passes(exchange)).isFalse();
|
||||
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
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.Locked;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Rule;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/loginSecurity")
|
||||
public class LoginSecurityController {
|
||||
|
||||
record RecordBody(String username, String event, String ip, String userAgent, String message) {}
|
||||
record AuditBody(String username, String event, String from, String to, Integer page, Integer size) {}
|
||||
record UnlockBody(String username, String by) {}
|
||||
|
||||
private final LoginSecurityService service;
|
||||
|
||||
public LoginSecurityController(LoginSecurityService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping("/isLocked/{username}")
|
||||
public Map<String, Boolean> isLocked(@PathVariable String username) {
|
||||
return Map.of("locked", service.isLocked(username));
|
||||
}
|
||||
|
||||
@PostMapping("/record")
|
||||
public void record(@RequestBody RecordBody b) {
|
||||
body(b);
|
||||
service.record(b.username(), b.event(), b.ip(), b.userAgent(), b.message());
|
||||
}
|
||||
|
||||
@PostMapping("/audit")
|
||||
public Map<String, Object> audit(@RequestBody AuditBody b) {
|
||||
body(b);
|
||||
return service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size());
|
||||
}
|
||||
|
||||
@GetMapping("/locked")
|
||||
public List<Locked> locked() {
|
||||
return service.lockedUsers();
|
||||
}
|
||||
|
||||
@PostMapping("/unlock")
|
||||
public void unlock(@RequestBody UnlockBody b) {
|
||||
body(b);
|
||||
service.unlock(b.username(), b.by());
|
||||
}
|
||||
|
||||
@GetMapping("/config")
|
||||
public Config config() {
|
||||
return service.config();
|
||||
}
|
||||
|
||||
@PostMapping("/config")
|
||||
public Config saveConfig(@RequestBody Config c) {
|
||||
return service.saveConfig(c);
|
||||
}
|
||||
|
||||
@GetMapping("/passwordRules")
|
||||
public List<Rule> passwordRules() {
|
||||
return service.passwordRules();
|
||||
}
|
||||
|
||||
@PostMapping("/passwordRules")
|
||||
public List<Rule> savePasswordRules(@RequestBody List<Rule> rules) {
|
||||
return service.savePasswordRules(rules);
|
||||
}
|
||||
|
||||
@ExceptionHandler({IllegalArgumentException.class, DateTimeParseException.class, HttpMessageNotReadableException.class})
|
||||
public ResponseEntity<Map<String, String>> badRequest(RuntimeException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", String.valueOf(e.getMessage())));
|
||||
}
|
||||
|
||||
private static void body(Object b) {
|
||||
if (b == null) throw new IllegalArgumentException("body is required");
|
||||
}
|
||||
|
||||
private static LocalDate date(String s) {
|
||||
return s == null || s.isBlank() ? null : LocalDate.parse(s);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.solvway.services.system.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "login_audit")
|
||||
@Getter
|
||||
@Setter
|
||||
public class LoginAudit {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@JsonIgnore
|
||||
private Long companyId;
|
||||
|
||||
private String username;
|
||||
|
||||
private LocalDateTime datetime;
|
||||
|
||||
private String event;
|
||||
|
||||
private String ipAddress;
|
||||
|
||||
private String userAgent;
|
||||
|
||||
private String message;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.solvway.services.system.repo;
|
||||
|
||||
import com.solvway.services.system.model.LoginAudit;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface LoginAuditRepository extends JpaRepository<LoginAudit, Long> {
|
||||
|
||||
Optional<LoginAudit> findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(String username, Collection<String> events);
|
||||
|
||||
List<LoginAudit> findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(String username, String event, LocalDateTime since);
|
||||
|
||||
@Query("SELECT DISTINCT a.username FROM LoginAudit a WHERE a.event = 'LOGIN_FAIL' AND a.datetime > :since")
|
||||
List<String> findUsernamesWithFailuresAfter(@Param("since") LocalDateTime since);
|
||||
|
||||
/** Null arguments are ignored; {@code pattern} is a LIKE pattern, {@code toExclusive} an exclusive upper bound. */
|
||||
@Query("SELECT a FROM LoginAudit a WHERE (:pattern IS NULL OR a.username LIKE :pattern) "
|
||||
+ "AND (:event IS NULL OR a.event = :event) "
|
||||
+ "AND (:from IS NULL OR a.datetime >= :from) "
|
||||
+ "AND (:toExclusive IS NULL OR a.datetime < :toExclusive)")
|
||||
Page<LoginAudit> search(@Param("pattern") String pattern, @Param("event") String event,
|
||||
@Param("from") LocalDateTime from, @Param("toExclusive") LocalDateTime toExclusive,
|
||||
Pageable pageable);
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
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 org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Admin login history, lock rule, unlock, and lockout / password-rule settings. */
|
||||
@Service
|
||||
public class LoginSecurityService {
|
||||
|
||||
private static final List<String> EVENTS = List.of(
|
||||
"LOGIN_SUCCESS", "LOGIN_FAIL", "LOGIN_LOCKED", "LOGOUT", "UNLOCK_RESET", "PASSWORD_CHANGED");
|
||||
private static final List<String> RESETS = List.of("LOGIN_SUCCESS", "UNLOCK_RESET", "PASSWORD_CHANGED");
|
||||
private static final String BLOCK = "ADMIN_LOGIN_BLOCK";
|
||||
private static final String UNIT = "ADMIN_LOGIN_BLOCK_TIME_UNIT";
|
||||
private static final String PWD = "ADMIN_PWD_FORMAT";
|
||||
private static final String PERIOD_PARAM = "ADMIN_LOGIN_BLOCK_PERIOD";
|
||||
private static final String MAX_PARAM = "ADMIN_LOGIN_MAX_ATTEMPT";
|
||||
|
||||
public record Config(boolean enabled, int maxAttempts, int period, String unit) {
|
||||
ChronoUnit chronoUnit() {
|
||||
return switch (unit == null ? "" : unit) {
|
||||
case "S" -> ChronoUnit.SECONDS;
|
||||
case "M" -> ChronoUnit.MINUTES;
|
||||
case "H" -> ChronoUnit.HOURS;
|
||||
case "D" -> ChronoUnit.DAYS;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
boolean valid() {
|
||||
return maxAttempts >= 1 && period >= 1 && chronoUnit() != null;
|
||||
}
|
||||
|
||||
Duration length() {
|
||||
return Duration.of(period, chronoUnit());
|
||||
}
|
||||
}
|
||||
|
||||
public record Locked(String username, int failures, LocalDateTime lastFailure, LocalDateTime lockedUntil) {}
|
||||
|
||||
/** Input and output shape of a password rule; {@code param} is ignored on input. */
|
||||
public record Rule(Long id, String param, String status, String value) {}
|
||||
|
||||
private final LoginAuditRepository audits;
|
||||
private final UserRepository users;
|
||||
private final PasswordRuleRepository properties; // same system_property table, any type
|
||||
Clock clock = Clock.systemDefaultZone(); // overridden by tests
|
||||
|
||||
public LoginSecurityService(LoginAuditRepository audits, UserRepository users, PasswordRuleRepository properties) {
|
||||
this.audits = audits;
|
||||
this.users = users;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public boolean isLocked(String username) {
|
||||
Config c = config();
|
||||
return c.enabled() && c.valid() && evaluate(username.trim(), c, LocalDateTime.now(clock)) != null;
|
||||
}
|
||||
|
||||
public List<Locked> lockedUsers() {
|
||||
Config c = config();
|
||||
if (!c.enabled() || !c.valid()) return List.of();
|
||||
LocalDateTime now = LocalDateTime.now(clock);
|
||||
return audits.findUsernamesWithFailuresAfter(now.minus(c.length())).stream()
|
||||
.map(u -> evaluate(u, c, now)).filter(l -> l != null).toList();
|
||||
}
|
||||
|
||||
public void record(String username, String event, String ip, String userAgent, String message) {
|
||||
if (!EVENTS.contains(event) || "UNLOCK_RESET".equals(event)) throw new IllegalArgumentException("unknown event");
|
||||
write(username, event, cut(ip, 64), cut(userAgent, 512), cut(message, 255));
|
||||
}
|
||||
|
||||
public void unlock(String username, String by) {
|
||||
write(username, "UNLOCK_RESET", null, null, cut("unlocked by " + by, 255));
|
||||
}
|
||||
|
||||
public Map<String, Object> audit(String username, String event, LocalDate from, LocalDate to, Integer page, Integer size) {
|
||||
int p = page == null || page < 0 ? 0 : page;
|
||||
int s = size == null || size < 1 ? 20 : Math.min(size, 100);
|
||||
String name = username == null ? "" : username.trim();
|
||||
// ponytail: % and _ in the username filter are not escaped (admin-only filter); escape in the query if it matters
|
||||
Page<LoginAudit> r = audits.search(name.isEmpty() ? null : "%" + name + "%",
|
||||
event == null || event.isBlank() ? null : event,
|
||||
from == null ? null : from.atStartOfDay(),
|
||||
to == null ? null : to.plusDays(1).atStartOfDay(),
|
||||
PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "datetime", "id")));
|
||||
return Map.of("content", r.getContent(), "totalElements", r.getTotalElements(), "number", p, "size", s);
|
||||
}
|
||||
|
||||
/** Missing or unparsable rows read as 0 / disabled, so bad config never locks anyone. */
|
||||
public Config config() {
|
||||
PasswordRuleProperty period = row(BLOCK, PERIOD_PARAM);
|
||||
PasswordRuleProperty max = row(BLOCK, MAX_PARAM);
|
||||
PasswordRuleProperty unit = row(UNIT, "ADMIN_LOGIN_BLOCK_TIME_UNIT");
|
||||
return new Config(period != null && "Y".equals(period.getStatus()), number(max), number(period),
|
||||
unit == null || unit.getValue() == null ? "" : unit.getValue().trim()); // missing unit = invalid = lockout off
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Config saveConfig(Config c) {
|
||||
if (c == null) throw new IllegalArgumentException("body is required");
|
||||
if (c.maxAttempts() < 1) throw new IllegalArgumentException("maxAttempts must be at least 1");
|
||||
if (c.period() < 1) throw new IllegalArgumentException("period must be at least 1");
|
||||
if (c.chronoUnit() == null) throw new IllegalArgumentException("unit must be S, M, H or D");
|
||||
put(BLOCK, PERIOD_PARAM, c.enabled() ? "Y" : "N", String.valueOf(c.period()));
|
||||
put(BLOCK, MAX_PARAM, null, String.valueOf(c.maxAttempts()));
|
||||
put(UNIT, "ADMIN_LOGIN_BLOCK_TIME_UNIT", null, c.unit());
|
||||
return config();
|
||||
}
|
||||
|
||||
public List<Rule> passwordRules() {
|
||||
return properties.findByType(PWD).stream().sorted(Comparator.comparing(r -> r.getId()))
|
||||
.map(r -> new Rule(r.getId(), r.getParam(), r.getStatus(), r.getValue())).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Rule> savePasswordRules(List<Rule> input) {
|
||||
if (input == null) throw new IllegalArgumentException("body is required");
|
||||
List<PasswordRuleProperty> rows = new ArrayList<>();
|
||||
for (Rule in : input) { // validate everything before saving anything
|
||||
if (in == null) throw new IllegalArgumentException("rule is required");
|
||||
if (!"Y".equals(in.status()) && !"N".equals(in.status())) throw new IllegalArgumentException("status must be Y or N");
|
||||
if (in.id() == null) throw new IllegalArgumentException("id is required");
|
||||
PasswordRuleProperty row = properties.findById(in.id()).filter(r -> PWD.equals(r.getType()))
|
||||
.orElseThrow(() -> new IllegalArgumentException("unknown password rule " + in.id()));
|
||||
String p = row.getParam();
|
||||
if (in.value() != null && p != null && (p.endsWith("_MIN") || p.endsWith("_MAX")) && !in.value().matches("\\d{1,9}"))
|
||||
throw new IllegalArgumentException(p + " must be a non-negative integer");
|
||||
rows.add(row);
|
||||
}
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
rows.get(i).setStatus(input.get(i).status());
|
||||
if (input.get(i).value() != null) rows.get(i).setValue(input.get(i).value());
|
||||
}
|
||||
properties.saveAll(rows);
|
||||
return passwordRules();
|
||||
}
|
||||
|
||||
/** failures: LOGIN_FAIL rows after max(now - period, newest reset); locked once there are maxAttempts of them. */
|
||||
private Locked evaluate(String username, Config c, LocalDateTime now) {
|
||||
Duration period = c.length();
|
||||
LocalDateTime since = now.minus(period);
|
||||
LocalDateTime reset = audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(username, RESETS)
|
||||
.map(LoginAudit::getDatetime).orElse(null);
|
||||
if (reset != null && reset.isAfter(since)) since = reset;
|
||||
List<LoginAudit> f = audits.findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(username, "LOGIN_FAIL", since);
|
||||
if (f.size() < c.maxAttempts()) return null;
|
||||
return new Locked(username, f.size(), f.get(f.size() - 1).getDatetime(),
|
||||
f.get(f.size() - c.maxAttempts()).getDatetime().plus(period));
|
||||
}
|
||||
|
||||
private void write(String username, String event, String ip, String userAgent, String message) {
|
||||
String name = username == null ? "" : username.trim();
|
||||
if (name.isEmpty()) throw new IllegalArgumentException("username is required");
|
||||
LoginAudit a = new LoginAudit();
|
||||
a.setUsername(cut(name, 191));
|
||||
a.setEvent(event);
|
||||
a.setIpAddress(ip);
|
||||
a.setUserAgent(userAgent);
|
||||
a.setMessage(message);
|
||||
a.setDatetime(LocalDateTime.now(clock));
|
||||
User user = users.findByUsername(name);
|
||||
if (user != null) a.setCompanyId(user.getCompanyId());
|
||||
audits.save(a);
|
||||
}
|
||||
|
||||
private PasswordRuleProperty row(String type, String param) {
|
||||
return properties.findByType(type).stream().filter(r -> param.equals(r.getParam())).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private void put(String type, String param, String status, String value) {
|
||||
PasswordRuleProperty r = row(type, param);
|
||||
if (r == null) {
|
||||
r = new PasswordRuleProperty();
|
||||
r.setType(type);
|
||||
r.setParam(param);
|
||||
r.setStatus("Y");
|
||||
}
|
||||
if (status != null) r.setStatus(status);
|
||||
r.setValue(value);
|
||||
properties.save(r);
|
||||
}
|
||||
|
||||
private static int number(PasswordRuleProperty r) {
|
||||
try {
|
||||
return r == null ? 0 : Integer.parseInt(r.getValue().trim());
|
||||
} catch (RuntimeException e) { // null or non-numeric value
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static String cut(String s, int max) {
|
||||
return s == null || s.length() <= max ? s : s.substring(0, max);
|
||||
}
|
||||
}
|
||||
+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