Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): auto-generate sub, fix JWT sub claim, add AdminUserGlobalSignOut (#68) (#183)
Hector Ventura9d6181c5479a
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.javaindex e0cfc8f56c..1830444a92 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common;import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsQueryHandler;+import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;import io.github.hectorvent.floci.services.elasticache.ElastiCacheQueryHandler;import io.github.hectorvent.floci.services.iam.IamQueryHandler;import io.github.hectorvent.floci.services.iam.StsQueryHandler;@@ -109,6 +110,7 @@ public class AwsQueryController {private final IamQueryHandler iamQueryHandler;private final StsQueryHandler stsQueryHandler;private final CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler;+ private final CognitoJsonHandler cognitoJsonHandler;private final RegionResolver regionResolver;@Inject@@ -119,6 +121,7 @@ public class AwsQueryController {SesQueryHandler sesQueryHandler,IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler,CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler,+ CognitoJsonHandler cognitoJsonHandler,RegionResolver regionResolver) {this.cloudFormationQueryHandler = cloudFormationQueryHandler;this.elastiCacheQueryHandler = elastiCacheQueryHandler;@@ -129,6 +132,7 @@ public class AwsQueryController {this.iamQueryHandler = iamQueryHandler;this.stsQueryHandler = stsQueryHandler;this.cloudWatchMetricsQueryHandler = cloudWatchMetricsQueryHandler;+ this.cognitoJsonHandler = cognitoJsonHandler;this.regionResolver = regionResolver;}@@ -160,11 +164,29 @@ public class AwsQueryController {case "email" -> sesQueryHandler.handle(action, formParams, region);case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region);case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region);+ case "cognito-idp" -> handleCognitoQuery(action, formParams, region);default -> xmlErrorResponse("UnknownService","Unknown or unsupported service: " + service, 400);};}+ private Response handleCognitoQuery(String action, MultivaluedMap<String, String> formParams, String region) {+ // Cognito is primarily JSON 1.1, but we provide a bridge for Query protocol if hit.+ // Convert MultivaluedMap to JsonNode if needed, but for now just return UnsupportedOperation+ // with Cognito namespace.+ String xml = new XmlBuilder()+ .start("ErrorResponse")+ .start("Error")+ .elem("Type", "Sender")+ .elem("Code", "UnsupportedOperation")+ .elem("Message", "Operation " + action + " is not supported by Cognito via Query protocol.")+ .end("Error")+ .elem("RequestId", UUID.randomUUID().toString())+ .end("ErrorResponse")+ .build();+ return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build();+ }+/*** Determines the target AWS service. Prefers the service name embedded in the* Authorization header credential scope. Falls back to action-name lookup when@@ -205,7 +227,19 @@ public class AwsQueryController {"GetIdentityDkimAttributes");- private static final Set<String> QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation", "email");+ private static final Set<String> COGNITO_ACTIONS = Set.of(+ "AdminCreateUser", "AdminGetUser", "AdminDeleteUser", "AdminSetUserPassword",+ "AdminUpdateUserAttributes", "AdminUserGlobalSignOut", "ListUsers",+ "InitiateAuth", "AdminInitiateAuth", "RespondToAuthChallenge",+ "SignUp", "ConfirmSignUp", "ChangePassword", "ForgotPassword",+ "ConfirmForgotPassword", "GetUser", "UpdateUserAttributes",+ "CreateUserPool", "DescribeUserPool", "ListUserPools", "DeleteUserPool",+ "CreateUserPoolClient", "DescribeUserPoolClient", "ListUserPoolClients", "DeleteUserPoolClient",+ "CreateGroup", "GetGroup", "ListGroups", "DeleteGroup",+ "AdminAddUserToGroup", "AdminRemoveUserFromGroup", "AdminListGroupsForUser"+ );++ private static final Set<String> QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation", "email", "cognito-idp");private String resolveService(String authorization, String action) {if (authorization != null && !authorization.isEmpty()) {@@ -245,6 +279,9 @@ public class AwsQueryController {if (SES_ACTIONS.contains(action)) {return "email";}+ if (COGNITO_ACTIONS.contains(action)) {+ return "cognito-idp";+ }// SQS actions are numerous and not enumerated — fall back to sqs only for// requests that arrived without an Authorization header (raw/test clients)return "sqs";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 0af2ca2312..7b8548e128 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@@ -51,6 +51,7 @@ public class CognitoJsonHandler {case "AdminDeleteUser" -> handleAdminDeleteUser(request);case "AdminSetUserPassword" -> handleAdminSetUserPassword(request);case "AdminUpdateUserAttributes" -> handleAdminUpdateUserAttributes(request);+ case "AdminUserGlobalSignOut" -> handleAdminUserGlobalSignOut(request);case "ListUsers" -> handleListUsers(request);case "InitiateAuth" -> handleInitiateAuth(request);case "AdminInitiateAuth" -> handleAdminInitiateAuth(request);@@ -256,6 +257,14 @@ public class CognitoJsonHandler {return Response.ok(objectMapper.createObjectNode()).build();}+ private Response handleAdminUserGlobalSignOut(JsonNode request) {+ service.adminUserGlobalSignOut(+ request.path("UserPoolId").asText(),+ request.path("Username").asText()+ );+ return Response.ok(objectMapper.createObjectNode()).build();+ }+private Response handleListUsers(JsonNode request) {List<CognitoUser> users = service.listUsers(request.path("UserPoolId").asText());ObjectNode response = objectMapper.createObjectNode();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 f7364cf1ef..ac0ca6369c 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@@ -225,6 +225,11 @@ public class CognitoService {user.getAttributes().putAll(attributes);}+ // Ensure sub attribute is present+ if (!user.getAttributes().containsKey("sub")) {+ user.getAttributes().put("sub", UUID.randomUUID().toString());+ }+if (temporaryPassword != null && !temporaryPassword.isEmpty()) {user.setPasswordHash(hashPassword(temporaryPassword));user.setTemporaryPassword(true);@@ -236,6 +241,11 @@ public class CognitoService {return user;}+ public void adminUserGlobalSignOut(String userPoolId, String username) {+ adminGetUser(userPoolId, username);+ LOG.infov("AdminUserGlobalSignOut stub: user {0} in pool {1} signed out globally", username, userPoolId);+ }+public CognitoUser adminGetUser(String userPoolId, String username) {return userStore.get(userKey(userPoolId, username)).orElseThrow(() -> new AwsException("UserNotFoundException", "User not found", 404));@@ -386,6 +396,11 @@ public class CognitoService {user.getAttributes().putAll(attributes);}+ // Ensure sub attribute is present+ if (!user.getAttributes().containsKey("sub")) {+ user.getAttributes().put("sub", UUID.randomUUID().toString());+ }+userStore.put(key, user);LOG.infov("Signed up user {0} in pool {1}", username, userPoolId);return user;@@ -639,11 +654,12 @@ public class CognitoService {.collect(Collectors.joining(",", "[", "]"));groupsFragment = ",\"cognito:groups\":" + groupsJson;}+ String sub = user.getAttributes().getOrDefault("sub", user.getUsername());String payloadJson = String.format("{\"sub\":\"%s\",\"event_id\":\"%s\",\"token_use\":\"%s\",\"auth_time\":%d," +"\"iss\":\"%s\",\"exp\":%d,\"iat\":%d," +"\"username\":\"%s\",\"email\":\"%s\",\"cognito:username\":\"%s\"%s}",- UUID.randomUUID(), UUID.randomUUID(), type, now,+ escapeJson(sub), UUID.randomUUID(), type, now,escapeJson(getIssuer(pool.getId())), now + 3600, now,user.getUsername(), email, user.getUsername(), groupsFragment);diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javaindex 3f89404a5d..846e0db863 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -13,6 +13,7 @@ import java.nio.charset.StandardCharsets;import java.util.Base64;import java.util.List;import java.util.Map;+import java.util.function.Function;import static org.junit.jupiter.api.Assertions.*;@@ -262,6 +263,110 @@ class CognitoServiceTest {"Group name should be properly JSON-escaped in JWT payload");}+ // =========================================================================+ // Issue #68 — sub attribute and AdminUserGlobalSignOut+ // =========================================================================++ @Test+ void adminCreateUserAutoGeneratesSub() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ CognitoUser user = service.adminCreateUser(pool.getId(), "bob",+ Map.of("email", "[email protected]"), null);++ assertTrue(user.getAttributes().containsKey("sub"),+ "adminCreateUser should auto-generate a sub attribute");+ assertFalse(user.getAttributes().get("sub").isBlank());+ }++ @Test+ void adminCreateUserPreservesExplicitSub() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ String explicitSub = "aaaaaaaa-1111-2222-3333-444444444444";+ CognitoUser user = service.adminCreateUser(pool.getId(), "bob",+ Map.of("email", "[email protected]", "sub", explicitSub), null);++ assertEquals(explicitSub, user.getAttributes().get("sub"),+ "adminCreateUser should not overwrite an explicitly provided sub");+ }++ @Test+ void signUpAutoGeneratesSub() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "test-client",+ false, false, List.of(), List.of());++ CognitoUser user = service.signUp(client.getClientId(),+ "carol", "Pass1234!", Map.of("email", "[email protected]"));++ assertTrue(user.getAttributes().containsKey("sub"),+ "signUp should auto-generate a sub attribute");+ assertFalse(user.getAttributes().get("sub").isBlank());+ }++ @Test+ @SuppressWarnings("unchecked")+ void jwtSubMatchesStoredSubAttribute() {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "test-client",+ false, false, List.of(), List.of());++ String storedSub = service.adminGetUser(pool.getId(), "alice")+ .getAttributes().get("sub");+ assertNotNull(storedSub, "user should have a sub attribute after creation");++ Map<String, Object> authResult = service.initiateAuth(+ client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));++ Map<String, Object> auth = (Map<String, Object>) authResult.get("AuthenticationResult");+ String token = (String) auth.get("AccessToken");+ String payloadJson = new String(+ Base64.getUrlDecoder().decode(token.split("\\.")[1]), StandardCharsets.UTF_8);++ assertTrue(payloadJson.contains("\"sub\":\"" + storedSub + "\""),+ "JWT sub claim must match the stored sub attribute, not be randomly generated");+ }++ @Test+ @SuppressWarnings("unchecked")+ void jwtSubIsConsistentAcrossMultipleLogins() {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "test-client",+ false, false, List.of(), List.of());++ Function<String, String> extractSub = token -> {+ String payload = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1]), StandardCharsets.UTF_8);+ int start = payload.indexOf("\"sub\":\"") + 7;+ int end = payload.indexOf("\"", start);+ return payload.substring(start, end);+ };++ Map<String, Object> auth1 = (Map<String, Object>)+ ((Map<String, Object>) service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"))).get("AuthenticationResult");+ Map<String, Object> auth2 = (Map<String, Object>)+ ((Map<String, Object>) service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"))).get("AuthenticationResult");++ String sub1 = extractSub.apply((String) auth1.get("AccessToken"));+ String sub2 = extractSub.apply((String) auth2.get("AccessToken"));++ assertEquals(sub1, sub2, "JWT sub claim must be identical across multiple logins");+ }++ @Test+ void adminUserGlobalSignOutSucceedsForExistingUser() {+ UserPool pool = createPoolAndUser();+ assertDoesNotThrow(() -> service.adminUserGlobalSignOut(pool.getId(), "alice"));+ }++ @Test+ void adminUserGlobalSignOutThrowsForNonexistentUser() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ assertThrows(AwsException.class,+ () -> service.adminUserGlobalSignOut(pool.getId(), "ghost"));+ }+// =========================================================================// deleteUserPool cascades groups// =========================================================================