fix: harden authentication and revoke stale sessions
This commit is contained in:
1 parent
c716ec7478
commit
d994ffb9a5
14 files changed
+373
-29
No files matched your search
@@ -32,6 +32,15 @@ class AuthRolesTest {
|
||||
verify(hasher).hash("test-password");
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstBootstrapCannotUsePublishedDefaultsOrExamplePlaceholders() {
|
||||
for (String password : List.of("admin123", "GENERATE_ADMIN_PASSWORD", "replace-with-a-strong-initial-password")) {
|
||||
assertEquals("INVALID_ADMIN_CONFIG", assertThrows(ApiException.class, () -> auth.ensureAdmin("adimin", password, "Owner")).getCode());
|
||||
}
|
||||
verify(jdbc, never()).update(anyString(), any(Object[].class));
|
||||
verifyNoInteractions(hasher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bootstrapPromotesLegacyAdminWithoutReplacingPassword() throws Exception {
|
||||
lookupUser(ownerId, "admin");
|
||||
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import com.moyi.controlplane.common.ApiExceptionHandler;
|
||||
import com.moyi.controlplane.security.SecretCipher;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.sql.DataSource;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@EnabledIfEnvironmentVariable(named="MOYI_AUTH_TEST_JDBC_URL", matches="jdbc:postgresql://127\\.0\\.0\\.1:[0-9]+/.+")
|
||||
class AuthSecurityPostgresTest {
|
||||
@Configuration @EnableTransactionManagement(proxyTargetClass=true) static class Transactions {}
|
||||
private final UUID userId = UUID.randomUUID();
|
||||
private final ObjectMapper json = new ObjectMapper().findAndRegisterModules();
|
||||
private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "isolated-security-test");
|
||||
private DriverManagerDataSource base, source;
|
||||
private String schema;
|
||||
private JdbcTemplate jdbc;
|
||||
private AnnotationConfigApplicationContext context;
|
||||
private AuthService auth;
|
||||
private PasswordHasher hasher;
|
||||
private MockMvc http;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL");
|
||||
schema = "auth_security_" + UUID.randomUUID().toString().replace("-", "");
|
||||
base = new DriverManagerDataSource(url, "moyi_role_test", "");
|
||||
source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", "");
|
||||
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
|
||||
jdbc = new JdbcTemplate(source); hasher = spy(new PasswordHasher("isolated-pepper"));
|
||||
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role) VALUES (?,'security_member','username',?,'Test','super_admin')", userId, hasher.hash("original-password"));
|
||||
context = new AnnotationConfigApplicationContext();
|
||||
context.register(Transactions.class);
|
||||
context.registerBean(DataSource.class, () -> source);
|
||||
context.registerBean(DataSourceTransactionManager.class, () -> new DataSourceTransactionManager(source));
|
||||
context.registerBean(AuthService.class, () -> new AuthService(jdbc, hasher, json, 168));
|
||||
context.registerBean(TotpService.class, () -> new TotpService(jdbc, new SecretCipher("isolated-mfa-key")));
|
||||
context.refresh(); auth = context.getBean(AuthService.class);
|
||||
http = MockMvcBuilders.standaloneSetup(new AuthController(auth, mock(VerificationService.class), 168, true)).setControllerAdvice(new ApiExceptionHandler()).build();
|
||||
}
|
||||
|
||||
@AfterEach void cleanup() {
|
||||
if (context != null) context.close();
|
||||
if (base != null && schema != null) new JdbcTemplate(base).execute("DROP SCHEMA " + schema + " CASCADE");
|
||||
}
|
||||
private String session() { return auth.login("security_member", "original-password", meta).token(); }
|
||||
|
||||
@Test void passwordChangeRevokesEverySessionAndClearsTheBrowserCookie() throws Exception {
|
||||
String first = session(), second = session();
|
||||
http.perform(patch("/api/auth/account").cookie(new Cookie("moyi_session", first)).contentType("application/json")
|
||||
.content("{\"displayName\":\"Test\",\"currentPassword\":\"original-password\",\"newPassword\":\"replacement-password\"}"))
|
||||
.andExpect(status().isOk()).andExpect(cookie().maxAge("moyi_session", 0));
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(first)).getStatus());
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(second)).getStatus());
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> session()).getStatus());
|
||||
assertNotNull(auth.login("security_member", "replacement-password", meta).token());
|
||||
}
|
||||
|
||||
@Test void allRolesHaveTheSamePasswordBoundsAndProfileOnlySaveKeepsSessions() {
|
||||
String token = session();
|
||||
assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> auth.updateAccount(token, "Test", "original-password", "x", meta)).getCode());
|
||||
assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> auth.resetPassword("security_member", "short", meta)).getCode());
|
||||
assertEquals("WEAK_PASSWORD", assertThrows(ApiException.class, () -> auth.register("unused", "new@example.test", "x".repeat(257), "New", meta)).getCode());
|
||||
auth.updateAccount(token, "Renamed", null, null, meta);
|
||||
assertEquals("Renamed", auth.requireUser(token).displayName());
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM auth_sessions WHERE revoked_at IS NOT NULL", Integer.class));
|
||||
}
|
||||
|
||||
@Test void failedLoginBudgetIsCommittedAndHttpReturnsRetryAfter() throws Exception {
|
||||
for (int i = 0; i < 10; i++) assertEquals(401, assertThrows(ApiException.class, () -> auth.login("missing_member", "wrong-password", meta)).getStatus());
|
||||
http.perform(post("/api/auth/login").contentType("application/json").content("{\"account\":\"missing_member\",\"password\":\"wrong-password\"}"))
|
||||
.andExpect(status().isTooManyRequests()).andExpect(header().exists("Retry-After"));
|
||||
assertEquals(2, jdbc.queryForObject("SELECT count(*) FROM auth_login_windows", Integer.class));
|
||||
assertFalse(jdbc.queryForObject("SELECT string_agg(bucket_hash,',') FROM auth_login_windows", String.class).contains("missing_member"));
|
||||
jdbc.update("UPDATE auth_login_windows SET expires_at=clock_timestamp()-interval '1 second'");
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.login("missing_member", "wrong-password", meta)).getStatus());
|
||||
}
|
||||
|
||||
@Test void concurrentLoginBudgetCannotExceedTheAccountLimit() throws Exception {
|
||||
var start = new CountDownLatch(1);
|
||||
try (var executor = Executors.newFixedThreadPool(12)) {
|
||||
var results = new ArrayList<java.util.concurrent.Future<Integer>>();
|
||||
for (int i = 0; i < 20; i++) results.add(executor.submit(() -> {
|
||||
assertTrue(start.await(10, TimeUnit.SECONDS));
|
||||
try { auth.login("missing_member", "wrong-password", meta); return 200; }
|
||||
catch (ApiException error) { return error.getStatus(); }
|
||||
}));
|
||||
start.countDown();
|
||||
var codes = new ArrayList<Integer>();
|
||||
for (var result : results) codes.add(result.get(30, TimeUnit.SECONDS));
|
||||
assertEquals(10, codes.stream().filter(code -> code == 401).count());
|
||||
assertEquals(10, codes.stream().filter(code -> code == 429).count());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sourceBudgetAlsoLimitsChangingUnknownAccounts() {
|
||||
var limiter = new LoginAttemptLimiter(jdbc);
|
||||
for (int i = 0; i < 50; i++) limiter.check("different-" + i, "127.0.0.1");
|
||||
assertEquals(429, assertThrows(ApiException.class, () -> limiter.check("yet-another", "127.0.0.1")).getStatus());
|
||||
assertDoesNotThrow(() -> limiter.check("yet-another", "127.0.0.2"));
|
||||
}
|
||||
|
||||
@Test void passwordResetWinningTheUserLockPreventsOldPasswordSessionIssuance() throws Exception {
|
||||
try (var executor = Executors.newSingleThreadExecutor()) {
|
||||
var started = new CountDownLatch(1);
|
||||
var future = new java.util.concurrent.atomic.AtomicReference<java.util.concurrent.Future<Integer>>();
|
||||
new TransactionTemplate(new DataSourceTransactionManager(source)).execute(status -> {
|
||||
jdbc.queryForList("SELECT id FROM users WHERE id=? FOR UPDATE", userId);
|
||||
future.set(executor.submit(() -> {
|
||||
started.countDown();
|
||||
try { session(); return 200; } catch (ApiException error) { return error.getStatus(); }
|
||||
}));
|
||||
try { assertTrue(started.await(10, TimeUnit.SECONDS)); } catch (InterruptedException error) { throw new AssertionError(error); }
|
||||
auth.resetPassword("security_member", "replacement-password", meta);
|
||||
return null;
|
||||
});
|
||||
assertEquals(401, future.get().get(20, TimeUnit.SECONDS));
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM auth_sessions WHERE revoked_at IS NULL", Integer.class));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void loginWinningTheLockStillGetsRevokedByFollowingPasswordReset() throws Exception {
|
||||
var verified = new CountDownLatch(1); var allow = new CountDownLatch(1);
|
||||
doAnswer(call -> {
|
||||
verified.countDown(); assertTrue(allow.await(15, TimeUnit.SECONDS)); return call.callRealMethod();
|
||||
}).when(hasher).matches(eq("original-password"), anyString());
|
||||
try (var executor = Executors.newFixedThreadPool(2)) {
|
||||
var login = executor.submit(this::session);
|
||||
assertTrue(verified.await(10, TimeUnit.SECONDS));
|
||||
var reset = executor.submit(() -> auth.resetPassword("security_member", "replacement-password", meta));
|
||||
allow.countDown();
|
||||
String token = login.get(20, TimeUnit.SECONDS); reset.get(20, TimeUnit.SECONDS);
|
||||
assertEquals(401, assertThrows(ApiException.class, () -> auth.requireUser(token)).getStatus());
|
||||
} finally { allow.countDown(); }
|
||||
}
|
||||
|
||||
@Test void mfaFailuresRemainCommittedInsideTheLoginTransaction() {
|
||||
var cipher = new SecretCipher("isolated-mfa-key");
|
||||
jdbc.update("INSERT INTO user_totp(user_id,secret_ciphertext,enabled) VALUES (?,?,true)", userId, cipher.encrypt("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
|
||||
for (int i = 0; i < 5; i++) assertEquals("INVALID_MFA_CODE", assertThrows(ApiException.class, () -> auth.login("security_member", "original-password", "not-a-code", meta)).getCode());
|
||||
assertEquals("MFA_RATE_LIMITED", assertThrows(ApiException.class, () -> auth.login("security_member", "original-password", "not-a-code", meta)).getCode());
|
||||
assertEquals(5, jdbc.queryForObject("SELECT attempts FROM user_totp WHERE user_id=?", Integer.class, userId));
|
||||
assertEquals(0, jdbc.queryForObject("SELECT count(*) FROM auth_sessions", Integer.class));
|
||||
}
|
||||
|
||||
@Test void auditFailureRollsBackPasswordAndRevocationsTogether() {
|
||||
String token = session();
|
||||
jdbc.execute("CREATE FUNCTION reject_password_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.event_type='user.account_updated' THEN RAISE EXCEPTION 'isolated audit failure'; END IF; RETURN NEW; END $$");
|
||||
jdbc.execute("CREATE TRIGGER reject_password_audit BEFORE INSERT ON auth_audit_log FOR EACH ROW EXECUTE FUNCTION reject_password_audit()");
|
||||
assertThrows(org.springframework.dao.DataAccessException.class, () -> auth.updateAccount(token, "Test", "original-password", "replacement-password", meta));
|
||||
assertNotNull(auth.requireUser(token));
|
||||
assertNotNull(session());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.moyi.controlplane.auth;
|
||||
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PasswordPolicyTest {
|
||||
@Test void everyNewPasswordHasTheSameBoundsWithoutTrimming() {
|
||||
for (String value : new String[]{null, "", " ".repeat(12), "short", "x".repeat(257)}) assertThrows(ApiException.class, () -> PasswordPolicy.validate(value));
|
||||
assertDoesNotThrow(() -> PasswordPolicy.validate("a".repeat(8)));
|
||||
assertDoesNotThrow(() -> PasswordPolicy.validate("a".repeat(256)));
|
||||
}
|
||||
@Test void malformedHashesCannotSelectUnboundedWorkAndNullIsNeverAPassword() {
|
||||
var hasher = new PasswordHasher("pepper");
|
||||
for (String encoded : new String[]{null, "", "pbkdf2$2147483647$AAECAwQFBgcICQoLDA0ODw$" + "A".repeat(43), "pbkdf2$210000$AA$AA"}) assertFalse(hasher.matches("test-password", encoded));
|
||||
assertFalse(hasher.matches(null, hasher.hash("null")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user