mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cognito): expire auth challenge sessions (#4417)
* fix(cognito): expire auth challenge sessions InitiateAuth and RespondToAuthChallenge session tokens for SRP, custom auth, and USER_AUTH never expired, so an abandoned challenge session lingered in memory forever and could still be completed long after AWS would have rejected it. Track when each session was issued and reject expired ones with the NotAuthorizedException Cognito returns in that case, purging expired entries whenever a new one is created. AWS defaults AuthSessionValidity to 3 minutes (configurable 3-15 via CreateUserPoolClient); UserPoolClient does not yet store a per-client override, so every client uses the 3 minute default for now. * fix(cognito): stamp custom auth tokens when they are issued A CUSTOM_AUTH session's issue time was recorded before the DefineAuthChallenge and CreateAuthChallenge triggers ran, so a slow trigger shortened the session handed to the client. The issue time also lived on the flow state shared across rounds, so minting the next round's token refreshed the old token while it was still in the map. Each custom auth token now carries its own issue time, stamped when it is stored, and every issuance path (including both continuations) purges expired tokens first. * style(cognito): brace the custom auth session lookup * test(cognito): use the shared MutableClock * docs(cognito): document auth challenge session expiry * chore: rerun CI * chore: rerun CI
This commit is contained in:
1 parent
a5ded3e162
commit
8b9f441bb4
5 files changed
+303
-16
No files matched your search
+78
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.ses.SesService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -28,6 +29,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -879,6 +881,82 @@ class CognitoLambdaTriggersTest {
|
||||
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());
|
||||
}
|
||||
|
||||
private CognitoService serviceWithClock(MutableClock clock) {
|
||||
return new CognitoService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
"http://localhost:4566", "cloudfront.net", regionResolver, lambdaService, mock(AcmService.class),
|
||||
null, null, mock(TlsCertificateManager.class), clock);
|
||||
}
|
||||
|
||||
private UserPoolClient customAuthClient(CognitoService clockedService) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("PoolName", "trigger-pool");
|
||||
req.put("LambdaConfig", Map.of(
|
||||
"DefineAuthChallenge", "arn:aws:lambda:::define",
|
||||
"CreateAuthChallenge", "arn:aws:lambda:::create",
|
||||
"VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));
|
||||
UserPool pool = clockedService.createUserPool(req, "us-east-1");
|
||||
clockedService.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), null);
|
||||
clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
|
||||
return clockedService.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of(),
|
||||
null, List.of(), null, AUTH_FLOWS, null, null, List.of(), null, List.of(), null,
|
||||
null, null, List.of(), null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void customAuthSessionValidityStartsWhenTheSessionIsIssued() {
|
||||
MutableClock clock = new MutableClock();
|
||||
CognitoService clockedService = serviceWithClock(clock);
|
||||
UserPoolClient client = customAuthClient(clockedService);
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))
|
||||
.thenReturn(ok(Map.of("issueTokens", true)));
|
||||
// A slow CreateAuthChallenge trigger: two minutes pass before the session is handed out.
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
return ok(Map.of("privateChallengeParameters", Map.of("answer", "blue")));
|
||||
});
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("answerCorrect", true)));
|
||||
|
||||
String session = (String) clockedService.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
|
||||
Map.of("USERNAME", "alice")).get("Session");
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
|
||||
Map<String, Object> tokens = clockedService.respondToAuthChallenge(client.getClientId(),
|
||||
"CUSTOM_CHALLENGE", session, Map.of("USERNAME", "alice", "ANSWER", "blue"));
|
||||
|
||||
assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customAuthSessionExpiresThreeMinutesAfterItIsIssued() {
|
||||
MutableClock clock = new MutableClock();
|
||||
CognitoService clockedService = serviceWithClock(clock);
|
||||
UserPoolClient client = customAuthClient(clockedService);
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")));
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("privateChallengeParameters", Map.of("answer", "blue"))));
|
||||
|
||||
String session = (String) clockedService.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
|
||||
Map.of("USERNAME", "alice")).get("Session");
|
||||
clock.advance(Duration.ofMinutes(3).plusSeconds(1));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
clockedService.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session,
|
||||
Map.of("USERNAME", "alice", "ANSWER", "blue")));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("Invalid session for the user, session is expired.", ex.getMessage());
|
||||
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void customAuthDoesNotIssueTokensWhenVerifyAuthChallengeTriggerErrors() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("DefineAuthChallenge",
|
||||
|
||||
@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDi
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
@@ -32,6 +33,8 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
@@ -2376,6 +2379,111 @@ class CognitoServiceTest {
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Auth challenge session expiry
|
||||
// =========================================================================
|
||||
|
||||
private CognitoService serviceWithClock(Clock clock) {
|
||||
return new CognitoService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
"http://localhost:4566",
|
||||
"cloudfront.net",
|
||||
regionResolver,
|
||||
null,
|
||||
acmService,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
clock
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void respondToAuthChallengeAfterSrpSessionExpiryRejects() {
|
||||
MutableClock clock = new MutableClock();
|
||||
CognitoService clockedService = serviceWithClock(clock);
|
||||
String password = "Password123!";
|
||||
UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
|
||||
clockedService.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com"), null);
|
||||
clockedService.adminSetUserPassword(pool.getId(), "bob", password, true);
|
||||
UserPoolClient client =
|
||||
clockedService.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
|
||||
Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_SRP_AUTH",
|
||||
Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890"));
|
||||
String session = (String) initResult.get("Session");
|
||||
|
||||
clock.advance(Duration.ofMinutes(3).plusSeconds(1));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER", session,
|
||||
Map.of(
|
||||
"USERNAME", "bob",
|
||||
"PASSWORD_CLAIM_SIGNATURE", "any-sig",
|
||||
"TIMESTAMP", "Wed Apr 8 12:00:00 UTC 2026"
|
||||
)));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("Invalid session for the user, session is expired.", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void respondToAuthChallengeBeforeSrpSessionExpiryStillWorks() {
|
||||
MutableClock clock = new MutableClock();
|
||||
CognitoService clockedService = serviceWithClock(clock);
|
||||
String password = "Password123!";
|
||||
UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
|
||||
clockedService.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com"), null);
|
||||
clockedService.adminSetUserPassword(pool.getId(), "bob", password, true);
|
||||
UserPoolClient client =
|
||||
clockedService.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
|
||||
Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_SRP_AUTH",
|
||||
Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890"));
|
||||
String session = (String) initResult.get("Session");
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER", session,
|
||||
Map.of(
|
||||
"USERNAME", "bob",
|
||||
"PASSWORD_CLAIM_SIGNATURE", "invalid-sig",
|
||||
"TIMESTAMP", "Wed Apr 8 12:00:00 UTC 2026"
|
||||
)));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertNotEquals("Invalid session for the user, session is expired.", ex.getMessage(),
|
||||
"a session still within AuthSessionValidity should fail signature checking, not expiry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void respondToAuthChallengeAfterUserAuthPasswordSessionExpiryRejects() {
|
||||
MutableClock clock = new MutableClock();
|
||||
CognitoService clockedService = serviceWithClock(clock);
|
||||
UserPool pool = clockedService.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
|
||||
clockedService.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "TempPass1!");
|
||||
clockedService.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
|
||||
UserPoolClient client = openClient(clockedService, pool.getId(), "c", false);
|
||||
|
||||
Map<String, Object> initResult = clockedService.initiateAuth(client.getClientId(), "USER_AUTH",
|
||||
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
|
||||
String session = (String) initResult.get("Session");
|
||||
|
||||
clock.advance(Duration.ofMinutes(3).plusSeconds(1));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
clockedService.respondToAuthChallenge(client.getClientId(), "PASSWORD", session,
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("Invalid session for the user, session is expired.", ex.getMessage());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// USER_AUTH (choice-based) flow
|
||||
// =========================================================================
|
||||
|
||||
Reference in new issue
Block a user