diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 96355a44de..67660202cb 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -5,31 +5,39 @@ Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys. -`CreateUserPool` accepts a reserved user-pool tag, `floci:override-id`, to pin the resulting `UserPool.Id` at creation time. Floci strips reserved `floci:*` tags from stored and returned `UserPoolTags` on both create and update paths, so the tag namespace acts as an input-only control channel and is never persisted as user-visible metadata. +`CreateUserPool` supports overiding several values using user-pool tags **only** at creation time: +* `floci:override-id`, to pin the resulting `UserPool.Id`. +* `floci:override-cognito-client-id` + * set to `use-name` to use the client name as client ID. + * set to `append-to-name:-somestring` to append a string to the client name to be used as client ID. + * set to `prepend-to-name:somestring-` to prepend a string to the client name to be used as client ID. +* `floci:override-cognito-client-secret`, to set the secret for all clients created in this userpool. + +Floci strips reserved `floci:*` tags from stored and returned `UserPoolTags` on both create and update paths, so the tag namespace acts as an input-only control channel and is never persisted as user-visible metadata. Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource` and `UntagResource` operate on the persisted user-pool tag map. ## Supported Actions -| Category | Actions | -|---|---| -| **User Pools** | CreateUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, DeleteUserPool | -| **User Pool Tags** | TagResource, UntagResource, ListTagsForResource | -| **User Pool Clients** | CreateUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, DeleteUserPoolClient | -| **Resource Servers** | CreateResourceServer, DescribeResourceServer, ListResourceServers, DeleteResourceServer | -| **Admin User Management** | AdminCreateUser (including `MessageAction=RESEND`), AdminGetUser, AdminDeleteUser, AdminSetUserPassword, AdminUpdateUserAttributes | -| **User Operations** | SignUp, ConfirmSignUp, GetUser, UpdateUserAttributes, ChangePassword, ForgotPassword, ConfirmForgotPassword | -| **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge (supports USER_PASSWORD_AUTH, USER_SRP_AUTH, ADMIN_USER_SRP_AUTH) | -| **User Listing** | ListUsers | -| **Groups** | CreateGroup, GetGroup, UpdateGroup, ListGroups, ListUsersInGroup, DeleteGroup, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser | +| Category | Actions | +|---------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| **User Pools** | CreateUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, DeleteUserPool | +| **User Pool Tags** | TagResource, UntagResource, ListTagsForResource | +| **User Pool Clients** | CreateUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, DeleteUserPoolClient | +| **Resource Servers** | CreateResourceServer, DescribeResourceServer, ListResourceServers, DeleteResourceServer | +| **Admin User Management** | AdminCreateUser (including `MessageAction=RESEND`), AdminGetUser, AdminDeleteUser, AdminSetUserPassword, AdminUpdateUserAttributes | +| **User Operations** | SignUp, ConfirmSignUp, GetUser, UpdateUserAttributes, ChangePassword, ForgotPassword, ConfirmForgotPassword | +| **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge (supports USER_PASSWORD_AUTH, USER_SRP_AUTH, ADMIN_USER_SRP_AUTH) | +| **User Listing** | ListUsers | +| **Groups** | CreateGroup, GetGroup, UpdateGroup, ListGroups, ListUsersInGroup, DeleteGroup, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser | ## Well-Known And OAuth Endpoints -| Endpoint | Description | -|---|---| -| `GET /{userPoolId}/.well-known/openid-configuration` | OpenID discovery document | -| `GET /{userPoolId}/.well-known/jwks.json` | JSON Web Key Set for JWT validation | -| `POST /cognito-idp/oauth2/token` | Relaxed OAuth token endpoint for `grant_type=client_credentials` | +| Endpoint | Description | +|------------------------------------------------------|------------------------------------------------------------------| +| `GET /{userPoolId}/.well-known/openid-configuration` | OpenID discovery document | +| `GET /{userPoolId}/.well-known/jwks.json` | JSON Web Key Set for JWT validation | +| `POST /cognito-idp/oauth2/token` | Relaxed OAuth token endpoint for `grant_type=client_credentials` | `POST /cognito-idp/oauth2/token` is intentionally emulator-friendly rather than full Cognito parity: @@ -44,9 +52,9 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource` ## Configuration -| Variable | Default | Description | -|---|---|---| -| `FLOCI_SERVICES_COGNITO_ENABLED` | `true` | Enable or disable the service | +| Variable | Default | Description | +|----------------------------------|---------|-------------------------------| +| `FLOCI_SERVICES_COGNITO_ENABLED` | `true` | Enable or disable the service | ## Examples diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index 6fcf740b0b..8312682e62 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -53,6 +53,7 @@ import org.jboss.logging.Logger; @Path("/") public class AwsJson11Controller { + public static final String CONTENT_TYPE_AWS_JSON_1_1 = "application/x-amz-json-1.1"; private static final Logger LOG = Logger.getLogger(AwsJson11Controller.class); private final ObjectMapper objectMapper; @@ -160,8 +161,8 @@ public class AwsJson11Controller { } @POST - @Consumes("application/x-amz-json-1.1") - @Produces("application/x-amz-json-1.1") + @Consumes(CONTENT_TYPE_AWS_JSON_1_1) + @Produces(CONTENT_TYPE_AWS_JSON_1_1) public Response handle( @HeaderParam("X-Amz-Target") String target, @Context HttpHeaders httpHeaders, diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java index dadd8166fa..42ad95c3ce 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java @@ -27,6 +27,7 @@ import org.jboss.logging.Logger; @Path("/") public class AwsJsonController { + public static final String CONTENT_TYPE_AWS_JSON_1_0 = "application/x-amz-json-1.0"; private static final Logger LOG = Logger.getLogger(AwsJsonController.class); private final ObjectMapper objectMapper; @@ -59,8 +60,8 @@ public class AwsJsonController { } @POST - @Consumes("application/x-amz-json-1.0") - @Produces("application/x-amz-json-1.0") + @Consumes(CONTENT_TYPE_AWS_JSON_1_0) + @Produces(CONTENT_TYPE_AWS_JSON_1_0) public Response handleJsonRequest( @HeaderParam("X-Amz-Target") String target, @Context HttpHeaders httpHeaders, diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java b/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java index 8123b95a7a..cfcfd90acb 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.core.common; import io.quarkus.runtime.annotations.RegisterForReflection; +import org.apache.commons.lang3.function.TriFunction; import java.util.HashMap; import java.util.Map; @@ -10,15 +11,30 @@ public final class ReservedTags { public static final String RESERVED_PREFIX = "floci:"; public static final String OVERRIDE_ID_KEY = RESERVED_PREFIX + "override-id"; + public static final String OVERRIDE_COGNITO_CLIENT_ID_KEY = RESERVED_PREFIX + "override-cognito-client-id"; + public static final String OVERRIDE_COGNITO_CLIENT_SECRET_KEY = RESERVED_PREFIX + "override-cognito-client-secret"; + private static final String INVALID_PARAMETER_EXCEPTION = "InvalidParameterException"; + private static final String VALIDATION_EXCEPTION = "ValidationException"; + private static final String TAG_EXCEPTION = "TagException"; + private static final String CONTROL_CHARACTER_ERROR_MESSAGE = "Override %s must not contain control characters."; private ReservedTags() { } - public static String extractOverrideId(Map tags) { - if (tags == null) { - return null; - } - return tags.get(OVERRIDE_ID_KEY); + public static String extractOverrideKeyId(Map tags) { + return getOverride(tags, OVERRIDE_ID_KEY, ReservedTags::validateOverrideId, "Resource ID", TAG_EXCEPTION); + } + + public static String extractOverrideUserPoolId(Map tags) { + return getOverride(tags, OVERRIDE_ID_KEY, ReservedTags::validateOverrideId, "Resource ID", INVALID_PARAMETER_EXCEPTION); + } + + public static String extractOverrideCognitoClientId(Map tags) { + return getOverride(tags, OVERRIDE_COGNITO_CLIENT_ID_KEY, ReservedTags::validateOverrideId, "Cognito Client ID", INVALID_PARAMETER_EXCEPTION); + } + + public static String extractOverrideCognitoClientSecret(Map tags) { + return getOverride(tags, OVERRIDE_COGNITO_CLIENT_SECRET_KEY, ReservedTags::validateClientSecret, "Cognito Client Secret", INVALID_PARAMETER_EXCEPTION); } public static Map stripReservedTags(Map tags) { @@ -41,7 +57,7 @@ public final class ReservedTags { for (String key : tags.keySet()) { if (isReserved(key)) { throw new AwsException( - "ValidationException", + VALIDATION_EXCEPTION, "Reserved tag keys with prefix " + RESERVED_PREFIX + " can only be supplied during resource creation.", 400 ); @@ -49,6 +65,63 @@ public final class ReservedTags { } } + public static void rejectUnknownReservedTags(Map tags, String errorCode) { + if (tags == null) { + return; + } + for (String key : tags.keySet()) { + if (isReserved(key) && !key.equals(OVERRIDE_ID_KEY) && !key.equals(OVERRIDE_COGNITO_CLIENT_ID_KEY) && !key.equals(OVERRIDE_COGNITO_CLIENT_SECRET_KEY)) { + throw new AwsException( + errorCode, + "%s is an unknown Reserved Tag.".formatted(key), + 400 + ); + } + } + } + + private static String getOverride(Map tags, String override, TriFunction validator, String name, String errorCode) { + if (tags == null) { + return null; + } + if (tags.containsKey(override)) { + String ov = tags.get(override); + return validator.apply(ov, name, errorCode); + } + return null; + } + + private static String validateOverrideId(String overrideId, String name, String errorCode) { + String normalized = checkNullAndWhitespace(overrideId, name, errorCode); + if (normalized.indexOf('/') >= 0 || normalized.indexOf('?') >= 0 || normalized.indexOf('#') >= 0) { + throw new AwsException(errorCode, "Override %s contains unsupported characters.".formatted(name), 400); + } + if (normalized.chars().anyMatch(Character::isISOControl)) { + throw new AwsException(errorCode, CONTROL_CHARACTER_ERROR_MESSAGE.formatted(name), 400); + } + return normalized; + } + + private static String validateClientSecret(String overrideSecret, String name, String errorCode) { + String normalized = checkNullAndWhitespace(overrideSecret, name, errorCode); + if (normalized.chars().anyMatch(Character::isISOControl)) { + throw new AwsException(errorCode, CONTROL_CHARACTER_ERROR_MESSAGE.formatted(name), 400); + } + return normalized; + } + + private static String checkNullAndWhitespace(String overrideSecret, String name, String errorCode) { + if (overrideSecret == null || overrideSecret.trim().isEmpty()) { + throw new AwsException(errorCode, "Override %s must not be blank.".formatted(name), 400); + } + String normalized = overrideSecret.trim(); + if (normalized.chars().anyMatch(Character::isWhitespace)) { + throw new AwsException(errorCode, "Override %s must not contain whitespace.".formatted(name), 400); + } + return normalized; + } + + private static boolean isReserved(String key) { return key != null && key.startsWith(RESERVED_PREFIX); } 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 d84baeeee6..32576cbcbb 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 @@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.sns.SnsService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import org.jspecify.annotations.Nullable; import java.nio.charset.StandardCharsets; import java.security.*; @@ -30,6 +31,8 @@ import java.time.Clock; import java.time.Duration; import java.util.*; +import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags; + @ApplicationScoped public class CognitoService { private static final int DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS = 30; @@ -39,7 +42,7 @@ public class CognitoService { /** * Claim overrides returned by a PreTokenGeneration Lambda trigger. - * + *

