fix: harden the lockout after the branch review

Settings get upper limits (a huge period made every lock check fail
open), the lock check uses the same 191-character key the history
stores, login_audit.username compares like user.username, and the
module gets its own icon. Docs and design notes follow.

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-11-30 14:59:06 +08:00
1 parent e240a9c37f
commit 059107fbaa
8 files changed
+31 -10

No files matched your search

+1 -1
View File
@@ -269,7 +269,7 @@ data:
## 10. Known gaps at go-live
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal data.
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username for 15 minutes, even with the right password, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
+2 -2
View File
@@ -129,7 +129,7 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
CREATE TABLE IF NOT EXISTS `login_audit` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NULL COMMENT 'the user''s company when the username matches a user',
`username` varchar(191) NOT NULL,
`username` varchar(191) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'compared like `user`.`username`',
`datetime` datetime NOT NULL,
`event` varchar(20) NOT NULL COMMENT 'LOGIN_SUCCESS | LOGIN_FAIL | LOGIN_LOCKED | LOGOUT | UNLOCK_RESET | PASSWORD_CHANGED',
`ip_address` varchar(64) NULL,
@@ -150,4 +150,4 @@ WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
-- add-admin-login-security/sql/03-login-security-module.sql
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'ShieldCheck');
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
@@ -41,7 +41,7 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe
- `max` is the new row `ADMIN_LOGIN_MAX_ATTEMPT` (type `ADMIN_LOGIN_BLOCK`).
- **Locked** means `on` and `count(LOGIN_FAIL where username = ? and datetime > greatest(now - period, latestReset)) >= max`. `latestReset` is the newest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` for that username.
- **Lock end** is the datetime of the oldest counted failure that keeps the count at `max`, plus the period. The locked list uses it, and so do the tests.
- **Username matching:** the lock rule compares the trimmed username exactly. MySQL's default collation makes that comparison case-insensitive, which is acceptable.
- **Username matching:** the lock rule uses the trimmed username, cut to 191 characters, the same key the history stores. `login_audit.username` uses `utf8mb4_general_ci`, so it compares like `user.username` (case-insensitive).
3. **services-system endpoints** (`LoginSecurityController`, under `/loginSecurity`; the gateway gets a matching route):
- `GET isLocked/{username}` returns `{locked}`.
@@ -49,7 +49,7 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe
- `POST audit` takes `{username, event, from, to, page, size}`. Dates are `yyyy-MM-dd`. It returns newest first, with size capped at 100.
- `GET locked` returns `[{username, failures, lastFailure, lockedUntil}]`. It considers usernames with a `LOGIN_FAIL` inside the period.
- `POST unlock` takes `{username, by}` and writes `UNLOCK_RESET` with `message = "unlocked by <by>"`.
- `GET config` and `POST config` take `{enabled, maxAttempts, period, unit}`. They validate `maxAttempts` and `period` ≥ 1 and the unit in S, M, H or D, and return 400 otherwise.
- `GET config` and `POST config` take `{enabled, maxAttempts, period, unit}`. They validate `maxAttempts` between 1 and 1000, `period` between 1 and 10000, and the unit in S, M, H or D, and return 400 otherwise. The upper limits keep the lock window computable.
- `GET passwordRules` and `POST passwordRules` take `[{id, status, value}]`. They only update existing `ADMIN_PWD_FORMAT` rows, and refuse any id outside that type with 400.
4. **services-system `/user/changeAdminPassword`** takes `{id, currentPassword, newPassword}` and returns one result string:
@@ -103,7 +103,7 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe
- Settings: a lockout form, then a rules table with an on/off switch and a value.
- Proxy: `app/api/login-security/[[...path]]/route.ts` for GET, POST and PUT, refusing dot segments. `app/api/auth/change-password/route.ts`.
10. **Module row:** `(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'ShieldCheck')`. No role grants, so only super admins see it until granted.
10. **Module row:** `(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield')`. No role grants, so only super admins see it until granted.
## Risks / Trade-offs
@@ -112,3 +112,4 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe
- **Concurrency:** two simultaneous wrong guesses may both pass the pre-check, so the count can exceed `max` by the number of parallel requests. Accepted; it is a limit, not a security boundary.
- **History growth:** no purge. One company and a handful of staff make this small. A purge can come with the audit viewer.
- **Forged IP or user agent:** these are stored for reading only, and never trusted.
- **Unauthenticated writes behind the gateway key:** `/loginSecurity/record` needs no user token, so it can write `LOGIN_SUCCESS` or `PASSWORD_CHANGED` rows, and both clear a lock. The older `/blockLoginPeriod/**` routes also skip the token, and their save can rewrite the `ADMIN_LOGIN_BLOCK` rows. Both are reachable only with a gateway api-key from an allowed IP, which today only mobile-api holds (`docs/deployment.md` section 7). A later change can narrow the `/blockLoginPeriod/` bypass to its read endpoints.
@@ -109,7 +109,7 @@ The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, n
### Requirement: Lockout and password-rule settings
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum or period below 1 and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
#### Scenario: Change the lockout settings
@@ -7,7 +7,7 @@ USE `service-system`;
CREATE TABLE IF NOT EXISTS `login_audit` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NULL COMMENT 'the user''s company when the username matches a user',
`username` varchar(191) NOT NULL,
`username` varchar(191) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'compared like `user`.`username`',
`datetime` datetime NOT NULL,
`event` varchar(20) NOT NULL COMMENT 'LOGIN_SUCCESS | LOGIN_FAIL | LOGIN_LOCKED | LOGOUT | UNLOCK_RESET | PASSWORD_CHANGED',
`ip_address` varchar(64) NULL,
@@ -4,4 +4,4 @@
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'ShieldCheck');
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
@@ -73,7 +73,8 @@ public class LoginSecurityService {
public boolean isLocked(String username) {
Config c = config();
return c.enabled() && c.valid() && evaluate(username.trim(), c, LocalDateTime.now(clock)) != null;
// Same key the history stores (trimmed, cut to the column size).
return c.enabled() && c.valid() && evaluate(cut(username.trim(), 191), c, LocalDateTime.now(clock)) != null;
}
public List<Locked> lockedUsers() {
@@ -120,6 +121,9 @@ public class LoginSecurityService {
if (c == null) throw new IllegalArgumentException("body is required");
if (c.maxAttempts() < 1) throw new IllegalArgumentException("Max attempts must be at least 1");
if (c.period() < 1) throw new IllegalArgumentException("Period must be at least 1");
// Upper limits keep the window computable; a huge period would make every lock check fail open.
if (c.maxAttempts() > 1000) throw new IllegalArgumentException("Max attempts must be at most 1000");
if (c.period() > 10000) throw new IllegalArgumentException("Period must be at most 10000");
if (c.chronoUnit() == null) throw new IllegalArgumentException("Unit must be seconds, minutes, hours or days");
put(BLOCK, PERIOD_PARAM, c.enabled() ? "Y" : "N", String.valueOf(c.period()));
put(BLOCK, MAX_PARAM, null, String.valueOf(c.maxAttempts()));
@@ -116,6 +116,22 @@ class LoginSecurityServiceTest {
assertThat(service.isLocked("admin")).isFalse();
}
@Test
void lockCheckUsesTheSame191CharacterKeyTheHistoryStores() {
String stored = "a".repeat(191);
settings("Y", "10", "1", "M");
failures(stored, NOW.minusMinutes(1));
assertThat(service.isLocked(stored + "bbbb")).isTrue();
}
@Test
void settingsHaveUpperLimits() {
assertThatThrownBy(() -> service.saveConfig(new Config(true, 1001, 15, "M"))).hasMessage("Max attempts must be at most 1000");
assertThatThrownBy(() -> service.saveConfig(new Config(true, 5, 10001, "M"))).hasMessage("Period must be at most 10000");
verify(properties, never()).save(any());
}
@Test
void usernameIsTrimmed() {
settings("Y", "10", "1", "M");