mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(cognito): implement custom schema attributes and attribute deletion APIs (#1060)
* feat(cognito): implement custom schema attributes and attribute deletion APIs * test(lambda): resolve flaky port bind error in RuntimeApiServerTest * test(ec2): isolate Ec2NetworkInterfacePaginationTest by filtering by subnet-id * fix: resolve flaky integration tests and robustify runtime binding & codebuild diagnostics * fix: unregister websocket connection immediately on close to prevent postToConnection race conditions * feat(cognito): implement AddCustomAttributes validations, developer prefixing, name checks, and fix RuntimeApiServer retry race condition
This commit is contained in:
1 parent
f191982f25
commit
b5c15fdabd
7 files changed
+421
-15
No files matched your search
+3
-6
@@ -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 route
|
||||
Route 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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));
|
||||
|
||||
+15
-4
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user