* Supports both V1 (single claims map applied to both id and access tokens) * and V2 (per-token-type claim overrides + scope changes for the access * token). For V1 lambdas the parser populates the id/access slots with the @@ -138,6 +141,7 @@ public class CognitoService { public UserPool createUserPool(Map request, String region) { String name = (String) request.get("PoolName"); Map userPoolTags = (Map) request.get("UserPoolTags"); + rejectUnknownReservedTags(userPoolTags,"UserPoolTaggingException"); String id = resolveUserPoolId(region, userPoolTags); if (poolStore.get(id).isPresent()) { throw new AwsException("ResourceConflictException", "User pool already exists", 400); @@ -146,7 +150,8 @@ public class CognitoService { pool.setId(id); pool.setName(name); pool.setArn(regionResolver.buildArn("cognito-idp", region, "userpool/" + id)); - + pool.setClientIdOverride(getClientIdOverride(userPoolTags)); + pool.setClientSecretOverride(ReservedTags.extractOverrideCognitoClientSecret(userPoolTags)); populateUserPool(pool, request); ensureJwtSigningKeys(pool); @@ -155,6 +160,15 @@ public class CognitoService { return pool; } + private @Nullable String getClientIdOverride(Map userPoolTags) { + String overrideMode = ReservedTags.extractOverrideCognitoClientId(userPoolTags); + if (overrideMode != null && + (!overrideMode.equals("use-name") && !overrideMode.startsWith("append-to-name:") && !overrideMode.startsWith("prepend-to-name:"))) { + throw new AwsException("InvalidParameterException", "Invalid override mode for Cognito client ID. Only use-name, append-to-name: and prepend-to-name: are allowed", 400); + } + return overrideMode; + } + public UserPool updateUserPool(Map request, String region) { String id = (String) request.get("UserPoolId"); UserPool pool = describeUserPool(id); @@ -331,16 +345,17 @@ public class CognitoService { } public UserPoolClient createUserPoolClient(String userPoolId, String clientName, - boolean generateSecret, boolean allowedOAuthFlowsUserPoolClient, - List allowedOAuthFlows, List allowedOAuthScopes, - Map analyticsConfiguration, List callbackURLs, - String defaultRedirectURI, List explicitAuthFlows, Integer accessTokenValidity, - Integer idTokenValidity, List logoutURLs, String preventUserExistenceErrors, - List readAttributes, Integer refreshTokenValidity, - List supportedIdentityProviders, Map tokenValidityUnits, - List writeAttributes, Map refreshTokenRotation, - Boolean enableTokenRevocation) { - describeUserPool(userPoolId); + boolean generateSecret, boolean allowedOAuthFlowsUserPoolClient, + List allowedOAuthFlows, List allowedOAuthScopes, + Map analyticsConfiguration, List callbackURLs, + String defaultRedirectURI, List explicitAuthFlows, Integer accessTokenValidity, + Integer idTokenValidity, List logoutURLs, String preventUserExistenceErrors, + List readAttributes, Integer refreshTokenValidity, + List supportedIdentityProviders, Map tokenValidityUnits, + List writeAttributes, Map refreshTokenRotation, + Boolean enableTokenRevocation) { + + UserPool userPool = describeUserPool(userPoolId); String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26); List normalizedAllowedOAuthFlows = normalizeStringList(allowedOAuthFlows); List normalizedAllowedOAuthScopes = normalizeStringList(allowedOAuthScopes); @@ -368,6 +383,15 @@ public class CognitoService { ); UserPoolClient client = new UserPoolClient(); + if (userPool.getClientIdOverride() != null) { + if (userPool.getClientIdOverride().equalsIgnoreCase("use-name")) { + clientId = clientName; + } else if (userPool.getClientIdOverride().startsWith("append-to-name:")) { + clientId = clientName + userPool.getClientIdOverride().substring(15); + } else if (userPool.getClientIdOverride().startsWith("prepend-to-name:")) { + clientId = userPool.getClientIdOverride().substring(16) + clientName; + } + } client.setClientId(clientId); client.setUserPoolId(userPoolId); client.setClientName(clientName); @@ -394,6 +418,12 @@ public class CognitoService { client.setEnableTokenRevocation(enableTokenRevocation != null ? enableTokenRevocation : Boolean.TRUE); if (generateSecret) { String clientSecret = generateSecretValue(); + if (userPool.getClientSecretOverride() != null) { + clientSecret = userPool.getClientSecretOverride(); + if (clientSecret.isEmpty()) { + throw new AwsException("InvalidParameterException", "Client secret override cannot be empty", 400); + } + } client.setClientSecret(clientSecret); long epochMillis = System.currentTimeMillis(); @@ -1367,29 +1397,11 @@ public class CognitoService { } private String resolveUserPoolId(String region, Map tags) { - String overrideId = ReservedTags.extractOverrideId(tags); + String overrideId = ReservedTags.extractOverrideUserPoolId(tags); if (overrideId == null) { return region + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9); } - validateOverridePoolId(overrideId); - return overrideId.trim(); - } - - private void validateOverridePoolId(String overrideId) { - if (overrideId == null || overrideId.trim().isEmpty()) { - throw new AwsException("ValidationException", "Override resource ID must not be blank.", 400); - } - - String normalized = overrideId.trim(); - if (normalized.chars().anyMatch(Character::isWhitespace)) { - throw new AwsException("ValidationException", "Override resource ID must not contain whitespace.", 400); - } - if (normalized.indexOf('/') >= 0 || normalized.indexOf('?') >= 0 || normalized.indexOf('#') >= 0) { - throw new AwsException("ValidationException", "Override resource ID contains unsupported characters.", 400); - } - if (normalized.chars().anyMatch(Character::isISOControl)) { - throw new AwsException("ValidationException", "Override resource ID must not contain control characters.", 400); - } + return overrideId; } public String getJwksUri(String poolId) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java index 279e0b228e..a142101551 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java @@ -46,6 +46,9 @@ public class UserPool { private Map accountRecoverySetting = new HashMap<>(); private String userPoolTier = "ESSENTIALS"; + private String clientIdOverride = null; + private String clientSecretOverride = null; + public UserPool() { long now = System.currentTimeMillis() / 1000L; this.creationDate = now; @@ -151,4 +154,10 @@ public class UserPool { public String getUserPoolTier() { return userPoolTier; } public void setUserPoolTier(String userPoolTier) { this.userPoolTier = userPoolTier; } + + public String getClientIdOverride() { return clientIdOverride; } + public void setClientIdOverride(String clientIdOverride) { this.clientIdOverride = clientIdOverride;} + + public String getClientSecretOverride() { return clientSecretOverride; } + public void setClientSecretOverride(String clientSecretOverride) { this.clientSecretOverride = clientSecretOverride; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java index a032570e01..ebd3682f79 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java @@ -20,6 +20,8 @@ import jakarta.ws.rs.core.Response; import java.util.*; +import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags; + @ApplicationScoped public class KmsJsonHandler { @@ -87,7 +89,7 @@ public class KmsJsonHandler { String policy = request.path("Policy").isMissingNode() ? null : request.path("Policy").asText(null); Map tags = new HashMap<>(); request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText())); - + rejectUnknownReservedTags(tags,"TagException"); KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, region); ObjectNode response = objectMapper.createObjectNode(); response.set("KeyMetadata", addKeyMetadata(key)); diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index edf40cbe98..42a82e8c69 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -156,17 +156,17 @@ public class KmsService { } private String resolveKeyId(Map tags) { - String overrideId = ReservedTags.extractOverrideId(tags); + String overrideId = ReservedTags.extractOverrideKeyId(tags); if (overrideId == null) { return UUID.randomUUID().toString(); } String normalized = overrideId.trim(); if (normalized.isEmpty()) { - throw new AwsException("ValidationException", "Override resource ID must not be blank.", 400); + throw new AwsException("TagException", "Override resource ID must not be blank.", 400); } if (normalized.length() > 256) { - throw new AwsException("ValidationException", "Override resource ID must be 256 characters or fewer.", 400); + throw new AwsException("TagException", "Override resource ID must be 256 characters or fewer.", 400); } return normalized; } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java index d0f64e65f3..e24bfb7bd8 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java @@ -54,19 +54,19 @@ class ReservedTagsTest { } @Test - void extractOverrideIdReturnsNullForNullInput() { - assertNull(ReservedTags.extractOverrideId(null)); + void extractOverrideUserPoolIdReturnsNullForNullInput() { + assertNull(ReservedTags.extractOverrideUserPoolId(null)); } @Test - void extractOverrideIdReturnsReservedOverrideOnly() { + void extractOverrideIdReturnsReservedOverrideUserPoolOnly() { Map tags = Map.of( ReservedTags.OVERRIDE_ID_KEY, "my-id", "floci:internal", "hidden", "env", "test" ); - assertEquals("my-id", ReservedTags.extractOverrideId(tags)); + assertEquals("my-id", ReservedTags.extractOverrideUserPoolId(tags)); } @Test @@ -83,4 +83,24 @@ class ReservedTagsTest { assertEquals("ValidationException", exception.getErrorCode()); } + + @Test + void rejectUnknownReservedTagsRejectsReservedTagsWithUserPoolTaggingException() { + AwsException exception = assertThrows( + AwsException.class, + () -> ReservedTags.rejectUnknownReservedTags(Map.of(ReservedTags.RESERVED_PREFIX + "unknown-override", "something"), "UserPoolTaggingException") + ); + + assertEquals("UserPoolTaggingException", exception.getErrorCode()); + } + + @Test + void rejectUnknownReservedTagsRejectsReservedTagsWithTagException() { + AwsException exception = assertThrows( + AwsException.class, + () -> ReservedTags.rejectUnknownReservedTags(Map.of(ReservedTags.RESERVED_PREFIX + "unknown-override", "something"), "TagException") + ); + + assertEquals("TagException", exception.getErrorCode()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java index b116b84803..0c058044e9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java @@ -4,19 +4,19 @@ import com.fasterxml.jackson.databind.JsonNode; 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.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 static io.restassured.RestAssured.given; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; import static org.junit.jupiter.api.Assertions.*; /** * Integration tests for the AdminUserGlobalSignOut API. - * + *

* Reproduces issue #1395: previously issued tokens must be invalidated * after calling AdminUserGlobalSignOut, matching AWS Cognito behavior. */ @@ -24,13 +24,11 @@ import static org.junit.jupiter.api.Assertions.*; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class AdminUserGlobalSignOutIntegrationTest { - private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; private static final ObjectMapper MAPPER = new ObjectMapper(); private static String poolId; private static String clientId; private static String refreshToken; - private static String accessToken; private static final String USERNAME = "alice"; private static final String PASSWORD = "Password123!"; @@ -42,20 +40,6 @@ class AdminUserGlobalSignOutIntegrationTest { // ─── helpers ──────────────────────────────────────────────────────────── - private static Response cognitoAction(String action, String body) { - return given() - .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) - .contentType(CONTENT_TYPE) - .body(body) - .when() - .post("/"); - } - - private static JsonNode cognitoJson(String action, String body) throws Exception { - return MAPPER.readTree( - cognitoAction(action, body).then().statusCode(200).extract().asString()); - } - /** POST without asserting 200 — lets tests inspect the error response. */ private static JsonNode cognitoJsonAny(String action, String body) throws Exception { return MAPPER.readTree(cognitoAction(action, body).then().extract().asString()); @@ -103,7 +87,7 @@ class AdminUserGlobalSignOutIntegrationTest { """.formatted(clientId, USERNAME, PASSWORD)); refreshToken = auth.path("AuthenticationResult").path("RefreshToken").asText(); - accessToken = auth.path("AuthenticationResult").path("AccessToken").asText(); + String accessToken = auth.path("AuthenticationResult").path("AccessToken").asText(); assertFalse(refreshToken.isBlank(), "RefreshToken must be present after sign-in"); assertFalse(accessToken.isBlank(), "AccessToken must be present after sign-in"); 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 080f4711de..b9c4e5e555 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 @@ -29,6 +29,8 @@ import java.util.UUID; import java.util.stream.Stream; import java.util.stream.StreamSupport; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -40,14 +42,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class CognitoIntegrationTest { - private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b"); private static String poolId; private static String clientId; - private static final String username = "alice+" + UUID.randomUUID() + "@example.com"; - private static final String password = "Perm1234!"; + private static final String USERNAME = "alice+" + UUID.randomUUID() + "@example.com"; + private static final String PASSWORD = "Perm1234!"; @BeforeAll static void configureRestAssured() { @@ -93,7 +94,7 @@ class CognitoIntegrationTest { { "Name": "custom:department", "Value": "engineering" } ] } - """.formatted(poolId, username, username)) + """.formatted(poolId, USERNAME, USERNAME)) .then() .statusCode(200); @@ -104,7 +105,7 @@ class CognitoIntegrationTest { "Password": "%s", "Permanent": true } - """.formatted(poolId, username, password)) + """.formatted(poolId, USERNAME, PASSWORD)) .then() .statusCode(200); } @@ -121,7 +122,7 @@ class CognitoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, password)) + """.formatted(clientId, USERNAME, PASSWORD)) .then() .statusCode(200) .body("AuthenticationResult.AccessToken", org.hamcrest.Matchers.notNullValue()) @@ -141,7 +142,7 @@ class CognitoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); authResponse.then().statusCode(200); @@ -151,7 +152,7 @@ class CognitoIntegrationTest { assertEquals("RS256", header.path("alg").asText()); assertEquals(poolId, header.path("kid").asText()); assertEquals("http://localhost:4566/" + poolId, payload.path("iss").asText()); - assertEquals(username, payload.path("username").asText()); + assertEquals(USERNAME, payload.path("username").asText()); assertEquals("access", payload.path("token_use").asText()); String jwksResponse = given() @@ -582,7 +583,7 @@ class CognitoIntegrationTest { "GroupName": "admin", "Username": "%s" } - """.formatted(poolId, username)) + """.formatted(poolId, USERNAME)) .then() .statusCode(200); } @@ -595,7 +596,7 @@ class CognitoIntegrationTest { "UserPoolId": "%s", "Username": "%s" } - """.formatted(poolId, username)); + """.formatted(poolId, USERNAME)); assertEquals(1, resp.path("Groups").size()); assertEquals("admin", resp.path("Groups").get(0).path("GroupName").asText()); } @@ -612,7 +613,7 @@ class CognitoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); authResponse.then().statusCode(200); @@ -634,7 +635,7 @@ class CognitoIntegrationTest { "GroupName": "admin", "Username": "%s" } - """.formatted(poolId, username)) + """.formatted(poolId, USERNAME)) .then() .statusCode(200); } @@ -647,7 +648,7 @@ class CognitoIntegrationTest { "UserPoolId": "%s", "Username": "%s" } - """.formatted(poolId, username)); + """.formatted(poolId, USERNAME)); assertEquals(0, resp.path("Groups").size()); } @@ -730,7 +731,7 @@ class CognitoIntegrationTest { "GroupName": "editors", "Username": "%s" } - """.formatted(poolId, username)) + """.formatted(poolId, USERNAME)) .then().statusCode(200); // List users in group @@ -742,7 +743,7 @@ class CognitoIntegrationTest { """.formatted(poolId)); assertEquals(1, resp.path("Users").size()); - assertEquals(username, resp.path("Users").get(0).path("Username").asText()); + assertEquals(USERNAME, resp.path("Users").get(0).path("Username").asText()); } @Test @@ -755,7 +756,7 @@ class CognitoIntegrationTest { "GroupName": "editors", "Username": "%s" } - """.formatted(poolId, username)) + """.formatted(poolId, USERNAME)) .then().statusCode(200); JsonNode resp = cognitoJson("ListUsersInGroup", """ @@ -796,7 +797,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String idToken = auth.path("AuthenticationResult").path("IdToken").asText(); JsonNode payload = decodeJwtPayload(idToken); assertTrue(payload.path("client_id").isMissingNode(), @@ -814,7 +815,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String idToken = auth.path("AuthenticationResult").path("IdToken").asText(); JsonNode payload = decodeJwtPayload(idToken); assertEquals(clientId, payload.path("aud").asText(), @@ -839,7 +840,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String refreshToken = authResp.path("AuthenticationResult").path("RefreshToken").asText(); JsonNode refreshed = cognitoJson("InitiateAuth", """ @@ -982,7 +983,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); JsonNode payload = decodeJwtPayload( auth.path("AuthenticationResult").path("IdToken").asText()); @@ -1010,7 +1011,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); JsonNode payload = decodeJwtPayload( auth.path("AuthenticationResult").path("AccessToken").asText()); @@ -1032,7 +1033,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String refreshToken = authResp.path("AuthenticationResult").path("RefreshToken").asText(); JsonNode refreshed = cognitoJson("InitiateAuth", """ @@ -1063,7 +1064,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "WrongPassword!" } } - """.formatted(clientId, username)) + """.formatted(clientId, USERNAME)) .then() .statusCode(400); } @@ -1075,7 +1076,7 @@ class CognitoIntegrationTest { void adminGetUserBySubUuid() throws Exception { JsonNode user = cognitoJson("AdminGetUser", """ { "UserPoolId": "%s", "Username": "%s" } - """.formatted(poolId, username)); + """.formatted(poolId, USERNAME)); String sub = null; for (JsonNode attr : user.path("UserAttributes")) { if ("sub".equals(attr.path("Name").asText())) { @@ -1088,7 +1089,7 @@ class CognitoIntegrationTest { JsonNode bySubUser = cognitoJson("AdminGetUser", """ { "UserPoolId": "%s", "Username": "%s" } """.formatted(poolId, sub)); - assertEquals(username, bySubUser.path("Username").asText(), + assertEquals(USERNAME, bySubUser.path("Username").asText(), "AdminGetUser with sub UUID should return the same user"); } @@ -1097,8 +1098,8 @@ class CognitoIntegrationTest { void adminGetUserByEmailAlias() throws Exception { JsonNode byEmail = cognitoJson("AdminGetUser", """ { "UserPoolId": "%s", "Username": "%s" } - """.formatted(poolId, username)); - assertEquals(username, byEmail.path("Username").asText()); + """.formatted(poolId, USERNAME)); + assertEquals(USERNAME, byEmail.path("Username").asText()); } // ── Issue #233: ListUsers Filter ───────────────────────────────────── @@ -1111,16 +1112,16 @@ class CognitoIntegrationTest { "UserPoolId": "%s", "Filter": "email = \\"%s\\"" } - """.formatted(poolId, username)); + """.formatted(poolId, USERNAME)); assertEquals(1, resp.path("Users").size(), "Filter by email should return exactly one matching user"); - assertEquals(username, resp.path("Users").get(0).path("Username").asText()); + assertEquals(USERNAME, resp.path("Users").get(0).path("Username").asText()); } @Test @Order(61) void listUsersFilterByEmailPrefixStartsWith() throws Exception { - String prefix = username.substring(0, 5); + String prefix = USERNAME.substring(0, 5); JsonNode resp = cognitoJson("ListUsers", """ { "UserPoolId": "%s", @@ -1151,7 +1152,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String refreshToken = authResp.path("AuthenticationResult").path("RefreshToken").asText(); assertNotNull(refreshToken); @@ -1177,7 +1178,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String refreshToken = authResp.path("AuthenticationResult").path("RefreshToken").asText(); JsonNode refreshed = cognitoJson("InitiateAuth", """ @@ -1420,14 +1421,14 @@ class CognitoIntegrationTest { @Test @Order(90) - void adminResetUserPasswordBlocksAuth() throws Exception { + void adminResetUserPasswordBlocksAuth() { // 1. Reset the user's password cognitoAction("AdminResetUserPassword", """ { "UserPoolId": "%s", "Username": "%s" } - """.formatted(poolId, username)) + """.formatted(poolId, USERNAME)) .then() .statusCode(200); @@ -1441,7 +1442,7 @@ class CognitoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, password)) + """.formatted(clientId, USERNAME, PASSWORD)) .then() .statusCode(400) .body("__type", org.hamcrest.Matchers.containsString("PasswordResetRequiredException")); @@ -1455,7 +1456,7 @@ class CognitoIntegrationTest { "Password": "%s", "Permanent": true } - """.formatted(poolId, username, newPassword)) + """.formatted(poolId, USERNAME, newPassword)) .then() .statusCode(200); @@ -1469,7 +1470,7 @@ class CognitoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, newPassword)) + """.formatted(clientId, USERNAME, newPassword)) .then() .statusCode(200); } @@ -1503,7 +1504,7 @@ class CognitoIntegrationTest { { "Name": "email", "Value": "%s" } ] } - """.formatted(localClientId, testUser, password, testUser)); + """.formatted(localClientId, testUser, PASSWORD, testUser)); // Get user details to verify user status is UNCONFIRMED JsonNode userResp = cognitoJson("AdminGetUser", """ @@ -2155,23 +2156,7 @@ class CognitoIntegrationTest { assertEquals(1200L, refreshedIdPayload.path("exp").asLong() - refreshedIdPayload.path("iat").asLong()); } - private static Response cognitoAction(String action, String body) { - return given() - .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) - .contentType(COGNITO_CONTENT_TYPE) - .body(body) - .when() - .post("/"); - } - private static JsonNode cognitoJson(String action, String body) throws Exception { - String response = cognitoAction(action, body) - .then() - .statusCode(200) - .extract() - .asString(); - return OBJECT_MAPPER.readTree(response); - } private static JsonNode decodeJwtPayload(String token) throws Exception { return decodeJwtPart(token, 1); @@ -2209,7 +2194,7 @@ class CognitoIntegrationTest { "AuthFlow": "USER_PASSWORD_AUTH", "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); return auth.path("AuthenticationResult").path("AccessToken").asText(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java index 6459e380da..5369fcf4be 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java @@ -19,17 +19,16 @@ import java.security.Signature; import java.security.spec.RSAPublicKeySpec; import java.util.Base64; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class CognitoOAuthTokenIntegrationTest { - private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static String poolId; @@ -482,24 +481,6 @@ class CognitoOAuthTokenIntegrationTest { assertEquals("client_secret_basic", document.path("token_endpoint_auth_methods_supported").get(0).asText()); } - private static Response cognitoAction(String action, String body) { - return given() - .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) - .contentType(COGNITO_CONTENT_TYPE) - .body(body) - .when() - .post("/"); - } - - private static JsonNode cognitoJson(String action, String body) throws Exception { - String response = cognitoAction(action, body) - .then() - .statusCode(200) - .extract() - .asString(); - return OBJECT_MAPPER.readTree(response); - } - private static String cognitoDescribeClientSecret(String clientId) { return cognitoAction("DescribeUserPoolClient", """ { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoRestAssuredUtils.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoRestAssuredUtils.java new file mode 100644 index 0000000000..d8b776653c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoRestAssuredUtils.java @@ -0,0 +1,17 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.restassured.response.Response; + +public class CognitoRestAssuredUtils { + private CognitoRestAssuredUtils(){} + + public static Response cognitoAction(String action, String body) { + return RestAssuredJsonUtils.awsAction("AWSCognitoIdentityProviderService", action, body); + } + + public static JsonNode cognitoJson(String action, String body) throws Exception { + return RestAssuredJsonUtils.awsActionJson("AWSCognitoIdentityProviderService", action, body); + } +} 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.java index 06ea588f43..d30ca70a06 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -13,6 +13,8 @@ import io.github.hectorvent.floci.services.cognito.verification.VerificationCode import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -607,7 +609,7 @@ class CognitoServiceTest { ) ); - assertEquals("ValidationException", exception.getErrorCode()); + assertEquals("InvalidParameterException", exception.getErrorCode()); } @Test @@ -620,7 +622,7 @@ class CognitoServiceTest { ) ); - assertEquals("ValidationException", exception.getErrorCode()); + assertEquals("InvalidParameterException", exception.getErrorCode()); } @Test @@ -632,7 +634,7 @@ class CognitoServiceTest { "us-east-1" ) ); - assertEquals("ValidationException", questionMarkException.getErrorCode()); + assertEquals("InvalidParameterException", questionMarkException.getErrorCode()); AwsException hashException = assertThrows( AwsException.class, @@ -641,7 +643,7 @@ class CognitoServiceTest { "us-east-1" ) ); - assertEquals("ValidationException", hashException.getErrorCode()); + assertEquals("InvalidParameterException", hashException.getErrorCode()); } @Test @@ -1980,4 +1982,68 @@ class CognitoServiceTest { CognitoUser user = service.adminGetUser(pool.getId(), "carol"); assertEquals("Carolyn", user.getAttributes().get("given_name")); } + + // ========================================================================= + // Cognito ClientId And Secret overrides + // ========================================================================= + + @ParameterizedTest + @CsvSource( { + "use-name,basic-client", + "prepend-to-name:prepended-,prepended-basic-client", + "append-to-name:-appended,basic-client-appended", + }) + void createUserPoolWithOverrideForClientIdAndClientSecret(String overrideClientId, String expectedClientId) { + UserPool pool = service.createUserPool( + Map.of( + "PoolName", "ClientOverridesPool", + "UserPoolTags", Map.of( + "env", "test", + ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY, overrideClientId, + ReservedTags.OVERRIDE_COGNITO_CLIENT_SECRET_KEY, "secret") + ), + "us-east-1" + ); + + assertEquals("test",pool.getUserPoolTags().get("env")); + assertFalse(pool.getUserPoolTags().containsKey(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY)); + assertFalse(pool.getUserPoolTags().containsKey(ReservedTags.OVERRIDE_COGNITO_CLIENT_SECRET_KEY)); + + UserPoolClient client = service.createUserPoolClient( + pool.getId(), + "basic-client", + true, + true, + List.of(), + List.of() + ); + + assertEquals("basic-client", client.getClientName()); + assertEquals(expectedClientId, client.getClientId()); + assertEquals("secret", client.getClientSecret()); + } + + @ParameterizedTest + @CsvSource( { + "prepend-to-name: prepended- ,secret", + "append-to-name: -appended ,secret", + "append-to-name:-appended,", + "something-else,secret" + }) + void createUserPoolWithInvalidOverrideForClientIdAndClientSecret(String overrideClientId, String secret) { + Map createUserPool = new HashMap<>(); + Map userPoolTags = new HashMap<>(); + userPoolTags.put(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY, overrideClientId); + userPoolTags.put(ReservedTags.OVERRIDE_COGNITO_CLIENT_SECRET_KEY, secret); + createUserPool.put("PoolName", "InvalidOverridesPool"); + createUserPool.put("UserPoolTags", userPoolTags); + + AwsException ex = assertThrows(AwsException.class, () -> + service.createUserPool( + createUserPool, + "us-east-1" + )); + assertEquals("InvalidParameterException", ex.getErrorCode()); + + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java index 01f2412e06..f51a78869a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java @@ -13,25 +13,23 @@ import org.junit.jupiter.api.TestMethodOrder; import java.util.UUID; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class CognitoUserInfoIntegrationTest { - private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static String poolId; private static String clientId; private static String accessToken; - private static final String username = "carol+" + UUID.randomUUID() + "@example.com"; - private static final String password = "Perm1234!"; + private static final String USERNAME = "carol+" + UUID.randomUUID() + "@example.com"; + private static final String PASSWORD = "Perm1234!"; @BeforeAll static void configureRestAssured() { @@ -71,7 +69,7 @@ class CognitoUserInfoIntegrationTest { { "Name": "custom:tenant_id", "Value": "tenant-42" } ] } - """.formatted(poolId, username, username)) + """.formatted(poolId, USERNAME, USERNAME)) .then() .statusCode(200); @@ -82,7 +80,7 @@ class CognitoUserInfoIntegrationTest { "Password": "%s", "Permanent": true } - """.formatted(poolId, username, password)) + """.formatted(poolId, USERNAME, PASSWORD)) .then() .statusCode(200); @@ -95,7 +93,7 @@ class CognitoUserInfoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); accessToken = authResp.path("AuthenticationResult").path("AccessToken").asText(); assertNotNull(accessToken); assertFalse(accessToken.isBlank()); @@ -116,9 +114,9 @@ class CognitoUserInfoIntegrationTest { JsonNode body = OBJECT_MAPPER.readTree(response.asString()); - assertEquals(username, body.path("username").asText()); + assertEquals(USERNAME, body.path("username").asText()); assertTrue(body.hasNonNull("sub")); - assertEquals(username, body.path("email").asText()); + assertEquals(USERNAME, body.path("email").asText()); // email_verified / phone_number_verified must be JSON strings, not booleans. assertTrue(body.path("email_verified").isTextual(), "email_verified must be a string per AWS Cognito spec"); @@ -263,7 +261,7 @@ class CognitoUserInfoIntegrationTest { "PASSWORD": "%s" } } - """.formatted(clientId, username, password)); + """.formatted(clientId, USERNAME, PASSWORD)); String refreshToken = initialAuth.path("AuthenticationResult").path("RefreshToken").asText(); assertNotNull(refreshToken); @@ -286,7 +284,7 @@ class CognitoUserInfoIntegrationTest { .extract() .asString(); JsonNode refreshedBody = OBJECT_MAPPER.readTree(refreshedResponse); - assertEquals(username, refreshedBody.path("username").asText()); + assertEquals(USERNAME, refreshedBody.path("username").asText()); assertEquals("true", refreshedBody.path("email_verified").asText()); assertEquals("tenant-42", refreshedBody.path("custom:tenant_id").asText()); } @@ -338,24 +336,6 @@ class CognitoUserInfoIntegrationTest { .header("WWW-Authenticate", containsString("invalid_token")); } - private static Response cognitoAction(String action, String body) { - return given() - .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) - .contentType(COGNITO_CONTENT_TYPE) - .body(body) - .when() - .post("/"); - } - - private static JsonNode cognitoJson(String action, String body) throws Exception { - String response = cognitoAction(action, body) - .then() - .statusCode(200) - .extract() - .asString(); - return OBJECT_MAPPER.readTree(response); - } - private static String base64Url(String raw) { return java.util.Base64.getUrlEncoder().withoutPadding() .encodeToString(raw.getBytes(java.nio.charset.StandardCharsets.UTF_8)); diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index 5a25e8ff5b..293ba1dc2a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java @@ -945,7 +945,7 @@ class KmsServiceTest { () -> kmsService.createKey("bad", null, Map.of(ReservedTags.OVERRIDE_ID_KEY, " "), REGION) ); - assertEquals("ValidationException", exception.getErrorCode()); + assertEquals("TagException", exception.getErrorCode()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java b/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java index 4f122540fa..daec30ce42 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java +++ b/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java @@ -1,5 +1,7 @@ package io.github.hectorvent.floci.testing; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.restassured.RestAssured; import io.restassured.config.EncoderConfig; import io.restassured.filter.Filter; @@ -9,6 +11,10 @@ import io.restassured.response.Response; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.FilterableResponseSpecification; +import static io.github.hectorvent.floci.core.common.AwsJson11Controller.CONTENT_TYPE_AWS_JSON_1_1; +import static io.github.hectorvent.floci.core.common.AwsJsonController.CONTENT_TYPE_AWS_JSON_1_0; +import static io.restassured.RestAssured.given; + /** * Registers a global RestAssured filter that rewrites AWS-specific JSON content types * to standard application/json before response parsing. @@ -22,10 +28,8 @@ import io.restassured.specification.FilterableResponseSpecification; */ public class RestAssuredJsonUtils { - private static final String AWS_CONTENT_TYPE_1_0 = "application/x-amz-json-1.0"; - private static final String AWS_CONTENT_TYPE_1_1 = "application/x-amz-json-1.1"; - private static final AwsContentTypeFilter AWS_CONTENT_TYPE_FILTER = new AwsContentTypeFilter(); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private RestAssuredJsonUtils() { // Utility class, prevent instantiation @@ -34,13 +38,32 @@ public class RestAssuredJsonUtils { public static void configureAwsContentTypes() { RestAssured.config = RestAssured.config().encoderConfig( EncoderConfig.encoderConfig() - .encodeContentTypeAs(AWS_CONTENT_TYPE_1_0, ContentType.JSON) - .encodeContentTypeAs(AWS_CONTENT_TYPE_1_1, ContentType.JSON)); + .encodeContentTypeAs(CONTENT_TYPE_AWS_JSON_1_0, ContentType.JSON) + .encodeContentTypeAs(CONTENT_TYPE_AWS_JSON_1_1, ContentType.JSON)); if (!RestAssured.filters().contains(AWS_CONTENT_TYPE_FILTER)) { RestAssured.filters(AWS_CONTENT_TYPE_FILTER); } } + + public static Response awsAction(String target, String action, String body) { + return given() + .header("X-Amz-Target", target + "." + action) + .contentType(CONTENT_TYPE_AWS_JSON_1_1) + .body(body) + .when() + .post("/"); + } + + public static JsonNode awsActionJson(String target, String action, String body) throws Exception { + String response = awsAction(target, action, body) + .then() + .statusCode(200) + .extract() + .asString(); + return OBJECT_MAPPER.readTree(response); + } + } /**