fix(cognito): persist app client AuthSessionValidity (#4481)

* fix(cognito): persist app client AuthSessionValidity

* test(cognito): cover session validity through the SDK

* fix(cognito): align session validity validation with AWS errors
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-09-26 16:47:30 -05:00
1 parent 16a6c24e15
commit c0cb49facc
7 files changed
+367 -2

No files matched your search

@@ -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}"
+8
View File
@@ -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 <poolId> 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
@@ -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<Map<String, Object>>() {})
: 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());
@@ -760,7 +760,26 @@ public class CognitoService implements ResourceProvider {
List<String> supportedIdentityProviders, Map<String, String> tokenValidityUnits,
List<String> writeAttributes, Map<String, Object> 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<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
Map<String, Object> analyticsConfiguration, List<String> callbackURLs,
String defaultRedirectURI, List<String> explicitAuthFlows, Integer accessTokenValidity,
Integer idTokenValidity, List<String> logoutURLs, String preventUserExistenceErrors,
List<String> readAttributes, Integer refreshTokenValidity,
List<String> supportedIdentityProviders, Map<String, String> tokenValidityUnits,
List<String> writeAttributes, Map<String, Object> refreshTokenRotation,
Boolean enableTokenRevocation, Integer authSessionValidity) {
validateAuthSessionValidity(authSessionValidity);
UserPool userPool = describeUserPool(userPoolId);
String clientId = clientIdFor(userPool, clientName);
List<String> 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<String> writeAttributes,
Map<String, Object> 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<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
Map<String, Object> analyticsConfiguration, List<String> callbackURLs,
String defaultRedirectURI, List<String> explicitAuthFlows,
Integer accessTokenValidity, Integer idTokenValidity,
List<String> logoutURLs, String preventUserExistenceErrors,
List<String> readAttributes, Integer refreshTokenValidity,
List<String> supportedIdentityProviders, Map<String, String> tokenValidityUnits,
List<String> writeAttributes, Map<String, Object> 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<UserPoolClientSecret> listUserPoolClientSecrets(String userPoolId, String clientId) {
UserPoolClient client = clientStore.get(clientId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));
@@ -25,6 +25,7 @@ public class UserPoolClient {
private List<String> explicitAuthFlows = new ArrayList<>();
private Integer accessTokenValidity;
private Integer idTokenValidity;
private int authSessionValidity = 3;
private List<String> logoutURLs = new ArrayList<>();
private String preventUserExistenceErrors;
private List<String> 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<String> getLogoutURLs() { return logoutURLs; }
public void setLogoutURLs(List<String> logoutURLs) { this.logoutURLs = logoutURLs; }
@@ -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");
}
}
@@ -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<String, UserPool> poolStore;
private InMemoryStorage<String, CognitoUser> userStore;