Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): add group management support (#149)
Ruan Leite75bf3c3bdbe2
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 827769e432..7b114bbcc8 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -16,6 +16,7 @@ Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth to| **User Operations** | SignUp, ConfirmSignUp, GetUser, UpdateUserAttributes, ChangePassword, ForgotPassword, ConfirmForgotPassword || **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge || **User Listing** | ListUsers |+| **Groups** | CreateGroup, GetGroup, ListGroups, DeleteGroup, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser |## Well-Known And OAuth Endpoints@@ -95,6 +96,26 @@ aws cognito-idp initiate-auth \--auth-parameters [email protected],PASSWORD=Perm1234! \--endpoint-url $AWS_ENDPOINT+# Create a group+aws cognito-idp create-group \+ --user-pool-id $POOL_ID \+ --group-name admin \+ --description "Admin group" \+ --endpoint-url $AWS_ENDPOINT++# Add user to group+aws cognito-idp admin-add-user-to-group \+ --user-pool-id $POOL_ID \+ --group-name admin \+ --username [email protected] \+ --endpoint-url $AWS_ENDPOINT++# List groups for user+aws cognito-idp admin-list-groups-for-user \+ --user-pool-id $POOL_ID \+ --username [email protected] \+ --endpoint-url $AWS_ENDPOINT+# Fetch the pool discovery documentcurl -s "$AWS_ENDPOINT/$POOL_ID/.well-known/openid-configuration"@@ -119,6 +140,8 @@ http://localhost:4566/$POOL_ID/.well-known/openid-configurationhttp://localhost:4566/$POOL_ID/.well-known/jwks.json```+Tokens include the `cognito:groups` claim as a JSON array when the authenticated user belongs to one or more groups.+Tokens issued by Cognito auth flows and the OAuth token endpoint use the emulator base URL plus the pool id:```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 abbc5aa483..0af2ca2312 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@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;import io.github.hectorvent.floci.services.cognito.model.CognitoUser;import io.github.hectorvent.floci.services.cognito.model.ResourceServer;import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;@@ -61,6 +62,13 @@ public class CognitoJsonHandler {case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);case "GetUser" -> handleGetUser(request);case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);+ case "CreateGroup" -> handleCreateGroup(request);+ case "GetGroup" -> handleGetGroup(request);+ case "ListGroups" -> handleListGroups(request);+ case "DeleteGroup" -> handleDeleteGroup(request);+ case "AdminAddUserToGroup" -> handleAdminAddUserToGroup(request);+ case "AdminRemoveUserFromGroup" -> handleAdminRemoveUserFromGroup(request);+ case "AdminListGroupsForUser" -> handleAdminListGroupsForUser(request);default -> Response.status(400).entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported.")).build();@@ -455,4 +463,79 @@ public class CognitoJsonHandler {return node;}+ private Response handleCreateGroup(JsonNode request) {+ String userPoolId = request.path("UserPoolId").asText();+ String groupName = request.path("GroupName").asText();+ String description = request.path("Description").asText(null);+ JsonNode precNode = request.path("Precedence");+ Integer precedence = precNode.isMissingNode() || precNode.isNull() ? null : precNode.asInt();+ String roleArn = request.path("RoleArn").asText(null);+ CognitoGroup group = service.createGroup(userPoolId, groupName, description, precedence, roleArn);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Group", groupToNode(group));+ return Response.ok(response).build();+ }++ private Response handleGetGroup(JsonNode request) {+ CognitoGroup group = service.getGroup(+ request.path("UserPoolId").asText(),+ request.path("GroupName").asText());+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Group", groupToNode(group));+ return Response.ok(response).build();+ }++ private Response handleListGroups(JsonNode request) {+ List<CognitoGroup> groups = service.listGroups(request.path("UserPoolId").asText());+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode items = response.putArray("Groups");+ groups.forEach(g -> items.add(groupToNode(g)));+ return Response.ok(response).build();+ }++ private Response handleDeleteGroup(JsonNode request) {+ service.deleteGroup(+ request.path("UserPoolId").asText(),+ request.path("GroupName").asText());+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleAdminAddUserToGroup(JsonNode request) {+ service.adminAddUserToGroup(+ request.path("UserPoolId").asText(),+ request.path("GroupName").asText(),+ request.path("Username").asText());+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleAdminRemoveUserFromGroup(JsonNode request) {+ service.adminRemoveUserFromGroup(+ request.path("UserPoolId").asText(),+ request.path("GroupName").asText(),+ request.path("Username").asText());+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleAdminListGroupsForUser(JsonNode request) {+ List<CognitoGroup> groups = service.adminListGroupsForUser(+ request.path("UserPoolId").asText(),+ request.path("Username").asText());+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode items = response.putArray("Groups");+ groups.forEach(g -> items.add(groupToNode(g)));+ return Response.ok(response).build();+ }++ private ObjectNode groupToNode(CognitoGroup g) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("GroupName", g.getGroupName());+ node.put("UserPoolId", g.getUserPoolId());+ if (g.getDescription() != null) node.put("Description", g.getDescription());+ if (g.getPrecedence() != null) node.put("Precedence", g.getPrecedence());+ if (g.getRoleArn() != null) node.put("RoleArn", g.getRoleArn());+ node.put("CreationDate", g.getCreationDate());+ node.put("LastModifiedDate", g.getLastModifiedDate());+ return node;+ }+}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 21a3e07ce1..f7364cf1ef 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@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;import io.github.hectorvent.floci.services.cognito.model.CognitoUser;import io.github.hectorvent.floci.services.cognito.model.ResourceServer;import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;@@ -26,6 +27,7 @@ import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.*;+import java.util.stream.Collectors;@ApplicationScopedpublic class CognitoService {@@ -36,6 +38,7 @@ public class CognitoService {private final StorageBackend<String, UserPoolClient> clientStore;private final StorageBackend<String, ResourceServer> resourceServerStore;private final StorageBackend<String, CognitoUser> userStore;+ private final StorageBackend<String, CognitoGroup> groupStore;private final String baseUrl;@Inject@@ -48,9 +51,25 @@ public class CognitoService {new TypeReference<Map<String, ResourceServer>>() {});this.userStore = storageFactory.create("cognito", "cognito-users.json",new TypeReference<Map<String, CognitoUser>>() {});+ this.groupStore = storageFactory.create("cognito", "cognito-groups.json",+ new TypeReference<Map<String, CognitoGroup>>() {});this.baseUrl = trimTrailingSlash(emulatorConfig.baseUrl());}+ CognitoService(StorageBackend<String, UserPool> poolStore,+ StorageBackend<String, UserPoolClient> clientStore,+ StorageBackend<String, ResourceServer> resourceServerStore,+ StorageBackend<String, CognitoUser> userStore,+ StorageBackend<String, CognitoGroup> groupStore,+ String baseUrl) {+ this.poolStore = poolStore;+ this.clientStore = clientStore;+ this.resourceServerStore = resourceServerStore;+ this.userStore = userStore;+ this.groupStore = groupStore;+ this.baseUrl = baseUrl;+ }+// ──────────────────────────── User Pools ────────────────────────────public UserPool createUserPool(String name, String region) {@@ -78,6 +97,9 @@ public class CognitoService {}public void deleteUserPool(String id) {+ String prefix = id + "::";+ groupStore.scan(k -> k.startsWith(prefix))+ .forEach(g -> groupStore.delete(groupKey(id, g.getGroupName())));poolStore.delete(id);}@@ -220,6 +242,14 @@ public class CognitoService {}public void adminDeleteUser(String userPoolId, String username) {+ CognitoUser user = adminGetUser(userPoolId, username);+ for (String groupName : new ArrayList<>(user.getGroupNames())) {+ groupStore.get(groupKey(userPoolId, groupName)).ifPresent(group -> {+ group.removeUserName(username);+ group.setLastModifiedDate(System.currentTimeMillis() / 1000L);+ groupStore.put(groupKey(userPoolId, groupName), group);+ });+ }userStore.delete(userKey(userPoolId, username));}@@ -245,6 +275,95 @@ public class CognitoService {return userStore.scan(k -> k.startsWith(prefix));}+ // ──────────────────────────── Groups ────────────────────────────++ public CognitoGroup createGroup(String userPoolId, String groupName, String description,+ Integer precedence, String roleArn) {+ describeUserPool(userPoolId);+ validateGroupName(groupName);+ if (groupStore.get(groupKey(userPoolId, groupName)).isPresent()) {+ throw new AwsException("GroupExistsException",+ "A group with the name " + groupName + " already exists.", 400);+ }+ CognitoGroup group = new CognitoGroup();+ group.setGroupName(groupName);+ group.setUserPoolId(userPoolId);+ group.setDescription(description);+ group.setPrecedence(precedence);+ group.setRoleArn(roleArn);+ groupStore.put(groupKey(userPoolId, groupName), group);+ LOG.infov("Created Cognito group: {0} in pool {1}", groupName, userPoolId);+ return group;+ }++ public CognitoGroup getGroup(String userPoolId, String groupName) {+ describeUserPool(userPoolId);+ validateGroupName(groupName);+ return groupStore.get(groupKey(userPoolId, groupName))+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Group not found: " + groupName, 404));+ }++ public List<CognitoGroup> listGroups(String userPoolId) {+ describeUserPool(userPoolId);+ String prefix = userPoolId + "::";+ List<CognitoGroup> groups = new ArrayList<>(groupStore.scan(k -> k.startsWith(prefix)));+ groups.sort(Comparator.comparing(CognitoGroup::getGroupName));+ return groups;+ }++ public void deleteGroup(String userPoolId, String groupName) {+ CognitoGroup group = getGroup(userPoolId, groupName);+ long now = System.currentTimeMillis() / 1000L;+ for (String username : new ArrayList<>(group.getUserNames())) {+ userStore.get(userKey(userPoolId, username)).ifPresent(user -> {+ if (user.getGroupNames().remove(groupName)) {+ user.setLastModifiedDate(now);+ userStore.put(userKey(userPoolId, username), user);+ }+ });+ }+ groupStore.delete(groupKey(userPoolId, groupName));+ LOG.infov("Deleted Cognito group: {0} from pool {1}", groupName, userPoolId);+ }++ public void adminAddUserToGroup(String userPoolId, String groupName, String username) {+ CognitoGroup group = getGroup(userPoolId, groupName);+ CognitoUser user = adminGetUser(userPoolId, username);+ long now = System.currentTimeMillis() / 1000L;+ if (group.addUserName(username)) {+ group.setLastModifiedDate(now);+ groupStore.put(groupKey(userPoolId, groupName), group);+ }+ if (!user.getGroupNames().contains(groupName)) {+ user.getGroupNames().add(groupName);+ user.setLastModifiedDate(now);+ userStore.put(userKey(userPoolId, username), user);+ }+ }++ public void adminRemoveUserFromGroup(String userPoolId, String groupName, String username) {+ CognitoGroup group = getGroup(userPoolId, groupName);+ CognitoUser user = adminGetUser(userPoolId, username);+ long now = System.currentTimeMillis() / 1000L;+ if (group.removeUserName(username)) {+ group.setLastModifiedDate(now);+ groupStore.put(groupKey(userPoolId, groupName), group);+ }+ if (user.getGroupNames().remove(groupName)) {+ user.setLastModifiedDate(now);+ userStore.put(userKey(userPoolId, username), user);+ }+ }++ public List<CognitoGroup> adminListGroupsForUser(String userPoolId, String username) {+ describeUserPool(userPoolId);+ CognitoUser user = adminGetUser(userPoolId, username);+ return user.getGroupNames().stream()+ .flatMap(gn -> groupStore.get(groupKey(userPoolId, gn)).stream())+ .toList();+ }+// ──────────────────────────── Self-Service Registration ────────────────────────────public CognitoUser signUp(String clientId, String username, String password, Map<String, String> attributes) {@@ -513,13 +632,20 @@ public class CognitoService {long now = System.currentTimeMillis() / 1000L;String email = user.getAttributes().getOrDefault("email", user.getUsername());+ String groupsFragment = "";+ if (!user.getGroupNames().isEmpty()) {+ String groupsJson = user.getGroupNames().stream()+ .map(g -> "\"" + escapeJsonString(g) + "\"")+ .collect(Collectors.joining(",", "[", "]"));+ groupsFragment = ",\"cognito:groups\":" + groupsJson;+ }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\"}",+ "\"username\":\"%s\",\"email\":\"%s\",\"cognito:username\":\"%s\"%s}",UUID.randomUUID(), UUID.randomUUID(), type, now,escapeJson(getIssuer(pool.getId())), now + 3600, now,- user.getUsername(), email, user.getUsername()+ user.getUsername(), email, user.getUsername(), groupsFragment);String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));@@ -819,6 +945,35 @@ public class CognitoService {}}+ private void validateGroupName(String groupName) {+ if (groupName == null || groupName.isBlank()) {+ throw new AwsException("InvalidParameterException", "GroupName is required", 400);+ }+ }++ private String escapeJsonString(String s) {+ StringBuilder sb = new StringBuilder();+ for (char c : s.toCharArray()) {+ switch (c) {+ case '"' -> sb.append("\\\"");+ case '\\' -> sb.append("\\\\");+ case '\b' -> sb.append("\\b");+ case '\f' -> sb.append("\\f");+ case '\n' -> sb.append("\\n");+ case '\r' -> sb.append("\\r");+ case '\t' -> sb.append("\\t");+ default -> {+ if (c < 0x20) {+ sb.append(String.format("\\u%04x", (int) c));+ } else {+ sb.append(c);+ }+ }+ }+ }+ return sb.toString();+ }+private String extractJsonField(String json, String field) {String search = "\"" + field + "\":\"";int start = json.indexOf(search);@@ -833,6 +988,10 @@ public class CognitoService {return poolId + "::" + username;}+ private String groupKey(String poolId, String groupName) {+ return poolId + "::" + groupName;+ }+private String resourceServerKey(String userPoolId, String identifier) {return userPoolId + "::" + identifier;}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoGroup.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoGroup.javanew file mode 100644index 0000000000..6992c37f1d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoGroup.java@@ -0,0 +1,61 @@+package io.github.hectorvent.floci.services.cognito.model;++import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class CognitoGroup {+ private String groupName;+ private String userPoolId;+ private String description;+ private Integer precedence;+ private String roleArn;+ private long creationDate;+ private long lastModifiedDate;+ private List<String> userNames;++ public CognitoGroup() {+ long now = System.currentTimeMillis() / 1000L;+ this.creationDate = now;+ this.lastModifiedDate = now;+ this.userNames = new ArrayList<>();+ }++ public String getGroupName() { return groupName; }+ public void setGroupName(String groupName) { this.groupName = groupName; }++ public String getUserPoolId() { return userPoolId; }+ public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public Integer getPrecedence() { return precedence; }+ public void setPrecedence(Integer precedence) { this.precedence = precedence; }++ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }++ public long getCreationDate() { return creationDate; }+ public void setCreationDate(long creationDate) { this.creationDate = creationDate; }++ public long getLastModifiedDate() { return lastModifiedDate; }+ public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }++ public List<String> getUserNames() { return Collections.unmodifiableList(userNames); }+ public void setUserNames(List<String> userNames) { this.userNames = userNames == null ? new ArrayList<>() : new ArrayList<>(userNames); }++ public boolean addUserName(String name) {+ if (userNames.contains(name)) return false;+ return userNames.add(name);+ }++ public boolean removeUserName(String name) {+ return userNames.remove(name);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.javaindex 73b0ecd0a4..3506dc2385 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.cognito.model;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.ArrayList;import java.util.HashMap;+import java.util.List;import java.util.Map;@RegisterForReflection@@ -18,6 +20,7 @@ public class CognitoUser {private long lastModifiedDate;private String passwordHash;private boolean temporaryPassword;+ private List<String> groupNames = new ArrayList<>();public CognitoUser() {long now = System.currentTimeMillis() / 1000L;@@ -53,4 +56,7 @@ public class CognitoUser {public boolean isTemporaryPassword() { return temporaryPassword; }public void setTemporaryPassword(boolean temporaryPassword) { this.temporaryPassword = temporaryPassword; }++ public List<String> getGroupNames() { return groupNames; }+ public void setGroupNames(List<String> groupNames) { this.groupNames = groupNames == null ? new ArrayList<>() : new ArrayList<>(groupNames); }}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 53f8ce590a..51c063ea63 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@@ -173,6 +173,170 @@ class CognitoIntegrationTest {assertEquals("RS256", document.path("id_token_signing_alg_values_supported").get(0).asText());}+ // ── Groups ────────────────────────────────────────────────────────++ @Test+ @Order(10)+ void createGroup() throws Exception {+ JsonNode resp = cognitoJson("CreateGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin",+ "Description": "Admin group",+ "Precedence": 1+ }+ """.formatted(poolId));+ assertEquals("admin", resp.path("Group").path("GroupName").asText());+ assertEquals(poolId, resp.path("Group").path("UserPoolId").asText());+ assertEquals("Admin group", resp.path("Group").path("Description").asText());+ assertEquals(1, resp.path("Group").path("Precedence").asInt());+ }++ @Test+ @Order(11)+ void createGroupDuplicate() {+ cognitoAction("CreateGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin",+ "Description": "Admin group",+ "Precedence": 1+ }+ """.formatted(poolId))+ .then()+ .statusCode(400);+ }++ @Test+ @Order(12)+ void getGroup() throws Exception {+ JsonNode resp = cognitoJson("GetGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin"+ }+ """.formatted(poolId));+ assertEquals("admin", resp.path("Group").path("GroupName").asText());+ }++ @Test+ @Order(13)+ void listGroups() throws Exception {+ JsonNode resp = cognitoJson("ListGroups", """+ {+ "UserPoolId": "%s"+ }+ """.formatted(poolId));+ assertEquals(1, resp.path("Groups").size());+ assertEquals("admin", resp.path("Groups").get(0).path("GroupName").asText());+ }++ @Test+ @Order(14)+ void adminAddUserToGroup() {+ cognitoAction("AdminAddUserToGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin",+ "Username": "%s"+ }+ """.formatted(poolId, username))+ .then()+ .statusCode(200);+ }++ @Test+ @Order(15)+ void adminListGroupsForUser() throws Exception {+ JsonNode resp = cognitoJson("AdminListGroupsForUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s"+ }+ """.formatted(poolId, username));+ assertEquals(1, resp.path("Groups").size());+ assertEquals("admin", resp.path("Groups").get(0).path("GroupName").asText());+ }++ @Test+ @Order(16)+ void authenticateAndVerifyGroupsInToken() throws Exception {+ Response authResponse = cognitoAction("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {+ "USERNAME": "%s",+ "PASSWORD": "%s"+ }+ }+ """.formatted(clientId, username, password));++ authResponse.then().statusCode(200);++ String accessToken = authResponse.jsonPath().getString("AuthenticationResult.AccessToken");+ JsonNode payload = decodeJwtPayload(accessToken);++ assertTrue(payload.has("cognito:groups"),+ "JWT payload should contain cognito:groups claim");+ assertTrue(payload.path("cognito:groups").toString().contains("\"admin\""),+ "JWT payload should contain admin group");+ }++ @Test+ @Order(17)+ void adminRemoveUserFromGroup() {+ cognitoAction("AdminRemoveUserFromGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin",+ "Username": "%s"+ }+ """.formatted(poolId, username))+ .then()+ .statusCode(200);+ }++ @Test+ @Order(18)+ void adminListGroupsForUserEmpty() throws Exception {+ JsonNode resp = cognitoJson("AdminListGroupsForUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s"+ }+ """.formatted(poolId, username));+ assertEquals(0, resp.path("Groups").size());+ }++ @Test+ @Order(19)+ void deleteGroup() {+ cognitoAction("DeleteGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin"+ }+ """.formatted(poolId))+ .then()+ .statusCode(200);+ }++ @Test+ @Order(20)+ void getGroupNotFound() {+ cognitoAction("GetGroup", """+ {+ "UserPoolId": "%s",+ "GroupName": "admin"+ }+ """.formatted(poolId))+ .then()+ .statusCode(404);+ }++ // ── Helpers ───────────────────────────────────────────────────────+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/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javanew file mode 100644index 0000000000..3f89404a5d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -0,0 +1,282 @@+package io.github.hectorvent.floci.services.cognito;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;+import io.github.hectorvent.floci.services.cognito.model.UserPool;+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.nio.charset.StandardCharsets;+import java.util.Base64;+import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.*;++class CognitoServiceTest {++ private CognitoService service;+ private InMemoryStorage<String, CognitoGroup> groupStore;++ @BeforeEach+ void setUp() {+ groupStore = new InMemoryStorage<>();+ service = new CognitoService(+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ groupStore,+ "http://localhost:4566"+ );+ }++ private UserPool createPoolAndUser() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), "TempPass1!");+ service.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);+ return pool;+ }++ // =========================================================================+ // Groups+ // =========================================================================++ @Test+ void createGroup() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ CognitoGroup group = service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ assertEquals("admins", group.getGroupName());+ assertEquals(pool.getId(), group.getUserPoolId());+ assertEquals("Admin group", group.getDescription());+ assertEquals(1, group.getPrecedence());+ assertNull(group.getRoleArn());+ assertTrue(group.getCreationDate() > 0);+ assertTrue(group.getLastModifiedDate() > 0);+ }++ @Test+ void createGroupDuplicateThrows() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ assertThrows(AwsException.class, () ->+ service.createGroup(pool.getId(), "admins", "Another desc", 2, null));+ }++ @Test+ void getGroup() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ CognitoGroup fetched = service.getGroup(pool.getId(), "admins");+ assertEquals("admins", fetched.getGroupName());+ assertEquals(pool.getId(), fetched.getUserPoolId());+ assertEquals("Admin group", fetched.getDescription());+ assertEquals(1, fetched.getPrecedence());+ }++ @Test+ void getGroupNotFoundThrows() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");++ assertThrows(AwsException.class, () ->+ service.getGroup(pool.getId(), "nonexistent"));+ }++ @Test+ void listGroups() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.createGroup(pool.getId(), "editors", "Editor group", 2, null);++ List<CognitoGroup> groups = service.listGroups(pool.getId());+ assertEquals(2, groups.size());+ }++ @Test+ void deleteGroup() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ service.deleteGroup(pool.getId(), "admins");++ assertThrows(AwsException.class, () ->+ service.getGroup(pool.getId(), "admins"));+ }++ @Test+ void deleteGroupCleansUpUserMembership() {+ UserPool pool = createPoolAndUser();+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.adminAddUserToGroup(pool.getId(), "admins", "alice");++ service.deleteGroup(pool.getId(), "admins");++ CognitoUser user = service.adminGetUser(pool.getId(), "alice");+ assertTrue(user.getGroupNames().isEmpty());+ }++ @Test+ void adminDeleteUserCleansUpGroupMembership() {+ UserPool pool = createPoolAndUser();+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.adminAddUserToGroup(pool.getId(), "admins", "alice");++ service.adminDeleteUser(pool.getId(), "alice");++ CognitoGroup group = service.getGroup(pool.getId(), "admins");+ assertFalse(group.getUserNames().contains("alice"));+ }++ // =========================================================================+ // Group membership+ // =========================================================================++ @Test+ void adminAddUserToGroup() {+ UserPool pool = createPoolAndUser();+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ service.adminAddUserToGroup(pool.getId(), "admins", "alice");++ CognitoGroup group = service.getGroup(pool.getId(), "admins");+ assertTrue(group.getUserNames().contains("alice"));++ CognitoUser user = service.adminGetUser(pool.getId(), "alice");+ assertTrue(user.getGroupNames().contains("admins"));+ }++ @Test+ void adminAddUserToGroupIdempotent() {+ UserPool pool = createPoolAndUser();+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ service.adminAddUserToGroup(pool.getId(), "admins", "alice");+ service.adminAddUserToGroup(pool.getId(), "admins", "alice");++ CognitoGroup group = service.getGroup(pool.getId(), "admins");+ assertEquals(1, group.getUserNames().size());+ }++ @Test+ void adminRemoveUserFromGroup() {+ UserPool pool = createPoolAndUser();+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.adminAddUserToGroup(pool.getId(), "admins", "alice");++ service.adminRemoveUserFromGroup(pool.getId(), "admins", "alice");++ CognitoGroup group = service.getGroup(pool.getId(), "admins");+ assertFalse(group.getUserNames().contains("alice"));++ CognitoUser user = service.adminGetUser(pool.getId(), "alice");+ assertFalse(user.getGroupNames().contains("admins"));+ }++ @Test+ void adminListGroupsForUser() {+ UserPool pool = createPoolAndUser();+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.createGroup(pool.getId(), "editors", "Editor group", 2, null);+ service.adminAddUserToGroup(pool.getId(), "admins", "alice");+ service.adminAddUserToGroup(pool.getId(), "editors", "alice");++ List<CognitoGroup> groups = service.adminListGroupsForUser(pool.getId(), "alice");+ assertEquals(2, groups.size());+ }++ @Test+ void adminAddUserToGroupNonexistentGroupThrows() {+ UserPool pool = createPoolAndUser();++ assertThrows(AwsException.class, () ->+ service.adminAddUserToGroup(pool.getId(), "nonexistent", "alice"));+ }++ @Test+ void adminAddUserToGroupNonexistentUserThrows() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);++ assertThrows(AwsException.class, () ->+ service.adminAddUserToGroup(pool.getId(), "admins", "nonexistent"));+ }++ // =========================================================================+ // JWT groups claim+ // =========================================================================++ @Test+ @SuppressWarnings("unchecked")+ void jwtContainsGroupsClaim() {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "test-client", false, false, List.of(), List.of());+ String clientId = client.getClientId();++ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.adminAddUserToGroup(pool.getId(), "admins", "alice");++ Map<String, Object> authResult = service.initiateAuth(+ clientId, "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));++ Map<String, Object> authenticationResult = (Map<String, Object>) authResult.get("AuthenticationResult");+ String accessToken = (String) authenticationResult.get("AccessToken");++ // Decode the JWT payload (second segment)+ String[] parts = accessToken.split("\\.");+ String payloadJson = new String(+ Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);++ assertTrue(payloadJson.contains("\"cognito:groups\":[\"admins\"]"),+ "JWT payload should contain cognito:groups claim with the group name");+ }++ @Test+ @SuppressWarnings("unchecked")+ void jwtEscapesSpecialCharsInGroupName() {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "test-client", false, false, List.of(), List.of());++ String specialGroup = "group\"with\\special\nchars";+ service.createGroup(pool.getId(), specialGroup, null, null, null);+ service.adminAddUserToGroup(pool.getId(), specialGroup, "alice");++ 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("cognito:groups"),+ "JWT should contain cognito:groups claim");+ assertTrue(payloadJson.contains("group\\\"with\\\\special\\nchars"),+ "Group name should be properly JSON-escaped in JWT payload");+ }++ // =========================================================================+ // deleteUserPool cascades groups+ // =========================================================================++ @Test+ void deleteUserPoolCascadesGroups() {+ UserPool pool = service.createUserPool("TestPool", "us-east-1");+ service.createGroup(pool.getId(), "admins", "Admin group", 1, null);+ service.createGroup(pool.getId(), "editors", "Editor group", 2, null);++ String prefix = pool.getId() + "::";+ assertEquals(2, groupStore.scan(k -> k.startsWith(prefix)).size());++ service.deleteUserPool(pool.getId());++ assertEquals(0, groupStore.scan(k -> k.startsWith(prefix)).size());+ }+}