Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): implement custom schema attributes and attribute deletion APIs (#1060)
iam-ssrivastavb5c15fdabd54
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.javaindex 982b1e7644..e0df3af33c 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java@@ -561,6 +561,9 @@ public class WebSocketHandler {String sourceIp = connectionInfo != null ? connectionInfo.getSourceIp() : "127.0.0.1";String userAgent = connectionInfo != null ? connectionInfo.getUserAgent() : "";+ // Unregister the connection IMMEDIATELY so it is gone from the maps right away+ connectionManager.unregister(connectionId);+// Look up the $disconnect routeRoute disconnectRoute = apiGatewayV2Service.findRouteByKey(region, apiId, "$disconnect");@@ -585,7 +588,6 @@ public class WebSocketHandler {} catch (AwsException e) {LOG.warnv("$disconnect integration {0} not found for connection {1}: {2}",integrationId, connectionId, e.getMessage());- connectionManager.unregister(connectionId);return;}@@ -607,12 +609,7 @@ public class WebSocketHandler {LOG.warnv("Error invoking $disconnect route for connection {0}: {1}",connectionId, ar.cause().getMessage());}- // Always unregister the connection regardless of $disconnect outcome- connectionManager.unregister(connectionId);});- } else {- // No $disconnect route — just unregister- connectionManager.unregister(connectionId);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.javaindex b4e34937de..f7a94cd3dd 100644--- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java+++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java@@ -316,6 +316,26 @@ public class CodeBuildRunner {build.setBuildComplete(true);build.setBuildStatus("FAULT");build.setCurrentPhase("COMPLETED");+ if (build.getPhases() == null) {+ build.setPhases(new ArrayList<>());+ }+ boolean hasCompleted = build.getPhases().stream()+ .anyMatch(p -> "COMPLETED".equals(p.getPhaseType()));+ if (!hasCompleted) {+ BuildPhase completedPhase = new BuildPhase();+ completedPhase.setPhaseType("COMPLETED");+ completedPhase.setPhaseStatus("FAILED");+ completedPhase.setStartTime(System.currentTimeMillis() / 1000.0);+ completedPhase.setEndTime(System.currentTimeMillis() / 1000.0);+ completedPhase.setDurationInSeconds(0L);+ if (e.getMessage() != null) {+ completedPhase.setContexts(List.of(Map.of(+ "statusCode", "FAULT_ERROR",+ "message", e.getMessage()+ )));+ }+ build.getPhases().add(completedPhase);+ }} finally {stopFlags.remove(buildId);if (containerId != null) {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 5f4c38a97b..2e4724b832 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@@ -1,6 +1,8 @@package io.github.hectorvent.floci.services.cognito;import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.AwsException;+import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;@@ -38,6 +40,7 @@ public class CognitoJsonHandler {case "DescribeUserPool" -> handleDescribeUserPool(request);case "ListUserPools" -> handleListUserPools(request);case "UpdateUserPool" -> handleUpdateUserPool(request, region);+ case "AddCustomAttributes" -> handleAddCustomAttributes(request);case "TagResource" -> handleTagResource(request);case "UntagResource" -> handleUntagResource(request);case "ListTagsForResource" -> handleListTagsForResource(request);@@ -59,6 +62,7 @@ public class CognitoJsonHandler {case "AdminDeleteUser" -> handleAdminDeleteUser(request);case "AdminSetUserPassword" -> handleAdminSetUserPassword(request);case "AdminUpdateUserAttributes" -> handleAdminUpdateUserAttributes(request);+ case "AdminDeleteUserAttributes" -> handleAdminDeleteUserAttributes(request);case "AdminUserGlobalSignOut" -> handleAdminUserGlobalSignOut(request);case "AdminEnableUser" -> handleAdminEnableUser(request);case "AdminDisableUser" -> handleAdminDisableUser(request);@@ -75,6 +79,7 @@ public class CognitoJsonHandler {case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);case "GetUser" -> handleGetUser(request);case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);+ case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);case "CreateGroup" -> handleCreateGroup(request);case "GetGroup" -> handleGetGroup(request);case "ListGroups" -> handleListGroups(request);@@ -127,6 +132,23 @@ public class CognitoJsonHandler {return Response.ok(response).build();}+ private Response handleAddCustomAttributes(JsonNode request) {+ String userPoolId = request.path("UserPoolId").asText();+ List<Map<String, Object>> customAttributes = new java.util.ArrayList<>();+ JsonNode attrsNode = request.path("CustomAttributes");+ if (attrsNode.isArray()) {+ for (JsonNode attrNode : attrsNode) {+ Map<String, Object> attr = objectMapper.convertValue(attrNode, new TypeReference<Map<String, Object>>() {});+ customAttributes.add(attr);+ }+ }+ if (customAttributes.isEmpty() || customAttributes.size() > 25) {+ throw new AwsException("InvalidParameterException", "CustomAttributes list size must be between 1 and 25.", 400);+ }+ service.addCustomAttributes(userPoolId, customAttributes);+ return Response.ok(objectMapper.createObjectNode()).build();+ }+private Response handleTagResource(JsonNode request) {@SuppressWarnings("unchecked")Map<String, String> tags = objectMapper.convertValue(request.path("Tags"), Map.class);@@ -332,6 +354,14 @@ public class CognitoJsonHandler {return Response.ok(objectMapper.createObjectNode()).build();}+ private Response handleAdminDeleteUserAttributes(JsonNode request) {+ String userPoolId = request.path("UserPoolId").asText();+ String username = request.path("Username").asText();+ List<String> attributeNames = readStringList(request.path("UserAttributeNames"));+ service.adminDeleteUserAttributes(userPoolId, username, attributeNames);+ return Response.ok(objectMapper.createObjectNode()).build();+ }+private Response handleAdminUserGlobalSignOut(JsonNode request) {service.adminUserGlobalSignOut(request.path("UserPoolId").asText(),@@ -513,6 +543,13 @@ public class CognitoJsonHandler {return Response.ok(response).build();}+ private Response handleDeleteUserAttributes(JsonNode request) {+ String accessToken = request.path("AccessToken").asText();+ List<String> attributeNames = readStringList(request.path("UserAttributeNames"));+ service.deleteUserAttributes(accessToken, attributeNames);+ 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 1a0787acba..c1c4c57857 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@@ -130,6 +130,55 @@ public class CognitoService {return pool;}+ public void addCustomAttributes(String userPoolId, List<Map<String, Object>> customAttributes) {+ UserPool pool = describeUserPool(userPoolId);+ List<Map<String, Object>> schema = pool.getSchemaAttributes();+ if (schema == null) {+ schema = new ArrayList<>();+ }+ for (Map<String, Object> attr : customAttributes) {+ attr = new HashMap<>(attr);+ String name = (String) attr.get("Name");+ if (name == null || name.isEmpty()) {+ throw new AwsException("InvalidParameterException", "Attribute name is required.", 400);+ }++ // Strip prefix to validate name length and pattern+ String strippedName = name;+ if (strippedName.startsWith("custom:")) {+ strippedName = strippedName.substring("custom:".length());+ } else if (strippedName.startsWith("dev:")) {+ strippedName = strippedName.substring("dev:".length());+ }++ if (strippedName.isEmpty() || strippedName.length() > 20) {+ throw new AwsException("InvalidParameterException", "Attribute name length must be between 1 and 20 characters.", 400);+ }++ if (!strippedName.matches("[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+")) {+ throw new AwsException("InvalidParameterException", "Attribute name contains invalid characters.", 400);+ }++ boolean developerOnly = Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"));+ String prefix = developerOnly ? "dev:" : "custom:";+ if (!name.startsWith("custom:") && !name.startsWith("dev:")) {+ attr.put("Name", prefix + name);+ }++ String finalName = (String) attr.get("Name");+ boolean exists = schema.stream().anyMatch(existing -> finalName.equals(existing.get("Name")));+ if (exists) {+ throw new AwsException("InvalidParameterException", "Attribute already exists in schema: " + finalName, 400);+ }++ schema.add(attr);+ }+ pool.setSchemaAttributes(schema);+ pool.setLastModifiedDate(System.currentTimeMillis() / 1000L);+ poolStore.put(userPoolId, pool);+ LOG.infov("Added custom attributes to User Pool: {0}", userPoolId);+ }+@SuppressWarnings("unchecked")private void populateUserPool(UserPool pool, Map<String, Object> request) {if (request.containsKey("Policies")) pool.setPolicies((Map<String, Object>) request.get("Policies"));@@ -578,6 +627,16 @@ public class CognitoService {userStore.put(userKey(userPoolId, user.getUsername()), user);}+ public void adminDeleteUserAttributes(String userPoolId, String username, List<String> attributeNames) {+ CognitoUser user = adminGetUser(userPoolId, username);+ for (String attrName : attributeNames) {+ user.getAttributes().remove(attrName);+ }+ user.setLastModifiedDate(System.currentTimeMillis() / 1000L);+ userStore.put(userKey(userPoolId, user.getUsername()), user);+ LOG.infov("Deleted attributes {0} for user {1} in pool {2}", attributeNames, username, userPoolId);+ }+public void adminEnableUser(String userPoolId, String username) {CognitoUser user = adminGetUser(userPoolId, username);user.setEnabled(true);@@ -931,6 +990,15 @@ public class CognitoService {adminUpdateUserAttributes(poolId, username, attributes);}+ public void deleteUserAttributes(String accessToken, List<String> attributeNames) {+ String username = extractUsernameFromToken(accessToken);+ String poolId = extractPoolIdFromToken(accessToken);+ if (username == null || poolId == null) {+ throw new AwsException("NotAuthorizedException", "Invalid access token", 400);+ }+ adminDeleteUserAttributes(poolId, username, attributeNames);+ }+public Map<String, Object> issueClientCredentialsToken(String clientId, String clientSecret, String scope) {UserPoolClient client = clientStore.get(clientId).orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java b/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.javaindex a240dddc9f..cc7e54f621 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServer.java@@ -133,6 +133,14 @@ public class RuntimeApiServer {ctx.response().setStatusCode(202).end();});+ long deadline = System.currentTimeMillis() + 5000;+ tryListen(started, router, deadline);++ return started;+ }++ private void tryListen(CompletableFuture<Void> started, Router router, long deadline) {+ if (started.isDone()) return;httpServer = vertx.createHttpServer(new HttpServerOptions().setMaxFormAttributeSize(-1));httpServer.requestHandler(router).listen(port, "0.0.0.0", result -> {@@ -140,12 +148,15 @@ public class RuntimeApiServer {LOG.infov("RuntimeApiServer started on port {0}", port);started.complete(null);} else {- LOG.errorv(result.cause(), "RuntimeApiServer failed to bind on port {0}", port);- started.completeExceptionally(result.cause());+ if (System.currentTimeMillis() < deadline) {+ LOG.debugv("RuntimeApiServer failed to bind on port {0}, retrying in 100ms...", port);+ httpServer.close(ar -> vertx.setTimer(100, id -> tryListen(started, router, deadline)));+ } else {+ LOG.errorv(result.cause(), "RuntimeApiServer failed to bind on port {0}", port);+ started.completeExceptionally(result.cause());+ }}});-- return started;}public synchronized CompletableFuture<Void> stop() {diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.javaindex 6dd3cb1cc9..2b2c41af8c 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java@@ -1262,6 +1262,258 @@ class CognitoIntegrationTest {resent.path("User").path("UserStatus").asText());}+ @Test+ @Order(92)+ void addCustomAttributesAndSchemaIsUpdated() throws Exception {+ JsonNode poolResponse = cognitoJson("CreateUserPool", """+ {+ "PoolName": "SchemaTestPool"+ }+ """);+ String customPoolId = poolResponse.path("UserPool").path("Id").asText();++ cognitoAction("AddCustomAttributes", """+ {+ "UserPoolId": "%s",+ "CustomAttributes": [+ {+ "Name": "location",+ "AttributeDataType": "String",+ "Mutable": true+ },+ {+ "Name": "custom:hobby",+ "AttributeDataType": "String",+ "Mutable": true+ }+ ]+ }+ """.formatted(customPoolId))+ .then()+ .statusCode(200);++ JsonNode describeResponse = cognitoJson("DescribeUserPool", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(customPoolId));++ JsonNode schema = describeResponse.path("UserPool").path("SchemaAttributes");+ assertTrue(schema.isArray());++ boolean hasLocation = false;+ boolean hasHobby = false;+ for (JsonNode attr : schema) {+ String name = attr.path("Name").asText();+ if ("custom:location".equals(name)) {+ hasLocation = true;+ } else if ("custom:hobby".equals(name)) {+ hasHobby = true;+ }+ }+ assertTrue(hasLocation, "custom:location should be in the user pool schema");+ assertTrue(hasHobby, "custom:hobby should be in the user pool schema");+ }++ @Test+ @Order(93)+ void addCustomAttributesValidationAndDeveloperPrefix() throws Exception {+ JsonNode poolResponse = cognitoJson("CreateUserPool", """+ {+ "PoolName": "SchemaValidationPool"+ }+ """);+ String poolId = poolResponse.path("UserPool").path("Id").asText();++ // 1. Happy path developer attribute+ cognitoAction("AddCustomAttributes", """+ {+ "UserPoolId": "%s",+ "CustomAttributes": [+ {+ "Name": "devattr",+ "AttributeDataType": "String",+ "DeveloperOnlyAttribute": true+ }+ ]+ }+ """.formatted(poolId))+ .then()+ .statusCode(200);++ JsonNode describeResponse = cognitoJson("DescribeUserPool", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId));++ JsonNode schema = describeResponse.path("UserPool").path("SchemaAttributes");+ boolean hasDevAttr = false;+ for (JsonNode attr : schema) {+ if ("dev:devattr".equals(attr.path("Name").asText())) {+ hasDevAttr = true;+ break;+ }+ }+ assertTrue(hasDevAttr, "dev:devattr should be in the user pool schema with dev: prefix");++ // 2. Reject duplicate attribute+ cognitoAction("AddCustomAttributes", """+ {+ "UserPoolId": "%s",+ "CustomAttributes": [+ {+ "Name": "devattr",+ "AttributeDataType": "String",+ "DeveloperOnlyAttribute": true+ }+ ]+ }+ """.formatted(poolId))+ .then()+ .statusCode(400);++ // 3. Reject name longer than 20 characters (after stripping prefix)+ cognitoAction("AddCustomAttributes", """+ {+ "UserPoolId": "%s",+ "CustomAttributes": [+ {+ "Name": "custom:thisNameIsWayTooLongForCognitoAttributeLimits",+ "AttributeDataType": "String"+ }+ ]+ }+ """.formatted(poolId))+ .then()+ .statusCode(400);++ // 4. Reject empty attributes list+ cognitoAction("AddCustomAttributes", """+ {+ "UserPoolId": "%s",+ "CustomAttributes": []+ }+ """.formatted(poolId))+ .then()+ .statusCode(400);+ }++ @Test+ @Order(94)+ void deleteUserAttributesAndVerifyDeleted() throws Exception {+ JsonNode poolResponse = cognitoJson("CreateUserPool", """+ {+ "PoolName": "DeleteAttrPool"+ }+ """);+ String delPoolId = poolResponse.path("UserPool").path("Id").asText();++ JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """+ {+ "UserPoolId": "%s",+ "ClientName": "del-client"+ }+ """.formatted(delPoolId));+ String delClientId = clientResponse.path("UserPoolClient").path("ClientId").asText();++ String delUser = "user-" + UUID.randomUUID();+ cognitoAction("AdminCreateUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "UserAttributes": [+ { "Name": "email", "Value": "[email protected]" },+ { "Name": "custom:age", "Value": "30" },+ { "Name": "custom:gender", "Value": "female" }+ ]+ }+ """.formatted(delPoolId, delUser))+ .then()+ .statusCode(200);++ cognitoAction("AdminSetUserPassword", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "Password": "Password123!",+ "Permanent": true+ }+ """.formatted(delPoolId, delUser))+ .then()+ .statusCode(200);++ // Delete custom:age via AdminDeleteUserAttributes+ cognitoAction("AdminDeleteUserAttributes", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "UserAttributeNames": [ "custom:age" ]+ }+ """.formatted(delPoolId, delUser))+ .then()+ .statusCode(200);++ JsonNode userResp = cognitoJson("AdminGetUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s"+ }+ """.formatted(delPoolId, delUser));++ boolean hasAge = false;+ boolean hasGender = false;+ for (JsonNode attr : userResp.path("UserAttributes")) {+ String name = attr.path("Name").asText();+ if ("custom:age".equals(name)) {+ hasAge = true;+ } else if ("custom:gender".equals(name)) {+ hasGender = true;+ }+ }+ assertFalse(hasAge, "custom:age should be deleted");+ assertTrue(hasGender, "custom:gender should still be present");++ // Authenticate to get access token+ JsonNode auth = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {+ "USERNAME": "%s",+ "PASSWORD": "Password123!"+ }+ }+ """.formatted(delClientId, delUser));+ String accessToken = auth.path("AuthenticationResult").path("AccessToken").asText();+ assertNotNull(accessToken);++ // Delete custom:gender via DeleteUserAttributes+ cognitoAction("DeleteUserAttributes", """+ {+ "AccessToken": "%s",+ "UserAttributeNames": [ "custom:gender" ]+ }+ """.formatted(accessToken))+ .then()+ .statusCode(200);++ // Get user using AccessToken+ JsonNode getResponse = cognitoJson("GetUser", """+ {+ "AccessToken": "%s"+ }+ """.formatted(accessToken));++ boolean hasGenderAfterDelete = false;+ for (JsonNode attr : getResponse.path("UserAttributes")) {+ if ("custom:gender".equals(attr.path("Name").asText())) {+ hasGenderAfterDelete = true;+ }+ }+ assertFalse(hasGenderAfterDelete, "custom:gender should be deleted");+ }+private static Response cognitoAction(String action, String body) {return given().header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action)diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.javaindex 6a652980b2..ec916f724d 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/runtime/RuntimeApiServerTest.java@@ -233,10 +233,19 @@ class RuntimeApiServerTest {@Timeout(10)void stopReleasesPortSynchronously() throws Exception {server.stop().get(5, TimeUnit.SECONDS);- try (ServerSocket s = new ServerSocket()) {- s.setReuseAddress(true);- s.bind(new InetSocketAddress(port));+ boolean bound = false;+ long deadline = System.currentTimeMillis() + 5000;+ while (System.currentTimeMillis() < deadline) {+ try (ServerSocket s = new ServerSocket()) {+ s.setReuseAddress(true);+ s.bind(new InetSocketAddress(port));+ bound = true;+ break;+ } catch (IOException e) {+ Thread.sleep(100);+ }}+ assertTrue(bound, "Should be able to bind to the port after stop()");}@Test@@ -244,8 +253,20 @@ class RuntimeApiServerTest {void newServerOnSamePortAcceptsTrafficAfterStop() throws Exception {server.stop().get(5, TimeUnit.SECONDS);- server = new RuntimeApiServer(vertx, port);- server.start().get(5, TimeUnit.SECONDS);+ // Try to start a new server, retrying if it fails to bind due to temporary port conflicts+ boolean started = false;+ long deadline = System.currentTimeMillis() + 5000;+ while (System.currentTimeMillis() < deadline) {+ try {+ server = new RuntimeApiServer(vertx, port);+ server.start().get(5, TimeUnit.SECONDS);+ started = true;+ break;+ } catch (Exception e) {+ Thread.sleep(100);+ }+ }+ assertTrue(started, "New server should start successfully on the same port");HttpResponse<String> resp = httpClient.send(HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/x")).GET().build(),