diff --git a/compatibility-tests/sdk-test-python/tests/test_cognito.py b/compatibility-tests/sdk-test-python/tests/test_cognito.py index edb0735efb..93c5ce3db2 100644 --- a/compatibility-tests/sdk-test-python/tests/test_cognito.py +++ b/compatibility-tests/sdk-test-python/tests/test_cognito.py @@ -1,6 +1,8 @@ """Cognito Identity Provider integration tests.""" +import boto3 import pytest +from botocore.config import Config class TestCognitoUserPool: @@ -31,6 +33,110 @@ class TestCognitoUserPool: class TestCognitoUserPoolClient: """Test Cognito user pool client operations.""" + @pytest.mark.parametrize("minutes", [3, 10, 15]) + def test_auth_session_validity_sdk_round_trip(self, cognito_client, unique_name, minutes): + """The SDK must send and parse the configured session duration.""" + pool_id = cognito_client.create_user_pool( + PoolName=f"session-validity-{unique_name}" + )["UserPool"]["Id"] + try: + created = cognito_client.create_user_pool_client( + UserPoolId=pool_id, ClientName="session-client", AuthSessionValidity=minutes + )["UserPoolClient"] + client_id = created["ClientId"] + assert created["AuthSessionValidity"] == minutes + assert cognito_client.describe_user_pool_client( + UserPoolId=pool_id, ClientId=client_id + )["UserPoolClient"]["AuthSessionValidity"] == minutes + + updated_minutes = 15 if minutes != 15 else 3 + updated = cognito_client.update_user_pool_client( + UserPoolId=pool_id, ClientId=client_id, AuthSessionValidity=updated_minutes + )["UserPoolClient"] + assert updated["AuthSessionValidity"] == updated_minutes + assert cognito_client.describe_user_pool_client( + UserPoolId=pool_id, ClientId=client_id + )["UserPoolClient"]["AuthSessionValidity"] == updated_minutes + + omitted = cognito_client.update_user_pool_client( + UserPoolId=pool_id, ClientId=client_id, ClientName="renamed" + )["UserPoolClient"] + assert omitted["AuthSessionValidity"] == updated_minutes + finally: + cognito_client.delete_user_pool(UserPoolId=pool_id) + + def test_auth_session_validity_sdk_default(self, cognito_client, unique_name): + """Omitting the duration creates a client with the 3-minute default.""" + pool_id = cognito_client.create_user_pool( + PoolName=f"session-default-{unique_name}" + )["UserPool"]["Id"] + try: + created = cognito_client.create_user_pool_client( + UserPoolId=pool_id, ClientName="default-client" + )["UserPoolClient"] + assert created["AuthSessionValidity"] == 3 + assert cognito_client.describe_user_pool_client( + UserPoolId=pool_id, ClientId=created["ClientId"] + )["UserPoolClient"]["AuthSessionValidity"] == 3 + finally: + cognito_client.delete_user_pool(UserPoolId=pool_id) + + @pytest.mark.parametrize( + "minutes,constraint", + [ + (2, "Member must have value greater than or equal to 3"), + (16, "Member must have value less than or equal to 15"), + ], + ) + def test_auth_session_validity_sdk_constraint_errors( + self, aws_config, client_config, unique_name, minutes, constraint + ): + """Disable SDK validation so the server's constraint errors reach the SDK.""" + client = boto3.client( + "cognito-idp", + config=client_config.merge(Config(parameter_validation=False)), + **aws_config, + ) + pool_id = None + try: + message = ( + f"1 validation error detected: Value '{minutes}' at 'authSessionValidity' " + f"failed to satisfy constraint: {constraint}" + ) + with pytest.raises(client.exceptions.InvalidParameterException) as missing: + client.create_user_pool_client( + UserPoolId="us-east-1_missing", + ClientName="missing-pool-client", + AuthSessionValidity=minutes, + ) + assert missing.value.response["Error"]["Message"] == message + + pool_id = client.create_user_pool( + PoolName=f"session-constraint-{unique_name}" + )["UserPool"]["Id"] + created = client.create_user_pool_client( + UserPoolId=pool_id, ClientName="session-client", AuthSessionValidity=10 + )["UserPoolClient"] + with pytest.raises(client.exceptions.InvalidParameterException) as rejected: + client.update_user_pool_client( + UserPoolId=pool_id, + ClientId=created["ClientId"], + ClientName="changed", + AuthSessionValidity=minutes, + ) + assert rejected.value.response["Error"]["Message"] == message + stored = client.describe_user_pool_client( + UserPoolId=pool_id, ClientId=created["ClientId"] + )["UserPoolClient"] + assert stored["AuthSessionValidity"] == 10 + assert stored["ClientName"] == "session-client" + finally: + try: + if pool_id is not None: + client.delete_user_pool(UserPoolId=pool_id) + finally: + client.close() + def test_create_user_pool_client(self, cognito_client, unique_name): """Test CreateUserPoolClient creates a client.""" pool_name = f"pytest-pool-{unique_name}" diff --git a/docs/services/cognito.md b/docs/services/cognito.md index ddde0c4179..2678535364 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -19,6 +19,14 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource` An action given a user pool ID that does not resolve returns `ResourceNotFoundException` with the live service's wording, `User pool does not exist.`, so tooling that matches Cognito error text behaves the same way locally. +`CreateUserPoolClient` and `UpdateUserPoolClient` store `AuthSessionValidity` in minutes, +and `DescribeUserPoolClient` returns it. Values must be integers from 3 through 15. +New clients default to 3 minutes; an update that omits the field retains its stored value. +An explicit JSON `null` behaves as an omitted field. Wrong JSON types or numbers +outside the 32-bit integer range return `SerializationException`. Integer durations +outside 3 through 15 return `InvalidParameterException` with Cognito's constraint-error +format. Validation runs before pool or client lookup. + ## Supported Actions ### User Pools 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 babbb23a0f..4cdf38c8cf 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 @@ -270,7 +270,8 @@ public class CognitoJsonHandler { : null, request.has("EnableTokenRevocation") ? request.path("EnableTokenRevocation").asBoolean() - : null + : null, + authSessionValidity(request) ); ObjectNode response = objectMapper.createObjectNode(); response.set("UserPoolClient", clientToNode(client)); @@ -334,7 +335,8 @@ public class CognitoJsonHandler { ? objectMapper.convertValue(request.path("RefreshTokenRotation"), new TypeReference>() {}) : null, - request.has("EnableTokenRevocation") ? request.path("EnableTokenRevocation").asBoolean() : null + request.has("EnableTokenRevocation") ? request.path("EnableTokenRevocation").asBoolean() : null, + authSessionValidity(request) ); ObjectNode response = objectMapper.createObjectNode(); response.set("UserPoolClient", clientToNode(client)); @@ -1140,6 +1142,7 @@ public class CognitoJsonHandler { node.put("ClientId", c.getClientId()); node.put("UserPoolId", c.getUserPoolId()); node.put("ClientName", c.getClientName()); + node.put("AuthSessionValidity", c.getAuthSessionValidity()); if (c.getClientSecret() != null) { node.put("ClientSecret", c.getClientSecret()); } @@ -1190,6 +1193,17 @@ public class CognitoJsonHandler { return node; } + private static Integer authSessionValidity(JsonNode request) { + JsonNode value = request.get("AuthSessionValidity"); + if (value == null || value.isNull()) { + return null; + } + if (!value.isIntegralNumber() || !value.canConvertToInt()) { + throw new AwsException("SerializationException", "Expected integer or null", 400); + } + return value.intValue(); + } + private ObjectNode resourceServerToNode(ResourceServer server) { ObjectNode node = objectMapper.createObjectNode(); node.put("UserPoolId", server.getUserPoolId()); 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 1a1b43ecb3..483747cb18 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 @@ -760,7 +760,26 @@ public class CognitoService implements ResourceProvider { List supportedIdentityProviders, Map tokenValidityUnits, List writeAttributes, Map refreshTokenRotation, Boolean enableTokenRevocation) { + return createUserPoolClient(userPoolId, clientName, generateSecret, allowedOAuthFlowsUserPoolClient, + allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs, + defaultRedirectURI, explicitAuthFlows, accessTokenValidity, idTokenValidity, + logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity, + supportedIdentityProviders, tokenValidityUnits, writeAttributes, refreshTokenRotation, + enableTokenRevocation, null); + } + 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, Integer authSessionValidity) { + + validateAuthSessionValidity(authSessionValidity); UserPool userPool = describeUserPool(userPoolId); String clientId = clientIdFor(userPool, clientName); List normalizedAllowedOAuthFlows = normalizeStringList(allowedOAuthFlows); @@ -802,6 +821,9 @@ public class CognitoService implements ResourceProvider { client.setExplicitAuthFlows(normalizedExplicitAuthFlows); client.setAccessTokenValidity(accessTokenValidity); client.setIdTokenValidity(idTokenValidity); + if (authSessionValidity != null) { + client.setAuthSessionValidity(authSessionValidity); + } client.setLogoutURLs(normalizedLogoutUrls); client.setPreventUserExistenceErrors(preventUserExistenceErrors); client.setReadAttributes(normalizedReadAttributes); @@ -938,6 +960,26 @@ public class CognitoService implements ResourceProvider { List writeAttributes, Map refreshTokenRotation, Boolean enableTokenRevocation) { + return updateUserPoolClient(userPoolId, clientId, clientName, allowedOAuthFlowsUserPoolClient, + allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs, + defaultRedirectURI, explicitAuthFlows, accessTokenValidity, idTokenValidity, + logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity, + supportedIdentityProviders, tokenValidityUnits, writeAttributes, refreshTokenRotation, + enableTokenRevocation, null); + } + + public UserPoolClient updateUserPoolClient(String userPoolId, String clientId, String clientName, + 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, Integer authSessionValidity) { + validateAuthSessionValidity(authSessionValidity); UserPoolClient client = describeUserPoolClient(userPoolId, clientId); boolean effectiveAllowedOAuthFlowsUserPoolClient = allowedOAuthFlowsUserPoolClient != null ? allowedOAuthFlowsUserPoolClient @@ -1038,6 +1080,9 @@ public class CognitoService implements ResourceProvider { if (enableTokenRevocation != null) { client.setEnableTokenRevocation(enableTokenRevocation); } + if (authSessionValidity != null) { + client.setAuthSessionValidity(authSessionValidity); + } client.setLastModifiedDate(System.currentTimeMillis() / 1000L); clientStore.put(clientId, client); @@ -1045,6 +1090,17 @@ public class CognitoService implements ResourceProvider { return client; } + private static void validateAuthSessionValidity(Integer authSessionValidity) { + if (authSessionValidity != null && (authSessionValidity < 3 || authSessionValidity > 15)) { + String constraint = authSessionValidity < 3 + ? "Member must have value greater than or equal to 3" + : "Member must have value less than or equal to 15"; + throw new AwsException("InvalidParameterException", + "1 validation error detected: Value '" + authSessionValidity + + "' at 'authSessionValidity' failed to satisfy constraint: " + constraint, 400); + } + } + public List listUserPoolClientSecrets(String userPoolId, String clientId) { UserPoolClient client = clientStore.get(clientId) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400)); 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 b3ec49f90a..6d032c01c6 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 @@ -25,6 +25,7 @@ public class UserPoolClient { private List explicitAuthFlows = new ArrayList<>(); private Integer accessTokenValidity; private Integer idTokenValidity; + private int authSessionValidity = 3; private List logoutURLs = new ArrayList<>(); private String preventUserExistenceErrors; private List readAttributes = new ArrayList<>(); @@ -99,6 +100,9 @@ public class UserPoolClient { public Integer getIdTokenValidity() { return idTokenValidity; } public void setIdTokenValidity(Integer idTokenValidity) { this.idTokenValidity = idTokenValidity; } + public int getAuthSessionValidity() { return authSessionValidity; } + public void setAuthSessionValidity(int authSessionValidity) { this.authSessionValidity = authSessionValidity; } + public List getLogoutURLs() { return logoutURLs; } public void setLogoutURLs(List logoutURLs) { this.logoutURLs = logoutURLs; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.java new file mode 100644 index 0000000000..515adfd1e3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.java @@ -0,0 +1,166 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +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 org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class CognitoAuthSessionValidityIntegrationTest { + + private String poolId; + + @BeforeAll + static void configureJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createPool() throws Exception { + poolId = cognitoJson("CreateUserPool", """ + {"PoolName":"session-validity-%s"} + """.formatted(UUID.randomUUID())).path("UserPool").path("Id").asText(); + } + + @AfterEach + void deletePool() { + cognitoAction("DeleteUserPool", """ + {"UserPoolId":"%s"} + """.formatted(poolId)).then().statusCode(200); + } + + @ParameterizedTest + @ValueSource(ints = {3, 10, 15}) + void createAndDescribeReturnConfiguredMinutes(int minutes) throws Exception { + JsonNode client = createClient(Integer.toString(minutes)); + assertEquals(minutes, client.path("AuthSessionValidity").asInt()); + assertEquals(minutes, describeClient(client.path("ClientId").asText()) + .path("AuthSessionValidity").asInt()); + } + + @ParameterizedTest + @ValueSource(ints = {3, 10, 15}) + void updateAndDescribeReturnConfiguredMinutes(int minutes) throws Exception { + String clientId = createClient("7").path("ClientId").asText(); + JsonNode updated = cognitoJson("UpdateUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"%s","AuthSessionValidity":%d} + """.formatted(poolId, clientId, minutes)).path("UserPoolClient"); + assertEquals(minutes, updated.path("AuthSessionValidity").asInt()); + assertEquals(minutes, describeClient(clientId).path("AuthSessionValidity").asInt()); + } + + @Test + void omittedCreateUsesDefaultAndOmittedUpdatePreservesConfiguredValue() throws Exception { + JsonNode defaultClient = cognitoJson("CreateUserPoolClient", """ + {"UserPoolId":"%s","ClientName":"default-client"} + """.formatted(poolId)).path("UserPoolClient"); + assertEquals(3, defaultClient.path("AuthSessionValidity").asInt()); + assertEquals(3, describeClient(defaultClient.path("ClientId").asText()) + .path("AuthSessionValidity").asInt()); + + String clientId = createClient("10").path("ClientId").asText(); + JsonNode updated = cognitoJson("UpdateUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"%s","ClientName":"renamed"} + """.formatted(poolId, clientId)).path("UserPoolClient"); + assertEquals(10, updated.path("AuthSessionValidity").asInt()); + assertEquals(10, describeClient(clientId).path("AuthSessionValidity").asInt()); + } + + @Test + void explicitNullHasTheSameMeaningAsAnOmittedValue() throws Exception { + JsonNode created = createClient("null"); + assertEquals(3, created.path("AuthSessionValidity").asInt()); + assertEquals(3, describeClient(created.path("ClientId").asText()) + .path("AuthSessionValidity").asInt()); + + String clientId = createClient("10").path("ClientId").asText(); + JsonNode updated = cognitoJson("UpdateUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"%s","ClientName":"renamed","AuthSessionValidity":null} + """.formatted(poolId, clientId)).path("UserPoolClient"); + assertEquals(10, updated.path("AuthSessionValidity").asInt()); + JsonNode stored = describeClient(clientId); + assertEquals(10, stored.path("AuthSessionValidity").asInt()); + assertEquals("renamed", stored.path("ClientName").asText()); + } + + @ParameterizedTest + @ValueSource(ints = {2, 16, -1, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}) + void rangeViolationsUseConstraintErrorsBeforeResourceLookupAndDoNotMutateClients(int value) throws Exception { + String constraint = value < 3 + ? "Member must have value greater than or equal to 3" + : "Member must have value less than or equal to 15"; + String message = "1 validation error detected: Value '" + value + + "' at 'authSessionValidity' failed to satisfy constraint: " + constraint; + assertRejectedWithoutMutatingClients(Integer.toString(value), "InvalidParameterException", message); + assertRejectedBeforeResourceLookup(Integer.toString(value), "InvalidParameterException", message); + } + + @ParameterizedTest + @ValueSource(strings = {"3.5", "\"10\"", "true", "{}", "[]", "2147483648", "-2147483649"}) + void nonIntegerValuesUseSerializationErrorsBeforeResourceLookupAndDoNotMutateClients(String value) throws Exception { + assertRejectedWithoutMutatingClients(value, "SerializationException", "Expected integer or null"); + assertRejectedBeforeResourceLookup(value, "SerializationException", "Expected integer or null"); + } + + private void assertRejectedWithoutMutatingClients(String value, String error, String message) throws Exception { + cognitoAction("CreateUserPoolClient", createRequest(value)) + .then().statusCode(400).body("__type", containsString(error)) + .body("message", equalTo(message)); + assertEquals(0, cognitoJson("ListUserPoolClients", """ + {"UserPoolId":"%s"} + """.formatted(poolId)).path("UserPoolClients").size()); + + String clientId = createClient("10").path("ClientId").asText(); + cognitoAction("UpdateUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"%s","ClientName":"changed","AuthSessionValidity":%s} + """.formatted(poolId, clientId, value)) + .then().statusCode(400).body("__type", containsString(error)) + .body("message", equalTo(message)); + JsonNode stored = describeClient(clientId); + assertEquals(10, stored.path("AuthSessionValidity").asInt()); + assertEquals("session-client", stored.path("ClientName").asText()); + } + + private void assertRejectedBeforeResourceLookup(String value, String error, String message) { + String missingPool = "us-east-1_missing"; + cognitoAction("CreateUserPoolClient", """ + {"UserPoolId":"%s","ClientName":"missing-pool-client","AuthSessionValidity":%s} + """.formatted(missingPool, value)).then().statusCode(400) + .body("__type", containsString(error)).body("message", equalTo(message)); + for (String requestedPool : new String[]{missingPool, poolId}) { + cognitoAction("UpdateUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"missing-client","AuthSessionValidity":%s} + """.formatted(requestedPool, value)).then().statusCode(400) + .body("__type", containsString(error)).body("message", equalTo(message)); + } + } + + private JsonNode createClient(String value) throws Exception { + return cognitoJson("CreateUserPoolClient", createRequest(value)).path("UserPoolClient"); + } + + private String createRequest(String value) { + return """ + {"UserPoolId":"%s","ClientName":"session-client","AuthSessionValidity":%s} + """.formatted(poolId, value); + } + + private JsonNode describeClient(String clientId) throws Exception { + return cognitoJson("DescribeUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"%s"} + """.formatted(poolId, clientId)).path("UserPoolClient"); + } +} 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 b3515c4bb9..5fe9f6d0fa 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 @@ -58,6 +58,17 @@ class CognitoServiceTest { private static final ObjectMapper MAPPER = new ObjectMapper(); + @Test + void authSessionValiditySurvivesSerializationAndDefaultsForLegacyClients() throws Exception { + UserPoolClient client = new UserPoolClient(); + client.setAuthSessionValidity(10); + UserPoolClient reloaded = MAPPER.readValue(MAPPER.writeValueAsBytes(client), UserPoolClient.class); + assertEquals(10, reloaded.getAuthSessionValidity()); + + UserPoolClient legacy = MAPPER.readValue("{\"clientId\":\"legacy\"}", UserPoolClient.class); + assertEquals(3, legacy.getAuthSessionValidity()); + } + private CognitoService service; private InMemoryStorage poolStore; private InMemoryStorage userStore;