mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cognito): add group management support (#149)
* feat(cognito): add group management support * fix(cognito): handle null precedence in createGroup request * test(cognito): add tests for JWT escaping special characters in group names and user pool deletion cascading groups * feat(cognito): enhance group listing by sorting and improve group name validation * test(cognito): enhance group deletion test to verify group absence after user pool deletion * feat(cognito): update group and user models to set last modified date on changes * feat(cognito): update deleteGroup method to set last modified date for users when removing from group
This commit is contained in:
1 parent
b762becaea
commit
75bf3c3bdb
7 files changed
+780
-2
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@ApplicationScoped
|
||||
public 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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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); }
|
||||
}
|
||||
Reference in new issue
Block a user