From b9ddb8ee5d015cc3405490debbc9da43482cba83 Mon Sep 17 00:00:00 2001 From: Daniel Abeledo Date: Wed, 15 Apr 2026 05:11:58 +0100 Subject: [PATCH] feat(cognito-idp): adding create/list/delete user pool client secret cognito-idp actions (#345) * feat: add Cognito IDP list/add/delete user pool client secrets functionality * feat: add Cognito IDP list/add/delete user pool client secrets functionality - addressing comments * feat: add Cognito IDP list/add/delete user pool client secrets functionality - addressing comments --- .../services/cognito/CognitoJsonHandler.java | 52 ++++ .../services/cognito/CognitoService.java | 111 ++++++-- .../cognito/model/UserPoolClient.java | 8 + .../cognito/model/UserPoolClientSecret.java | 44 ++++ .../cognito/CognitoIntegrationTest.java | 242 ++++++++++++++++++ 5 files changed, 438 insertions(+), 19 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClientSecret.java 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.java index deceb446f7..231e5c812f 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 @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.cognito.model.ResourceServer; import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; @@ -73,6 +74,9 @@ public class CognitoJsonHandler { case "AdminRemoveUserFromGroup" -> handleAdminRemoveUserFromGroup(request); case "AdminListGroupsForUser" -> handleAdminListGroupsForUser(request); case "GetTokensFromRefreshToken" -> handleGetTokensFromRefreshToken(request); + case "ListUserPoolClientSecrets" -> handleListUserPoolClientSecrets(request); + case "AddUserPoolClientSecret" -> handleAddUserPoolClientSecret(request); + case "DeleteUserPoolClientSecret" -> handleDeleteUserPoolClientSecret(request); default -> Response.status(400) .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported.")) .build(); @@ -626,4 +630,52 @@ public class CognitoJsonHandler { return node; } + private Response handleListUserPoolClientSecrets(JsonNode request) { + List clientSecrets = + service.listUserPoolClientSecrets( + request.path("UserPoolId").asText(), + request.path("ClientId").asText() + ); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode items = response.putArray("ClientSecrets"); + clientSecrets.forEach(cs -> items.add(clientSecretToNode(cs, false))); + return Response.ok(response).build(); + } + + private Response handleAddUserPoolClientSecret(JsonNode request) { + String clientId = request.path("ClientId").asText(); + String clientSecret = request.path("ClientSecret").asText(null); + String userPoolId = request.path("UserPoolId").asText(); + + UserPoolClientSecret cs = service.addUserPoolClientSecret( + clientId, clientSecret, userPoolId + ); + + boolean includeClientSecretValue = clientSecret == null; + ObjectNode wrapper = objectMapper.createObjectNode(); + wrapper.set("ClientSecretDescriptor", clientSecretToNode(cs, includeClientSecretValue)); + return Response.ok(wrapper).build(); + } + + private Response handleDeleteUserPoolClientSecret(JsonNode request) { + String clientId = request.path("ClientId").asText(); + String clientSecretId = request.path("ClientSecretId").asText(); + String userPoolId = request.path("UserPoolId").asText(); + + service.deleteUserPoolClientSecret(clientId, clientSecretId, userPoolId); + + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private ObjectNode clientSecretToNode(UserPoolClientSecret cs, + boolean includeClientSecretValue) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("ClientSecretId", cs.getClientSecretId()); + if (includeClientSecretValue) { + node.put("ClientSecretValue", cs.getClientSecretValue()); + } + node.put("ClientSecretCreateDate", cs.getClientSecretCreateDate()); + 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.java index ebe6d529af..a8fa8646d9 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 @@ -1,34 +1,24 @@ package io.github.hectorvent.floci.services.cognito; -import io.github.hectorvent.floci.core.common.AwsException; +import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; 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; -import io.github.hectorvent.floci.services.cognito.model.UserPool; -import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; +import io.github.hectorvent.floci.services.cognito.model.*; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.nio.charset.StandardCharsets; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; +import java.security.*; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; import java.util.stream.Collectors; @ApplicationScoped @@ -177,7 +167,17 @@ public class CognitoService { client.setAllowedOAuthFlows(normalizeStringList(allowedOAuthFlows)); client.setAllowedOAuthScopes(normalizeStringList(allowedOAuthScopes)); if (generateSecret) { - client.setClientSecret(generateSecretValue()); + String clientSecret = generateSecretValue(); + client.setClientSecret(clientSecret); + + long epochMillis = System.currentTimeMillis(); + UserPoolClientSecret userPoolClientSecret = new UserPoolClientSecret( + clientId + "--" + epochMillis, + epochMillis / 1000, + clientSecret + ); + + client.getUserPoolClientSecrets().add(userPoolClientSecret); } clientStore.put(clientId, client); LOG.infov("Created User Pool Client: {0} for pool {1}", clientId, userPoolId); @@ -202,6 +202,71 @@ public class CognitoService { clientStore.delete(clientId); } + public List listUserPoolClientSecrets(String userPoolId, String clientId) { + UserPoolClient client = clientStore.get(clientId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404)); + if (!client.getUserPoolId().equals(userPoolId)) { + throw new AwsException("ResourceNotFoundException", "User pool client not found", 404); + } + return client.getUserPoolClientSecrets(); + } + + public UserPoolClientSecret addUserPoolClientSecret(String clientId, String clientSecret, String userPoolId) { + UserPoolClient client = clientStore.get(clientId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404)); + if (!client.getUserPoolId().equals(userPoolId)) { + throw new AwsException("ResourceNotFoundException", "User pool client not found", 404); + } + + if (client.getUserPoolClientSecrets().size() >= 2) { + throw new AwsException("LimitExceededException", "Client secrets cannot exceed limit of 2 secrets.", 400); + } + + if (clientSecret == null) { + clientSecret = generateSecretValue(); + } else if (!clientSecret.matches("\\w{24,64}")) { + throw new AwsException("InvalidParameterException", + "Client secret format is invalid.", 400); + } + long epochMillis = System.currentTimeMillis(); + UserPoolClientSecret userPoolClientSecret = new UserPoolClientSecret( + clientId + "--" + epochMillis, + epochMillis / 1000, + clientSecret + ); + + client.getUserPoolClientSecrets().add(userPoolClientSecret); + + return userPoolClientSecret; + } + + public void deleteUserPoolClientSecret(String clientId, String clientSecretId, String userPoolId) { + UserPoolClient client = clientStore.get(clientId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404)); + if (!client.getUserPoolId().equals(userPoolId)) { + throw new AwsException("ResourceNotFoundException", "User pool client not found", 404); + } + + UserPoolClientSecret userPoolClientSecret = client.getUserPoolClientSecrets().stream() + .filter(s -> s.getClientSecretId().equals(clientSecretId)) + .findFirst() + .orElseThrow(() -> new AwsException( + "ResourceNotFoundException", "Client secret does not exist", 404)); + + if (client.getUserPoolClientSecrets().size() <= 1) { + throw new AwsException( + "InvalidParameterException", "Cannot delete the only " + + "client secret.", 400 + ); + } + + if (userPoolClientSecret.getClientSecretValue().equals(client.getClientSecret())) { + client.setClientSecret(null); + } + + client.getUserPoolClientSecrets().remove(userPoolClientSecret); + } + // ──────────────────────────── Resource Servers ──────────────────────────── public ResourceServer createResourceServer(String userPoolId, String identifier, String name, @@ -967,15 +1032,23 @@ public class CognitoService { private void validateClientSecret(UserPoolClient client, String clientSecret) { String expectedSecret = client.getClientSecret(); - if (expectedSecret == null || expectedSecret.isBlank() || !client.isGenerateSecret()) { + if (client.getUserPoolClientSecrets().isEmpty() + && (expectedSecret == null || expectedSecret.isBlank() || !client.isGenerateSecret())) { throw new AwsException("InvalidClientException", "Client must have a secret for client_credentials", 400); } if (clientSecret == null || clientSecret.isBlank()) { throw new AwsException("InvalidClientException", "Client secret is required", 400); } - if (!expectedSecret.equals(clientSecret)) { - throw new AwsException("InvalidClientException", "Client secret is invalid", 400); + for (UserPoolClientSecret userPoolClientSecret : client.getUserPoolClientSecrets()) { + if (clientSecret.equals(userPoolClientSecret.getClientSecretValue())) { + return; + } } + // for "legacy" clients + if (expectedSecret != null && expectedSecret.equals(clientSecret)) { + return; + } + throw new AwsException("InvalidClientException", "Client secret is invalid", 400); } private void validateClientAllowsClientCredentials(UserPoolClient client) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java index dee2bf8883..271f3c1d52 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java @@ -13,6 +13,7 @@ public class UserPoolClient { private String userPoolId; private String clientName; private String clientSecret; + private List userPoolClientSecrets = new ArrayList<>(); private boolean generateSecret; private boolean allowedOAuthFlowsUserPoolClient; private List allowedOAuthFlows = new ArrayList<>(); @@ -38,6 +39,13 @@ public class UserPoolClient { public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } + public List getUserPoolClientSecrets() { + return userPoolClientSecrets; + } + public void setUserPoolClientSecrets(List userPoolClientSecrets) { + this.userPoolClientSecrets = userPoolClientSecrets; + } + public boolean isGenerateSecret() { return generateSecret; } public void setGenerateSecret(boolean generateSecret) { this.generateSecret = generateSecret; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClientSecret.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClientSecret.java new file mode 100644 index 0000000000..fa7b67514f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClientSecret.java @@ -0,0 +1,44 @@ +package io.github.hectorvent.floci.services.cognito.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class UserPoolClientSecret { + private String clientSecretId; + private String clientSecretValue; + private long clientSecretCreateDate; + + public UserPoolClientSecret() { + // empty constructor for jackson deserialisation + } + + public UserPoolClientSecret(String clientSecretId, + long clientSecretCreateDate, String clientSecretValue) { + this.clientSecretCreateDate = clientSecretCreateDate; + this.clientSecretId = clientSecretId; + this.clientSecretValue = clientSecretValue; + } + + public long getClientSecretCreateDate() { + return clientSecretCreateDate; + } + public void setClientSecretCreateDate(long clientSecretCreateDate) { + this.clientSecretCreateDate = clientSecretCreateDate; + } + + public String getClientSecretId() { + return clientSecretId; + } + public void setClientSecretId(String clientSecretId) { + this.clientSecretId = clientSecretId; + } + + public String getClientSecretValue() { + return clientSecretValue; + } + public void setClientSecretValue(String clientSecretValue) { + this.clientSecretValue = clientSecretValue; + } +} 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.java index 62c0e47dd0..cf4b05250e 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 @@ -5,11 +5,17 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -19,6 +25,7 @@ import java.security.Signature; import java.security.spec.RSAPublicKeySpec; import java.util.Base64; import java.util.UUID; +import java.util.stream.Stream; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -614,8 +621,243 @@ class CognitoIntegrationTest { assertNotNull(refreshed.path("AuthenticationResult").path("IdToken").asText(null)); } + // ── Client Secrets ──────────────────────────────────────────────── + + private static String clientSecretId1; + private static String clientSecretId2; + + @Test + @Order(80) + void listUserPoolClientSecretsInitiallyEmpty() throws Exception { + JsonNode resp = cognitoJson("ListUserPoolClientSecrets", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, poolId)); + assertEquals(0, resp.path("ClientSecrets").size()); + } + + @ParameterizedTest + @Order(81) + @MethodSource("generateInvalidUserPoolSecret") + void addUserPoolClientSecretInvalid(String clientSecret) { + cognitoAction("AddUserPoolClientSecret", """ + { + "ClientId": "%s", + "UserPoolId": "%s", + "ClientSecret": "%s" + } + """.formatted(clientId, poolId, clientSecret)) + .then() + .statusCode(400); + } + + public static Stream generateInvalidUserPoolSecret() { + return Stream.of( + Arguments.of("a".repeat(23)), // too short + Arguments.of("a".repeat(65)), // too large + Arguments.of("$".repeat(32)) // contains invalid characters + ); + } + + @Test + @Order(82) + void addUserPoolClientSecretAutoGeneratesValue() throws Exception { + JsonNode resp = cognitoJson("AddUserPoolClientSecret", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, poolId)); + JsonNode clientSecretDescriptor = resp.path("ClientSecretDescriptor"); + clientSecretId1 = clientSecretDescriptor.path("ClientSecretId").asText(); + assertNotNull(clientSecretId1); + assertTrue(clientSecretId1.startsWith(clientId + "--"), + "ClientSecretId should be prefixed with the ClientId"); + assertNotNull(clientSecretDescriptor.path("ClientSecretValue").asText(null), + "Auto-generated secret should include ClientSecretValue in response"); + assertTrue(clientSecretDescriptor.path("ClientSecretCreateDate").asLong() > 0); + } + + @Test + @Order(83) + void addUserPoolClientSecretWithExplicitValue() throws Exception { + String clientSecretValue = UUID.randomUUID().toString().replaceAll("-", ""); + JsonNode resp = cognitoJson("AddUserPoolClientSecret", """ + { + "ClientId": "%s", + "UserPoolId": "%s", + "ClientSecret": "%s" + } + """.formatted(clientId, poolId, clientSecretValue)); + clientSecretId2 = resp.path("ClientSecretDescriptor").path("ClientSecretId").asText(); + assertNotNull(clientSecretId2); + assertTrue(resp.path("ClientSecretDescriptor").path("ClientSecretValue").isMissingNode(), + "Explicit secret should not include ClientSecretValue in response"); + } + + @Test + @Order(84) + void listUserPoolClientSecretsReturnsTwo() throws Exception { + JsonNode resp = cognitoJson("ListUserPoolClientSecrets", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, poolId)); + assertEquals(2, resp.path("ClientSecrets").size()); + } + + @Test + @Order(85) + void addUserPoolClientSecretExceedsLimit() { + cognitoAction("AddUserPoolClientSecret", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, poolId)) + .then() + .statusCode(400); + } + + @Test + @Order(86) + void deleteUserPoolClientSecretNotFound() { + cognitoAction("DeleteUserPoolClientSecret", """ + { + "ClientId": "%s", + "ClientSecretId": "nonexistent", + "UserPoolId": "%s" + } + """.formatted(clientId, poolId)) + .then() + .statusCode(404); + } + + @Test + @Order(87) + void deleteUserPoolClientSecretCannotDeleteOnlyOne() { + cognitoAction("DeleteUserPoolClientSecret", """ + { + "ClientId": "%s", + "ClientSecretId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, clientSecretId1, poolId)) + .then() + .statusCode(200); + + cognitoAction("DeleteUserPoolClientSecret", """ + { + "ClientId": "%s", + "ClientSecretId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, clientSecretId2, poolId)) + .then() + .statusCode(400); + } + + @Test + @Order(88) + void listUserPoolClientSecretsAfterDelete() throws Exception { + JsonNode resp = cognitoJson("ListUserPoolClientSecrets", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(clientId, poolId)); + assertEquals(1, resp.path("ClientSecrets").size()); + assertEquals(clientSecretId2, resp.path("ClientSecrets").get(0).path("ClientSecretId").asText()); + } + + @Test + @Order(89) + void fullRotateScenario() throws Exception { + // Set up a resource server so the OAuth client_credentials flow has valid scopes + cognitoJson("CreateResourceServer", """ + { + "UserPoolId": "%s", + "Identifier": "api", + "Name": "API", + "Scopes": [ + { "ScopeName": "read", "ScopeDescription": "Read access" } + ] + } + """.formatted(poolId)); + + // Create a confidential client with client_credentials flow enabled + JsonNode clientResp = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "rotation-client", + "GenerateSecret": true, + "AllowedOAuthFlowsUserPoolClient": true, + "AllowedOAuthFlows": ["client_credentials"], + "AllowedOAuthScopes": ["api/read"] + } + """.formatted(poolId)); + String rotClientId = clientResp.path("UserPoolClient").path("ClientId").asText(); + String secret1Value = clientResp.path("UserPoolClient").path("ClientSecret").asText(); + + // client-secret-1 is still valid — authenticate with client-credentials successfully + oauthToken(rotClientId, secret1Value).then().statusCode(200); + + // grab secret-1's ID so we can delete it later + JsonNode secrets = cognitoJson("ListUserPoolClientSecrets", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(rotClientId, poolId)); + assertEquals(1, secrets.path("ClientSecrets").size()); + String secret1Id = secrets.path("ClientSecrets").get(0).path("ClientSecretId").asText(); + + // add new client-secret (auto-generated) + JsonNode addResp = cognitoJson("AddUserPoolClientSecret", """ + { + "ClientId": "%s", + "UserPoolId": "%s" + } + """.formatted(rotClientId, poolId)); + String secret2Value = addResp.path("ClientSecretDescriptor") + .path("ClientSecretValue").asText(); + assertNotNull(secret2Value); + + // authenticate with new client-credentials successfully + oauthToken(rotClientId, secret2Value).then().statusCode(200); + + // delete client-credentials 1 + cognitoAction("DeleteUserPoolClientSecret", """ + { + "ClientId": "%s", + "ClientSecretId": "%s", + "UserPoolId": "%s" + } + """.formatted(rotClientId, secret1Id, poolId)) + .then() + .statusCode(200); + + // authentication with client credentials 1 fails + oauthToken(rotClientId, secret1Value).then().statusCode(400); + + // secret 2 still works after rotation + oauthToken(rotClientId, secret2Value).then().statusCode(200); + } + // ── Helpers ─────────────────────────────────────────────────────── + private static Response oauthToken(String oauthClientId, String oauthClientSecret) { + return given() + .formParam("grant_type", "client_credentials") + .formParam("client_id", oauthClientId) + .formParam("client_secret", oauthClientSecret) + .when() + .post("/cognito-idp/oauth2/token"); + } + private static Response cognitoAction(String action, String body) { return given() .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action)