Light, fluffy, and always free - The AWS Local Emulator alternative
feat: Implement Cognito GlobalSignOut (#1701)
Abhigya001e530acaba
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.javaindex 4dbf8041fa..4869427f32 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java@@ -81,6 +81,7 @@ public class CognitoJsonHandler {case "GetUser" -> handleGetUser(request);case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);+ case "GlobalSignOut" -> handleGlobalSignOut(request);case "CreateGroup" -> handleCreateGroup(request);case "GetGroup" -> handleGetGroup(request);case "ListGroups" -> handleListGroups(request);@@ -609,6 +610,11 @@ public class CognitoJsonHandler {return Response.ok(objectMapper.createObjectNode()).build();}+ private Response handleGlobalSignOut(JsonNode request) {+ service.globalSignOut(request.path("AccessToken").asText());+ return Response.ok(objectMapper.createObjectNode()).build();+ }+private ObjectNode userPoolToDescriptionNode(UserPool p) {ObjectNode node = objectMapper.createObjectNode();node.put("Id", p.getId());diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex 04840d24f8..37efd3579b 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -847,13 +847,56 @@ public class CognitoService {public void adminUserGlobalSignOut(String userPoolId, String username) {// Validate user existsCognitoUser user = adminGetUser(userPoolId, username);-+// Revoke all tokens for this userrevokeAllUserTokens(userPoolId, username);-+LOG.infov("AdminUserGlobalSignOut: revoked all tokens for user {0} in pool {1}", username, userPoolId);}+ /**+ * GlobalSignOut — the self-service counterpart to AdminUserGlobalSignOut, authenticated+ * with the caller's access token instead of admin credentials. Invalidates the access,+ * ID, and refresh tokens Cognito issued to the user, matching AWS behavior.+ */+ public void globalSignOut(String accessToken) {+ if (accessToken == null || accessToken.isEmpty()) {+ throw new AwsException("InvalidParameterException",+ "1 validation error detected: Value at 'accessToken' failed to satisfy constraint: Member must not be null", 400);+ }++ String username = extractUsernameFromToken(accessToken);+ String poolId = extractPoolIdFromToken(accessToken);+ String jti = extractJtiFromToken(accessToken);++ if (username == null || poolId == null || jti == null) {+ throw new AwsException("NotAuthorizedException", "Invalid access token", 400);+ }++ // A token that was already revoked (or issued before an earlier sign-out) cannot+ // authorize a fresh sign-out.+ validateTokenNotRevoked(jti, poolId, "access");+ Long iat = extractIatFromToken(accessToken);+ validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);++ // Confirm the pool and user actually exist before mutating the revocation store,+ // matching the implicit validation AWS performs and the adminUserGlobalSignOut counterpart.+ try {+ adminGetUser(poolId, username);+ } catch (AwsException e) {+ if ("UserNotFoundException".equals(e.getErrorCode())+ || "ResourceNotFoundException".equals(e.getErrorCode())) {+ throw new AwsException("NotAuthorizedException", "Invalid access token", 400);+ }+ throw e;+ }++ // Revoke all of the user's issued tokens (access, ID, refresh).+ revokeAllUserTokens(poolId, username);++ LOG.infov("GlobalSignOut: revoked all tokens for user {0} in pool {1}", username, poolId);+ }+public CognitoUser adminGetUser(String userPoolId, String username) {UserPool pool = poolStore.get(userPoolId).orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 400));diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.javanew file mode 100644index 0000000000..d4ca9639fb--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java@@ -0,0 +1,260 @@+package io.github.hectorvent.floci.services.cognito;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.util.Base64;+import java.util.UUID;++import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for the GlobalSignOut API — the self-service counterpart to+ * AdminUserGlobalSignOut, authenticated with the caller's access token.+ * <p>+ * Verifies that all tokens Cognito issued to the user (access, ID, refresh) are+ * invalidated after GlobalSignOut, while a fresh login continues to work.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class GlobalSignOutIntegrationTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static String poolId;+ private static String clientId;+ private static String accessToken;+ private static String refreshToken;++ private static final String USERNAME = "bob";+ private static final String PASSWORD = "Password123!";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ /** POST without asserting 200 — lets tests inspect the error response. */+ private static JsonNode cognitoJsonAny(String action, String body) throws Exception {+ return MAPPER.readTree(cognitoAction(action, body).then().extract().asString());+ }++ @Test+ @Order(1)+ void setupPoolAndUser() throws Exception {+ JsonNode pool = cognitoJson("CreateUserPool", """+ {"PoolName":"GlobalSignOutTestPool"}+ """);+ poolId = pool.path("UserPool").path("Id").asText();+ assertFalse(poolId.isBlank(), "Pool ID must not be blank");++ JsonNode client = cognitoJson("CreateUserPoolClient", """+ {+ "UserPoolId": "%s",+ "ClientName": "test-client",+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]+ }+ """.formatted(poolId));+ clientId = client.path("UserPoolClient").path("ClientId").asText();+ assertFalse(clientId.isBlank(), "Client ID must not be blank");++ cognitoAction("AdminCreateUser", """+ {"UserPoolId":"%s","Username":"%s"}+ """.formatted(poolId, USERNAME)).then().statusCode(200);++ cognitoAction("AdminSetUserPassword", """+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}+ """.formatted(poolId, USERNAME, PASSWORD)).then().statusCode(200);+ }++ @Test+ @Order(2)+ void authenticateAndCaptureTokens() throws Exception {+ JsonNode auth = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}+ }+ """.formatted(clientId, USERNAME, PASSWORD));++ accessToken = auth.path("AuthenticationResult").path("AccessToken").asText();+ refreshToken = auth.path("AuthenticationResult").path("RefreshToken").asText();++ assertFalse(accessToken.isBlank(), "AccessToken must be present after sign-in");+ assertFalse(refreshToken.isBlank(), "RefreshToken must be present after sign-in");+ }++ @Test+ @Order(3)+ void getUserWorksBeforeSignOut() {+ // The access token must be usable before sign-out+ cognitoAction("GetUser", """+ {"AccessToken":"%s"}+ """.formatted(accessToken))+ .then()+ .statusCode(200);+ }++ @Test+ @Order(4)+ void globalSignOutSucceeds() {+ // GlobalSignOut must return HTTP 200 with an empty body+ cognitoAction("GlobalSignOut", """+ {"AccessToken":"%s"}+ """.formatted(accessToken))+ .then()+ .statusCode(200);+ }++ @Test+ @Order(5)+ void accessTokenIsRejectedAfterSignOut() throws Exception {+ // The access token used to sign out must itself be invalidated+ JsonNode body = cognitoJsonAny("GetUser", """+ {"AccessToken":"%s"}+ """.formatted(accessToken));++ assertEquals("NotAuthorizedException", body.path("__type").asText(),+ "Expected NotAuthorizedException for the access token after GlobalSignOut, body was: " + body);+ }++ @Test+ @Order(6)+ void refreshTokenIsRejectedAfterSignOut() throws Exception {+ // The refresh token must also be rejected after GlobalSignOut+ JsonNode body = cognitoJsonAny("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "REFRESH_TOKEN_AUTH",+ "AuthParameters": {"REFRESH_TOKEN": "%s"}+ }+ """.formatted(clientId, refreshToken));++ assertEquals("NotAuthorizedException", body.path("__type").asText(),+ "Expected NotAuthorizedException for the refresh token after GlobalSignOut");+ }++ @Test+ @Order(7)+ void globalSignOutFailsForInvalidToken() throws Exception {+ // A malformed / non-JWT access token must surface NotAuthorizedException+ JsonNode body = cognitoJsonAny("GlobalSignOut", """+ {"AccessToken":"not-a-real-token"}+ """);++ assertEquals("NotAuthorizedException", body.path("__type").asText(),+ "GlobalSignOut with an invalid access token must fail with NotAuthorizedException");+ }++ @Test+ @Order(8)+ void newLoginSucceedsAfterSignOut() throws Exception {+ // A fresh login must still work — sign-out does not lock the account+ JsonNode auth = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}+ }+ """.formatted(clientId, USERNAME, PASSWORD));++ String newAccess = auth.path("AuthenticationResult").path("AccessToken").asText();+ String newRefresh = auth.path("AuthenticationResult").path("RefreshToken").asText();+ assertFalse(newAccess.isBlank(), "Fresh login must succeed after GlobalSignOut");+ assertNotEquals(accessToken, newAccess, "New session must issue a new AccessToken");+ assertNotEquals(refreshToken, newRefresh, "New session must issue a new RefreshToken");++ // The freshly issued refresh token must be usable — tokens minted after sign-out are valid.+ // (Verified via the refresh flow, whose millisecond-granular iat reliably post-dates the+ // revocation timestamp even when the new login lands in the same wall-clock second.)+ JsonNode refreshed = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "REFRESH_TOKEN_AUTH",+ "AuthParameters": {"REFRESH_TOKEN": "%s"}+ }+ """.formatted(clientId, newRefresh));++ assertFalse(refreshed.path("AuthenticationResult").path("AccessToken").asText().isBlank(),+ "Refresh should succeed for tokens issued after GlobalSignOut");+ }++ @Test+ @Order(9)+ void oldRefreshTokenStillRejectedAfterNewLogin() throws Exception {+ // Even after a new login, the original revoked refresh token remains invalid+ JsonNode body = cognitoJsonAny("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "REFRESH_TOKEN_AUTH",+ "AuthParameters": {"REFRESH_TOKEN": "%s"}+ }+ """.formatted(clientId, refreshToken));++ assertEquals("NotAuthorizedException", body.path("__type").asText(),+ "Old revoked refresh token must still be rejected after a new login");+ }++ @Test+ @Order(10)+ void globalSignOutFailsForNonexistentUser() throws Exception {+ // A syntactically valid (but unverified) token whose username does not exist in the+ // pool must be rejected — GlobalSignOut confirms the user exists before touching the+ // revocation store, matching AdminUserGlobalSignOut and AWS behavior.+ String forged = forgeAccessToken(poolId, "ghost");++ JsonNode body = cognitoJsonAny("GlobalSignOut", """+ {"AccessToken":"%s"}+ """.formatted(forged));++ assertEquals("NotAuthorizedException", body.path("__type").asText(),+ "GlobalSignOut for a nonexistent user must fail with NotAuthorizedException, body was: " + body);+ }++ @Test+ @Order(11)+ void globalSignOutFailsForNonexistentPool() throws Exception {+ String forged = forgeAccessToken("us-east-1_NONEXISTENT", "ghost");++ JsonNode body = cognitoJsonAny("GlobalSignOut", """+ {"AccessToken":"%s"}+ """.formatted(forged));++ assertEquals("NotAuthorizedException", body.path("__type").asText(),+ "GlobalSignOut for a nonexistent pool must fail with NotAuthorizedException, body was: " + body);+ }++ @Test+ @Order(12)+ void globalSignOutRejectsMissingAccessToken() throws Exception {+ JsonNode body = cognitoJsonAny("GlobalSignOut", "{}");++ assertEquals("InvalidParameterException", body.path("__type").asText(),+ "GlobalSignOut with no AccessToken must fail with InvalidParameterException, body was: " + body);+ }++ /** Build an unsigned JWT-shaped access token — the emulator decodes the payload without verifying the signature. */+ private static String forgeAccessToken(String poolId, String username) {+ long nowSeconds = System.currentTimeMillis() / 1000L;+ String header = base64Url("{\"alg\":\"RS256\",\"typ\":\"JWT\"}");+ String payload = base64Url(("""+ {"username":"%s","iss":"https://cognito-idp.us-east-1.amazonaws.com/%s",\+ "jti":"%s","iat":%d,"token_use":"access"}""")+ .formatted(username, poolId, UUID.randomUUID(), nowSeconds));+ return header + "." + payload + ".sig";+ }++ private static String base64Url(String value) {+ return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes());+ }+}