diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index 27da76d8f1..e91da7ffd3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -239,9 +239,9 @@ final class CognitoAuthFlowHandler { CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, "TokenGeneration_RefreshTokens"); Map auth = new HashMap<>(); - auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", tokenClientId, override)); - auth.put("IdToken", service.generateSignedJwt(user, pool, "id", tokenClientId, override)); - auth.put("ExpiresIn", 3600); + auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override)); + auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override)); + auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client)); auth.put("TokenType", "Bearer"); Map result = new HashMap<>(); result.put("AuthenticationResult", auth); @@ -249,9 +249,9 @@ final class CognitoAuthFlowHandler { } catch (AwsException ignored) { } } Map auth = new HashMap<>(); - auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client.getClientId())); - auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client.getClientId())); - auth.put("ExpiresIn", 3600); + auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client)); + auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client)); + auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client)); auth.put("TokenType", "Bearer"); Map result = new HashMap<>(); result.put("AuthenticationResult", auth); @@ -934,7 +934,7 @@ final class CognitoAuthFlowHandler { String triggerSource, Map clientMetadata) { firePostAuthentication(pool, client, user, clientMetadata, false); CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource); - return service.generateAuthResult(user, pool, client.getClientId(), override); + return service.generateAuthResult(user, pool, client, override); } CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user) { 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 2e4724b832..8b7c9fe26a 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 @@ -186,7 +186,35 @@ public class CognitoJsonHandler { request.path("GenerateSecret").asBoolean(false), request.path("AllowedOAuthFlowsUserPoolClient").asBoolean(false), readStringList(request.path("AllowedOAuthFlows")), - readStringList(request.path("AllowedOAuthScopes")) + readStringList(request.path("AllowedOAuthScopes")), + request.path("AnalyticsConfiguration").isObject() + ? objectMapper.convertValue(request.path("AnalyticsConfiguration"), + new TypeReference>() {}) + : null, + readStringList(request.path("CallbackURLs")), + request.path("DefaultRedirectURI").asText(null), + readStringList(request.path("ExplicitAuthFlows")), + request.has("AccessTokenValidity") ? request.path("AccessTokenValidity").asInt() + : null, + request.has("IdTokenValidity") ? request.path("IdTokenValidity").asInt() : null, + readStringList(request.path("LogoutURLs")), + request.path("PreventUserExistenceErrors").asText(null), + readStringList(request.path("ReadAttributes")), + request.has("RefreshTokenValidity") ? request.path("RefreshTokenValidity").asInt() + : null, + readStringList(request.path("SupportedIdentityProviders")), + request.path("TokenValidityUnits").isObject() + ? objectMapper.convertValue(request.path("TokenValidityUnits"), + new TypeReference>() {}) + : null, + readStringList(request.path("WriteAttributes")), + request.path("RefreshTokenRotation").isObject() + ? objectMapper.convertValue(request.path("RefreshTokenRotation"), + new TypeReference>() {}) + : null, + request.has("EnableTokenRevocation") + ? request.path("EnableTokenRevocation").asBoolean() + : null ); ObjectNode response = objectMapper.createObjectNode(); response.set("UserPoolClient", clientToNode(client)); @@ -225,8 +253,32 @@ public class CognitoJsonHandler { request.path("ClientId").asText(), request.has("ClientName") ? request.path("ClientName").asText() : null, request.has("AllowedOAuthFlowsUserPoolClient") ? request.path("AllowedOAuthFlowsUserPoolClient").asBoolean() : null, - readStringList(request.path("AllowedOAuthFlows")), - readStringList(request.path("AllowedOAuthScopes")) + request.has("AllowedOAuthFlows") ? readStringList(request.path("AllowedOAuthFlows")) : null, + request.has("AllowedOAuthScopes") ? readStringList(request.path("AllowedOAuthScopes")) : null, + request.path("AnalyticsConfiguration").isObject() + ? objectMapper.convertValue(request.path("AnalyticsConfiguration"), + new TypeReference>() {}) + : null, + request.has("CallbackURLs") ? readStringList(request.path("CallbackURLs")) : null, + request.has("DefaultRedirectURI") ? request.path("DefaultRedirectURI").asText(null) : null, + request.has("ExplicitAuthFlows") ? readStringList(request.path("ExplicitAuthFlows")) : null, + request.has("AccessTokenValidity") ? request.path("AccessTokenValidity").asInt() : null, + request.has("IdTokenValidity") ? request.path("IdTokenValidity").asInt() : null, + request.has("LogoutURLs") ? readStringList(request.path("LogoutURLs")) : null, + request.has("PreventUserExistenceErrors") ? request.path("PreventUserExistenceErrors").asText(null) : null, + request.has("ReadAttributes") ? readStringList(request.path("ReadAttributes")) : null, + request.has("RefreshTokenValidity") ? request.path("RefreshTokenValidity").asInt() : null, + request.has("SupportedIdentityProviders") ? readStringList(request.path("SupportedIdentityProviders")) : null, + request.path("TokenValidityUnits").isObject() + ? objectMapper.convertValue(request.path("TokenValidityUnits"), + new TypeReference>() {}) + : null, + request.has("WriteAttributes") ? readStringList(request.path("WriteAttributes")) : null, + request.path("RefreshTokenRotation").isObject() + ? objectMapper.convertValue(request.path("RefreshTokenRotation"), + new TypeReference>() {}) + : null, + request.has("EnableTokenRevocation") ? request.path("EnableTokenRevocation").asBoolean() : null ); ObjectNode response = objectMapper.createObjectNode(); response.set("UserPoolClient", clientToNode(client)); @@ -577,15 +629,15 @@ public class CognitoJsonHandler { node.set("AutoVerifiedAttributes", objectMapper.valueToTree(p.getAutoVerifiedAttributes() != null ? p.getAutoVerifiedAttributes() : new java.util.ArrayList<>())); node.set("AliasAttributes", objectMapper.valueToTree(p.getAliasAttributes() != null ? p.getAliasAttributes() : new java.util.ArrayList<>())); node.set("UsernameAttributes", objectMapper.valueToTree(p.getUsernameAttributes() != null ? p.getUsernameAttributes() : new java.util.ArrayList<>())); - + if (p.getSmsVerificationMessage() != null) node.put("SmsVerificationMessage", p.getSmsVerificationMessage()); if (p.getEmailVerificationMessage() != null) node.put("EmailVerificationMessage", p.getEmailVerificationMessage()); if (p.getEmailVerificationSubject() != null) node.put("EmailVerificationSubject", p.getEmailVerificationSubject()); - + node.set("VerificationMessageTemplate", objectMapper.valueToTree(p.getVerificationMessageTemplate() != null ? p.getVerificationMessageTemplate() : new HashMap<>())); - + if (p.getSmsAuthenticationMessage() != null) node.put("SmsAuthenticationMessage", p.getSmsAuthenticationMessage()); - + node.put("MfaConfiguration", p.getMfaConfiguration() != null ? p.getMfaConfiguration() : "OFF"); node.set("DeviceConfiguration", objectMapper.valueToTree(p.getDeviceConfiguration() != null ? p.getDeviceConfiguration() : new HashMap<>())); node.put("EstimatedNumberOfUsers", p.getEstimatedNumberOfUsers()); @@ -623,6 +675,42 @@ public class CognitoJsonHandler { c.getAllowedOAuthFlows().forEach(flows::add); ArrayNode scopes = node.putArray("AllowedOAuthScopes"); c.getAllowedOAuthScopes().forEach(scopes::add); + node.set("AnalyticsConfiguration", objectMapper.valueToTree( + c.getAnalyticsConfiguration() != null ? c.getAnalyticsConfiguration() : new HashMap<>())); + ArrayNode callbackUrls = node.putArray("CallbackURLs"); + c.getCallbackURLs().forEach(callbackUrls::add); + if (c.getDefaultRedirectURI() != null) { + node.put("DefaultRedirectURI", c.getDefaultRedirectURI()); + } + ArrayNode explicitAuthFlows = node.putArray("ExplicitAuthFlows"); + c.getExplicitAuthFlows().forEach(explicitAuthFlows::add); + if (c.getAccessTokenValidity() != null) { + node.put("AccessTokenValidity", c.getAccessTokenValidity()); + } + if (c.getIdTokenValidity() != null) { + node.put("IdTokenValidity", c.getIdTokenValidity()); + } + ArrayNode logoutUrls = node.putArray("LogoutURLs"); + c.getLogoutURLs().forEach(logoutUrls::add); + if (c.getPreventUserExistenceErrors() != null) { + node.put("PreventUserExistenceErrors", c.getPreventUserExistenceErrors()); + } + ArrayNode readAttributes = node.putArray("ReadAttributes"); + c.getReadAttributes().forEach(readAttributes::add); + if (c.getRefreshTokenValidity() != null) { + node.put("RefreshTokenValidity", c.getRefreshTokenValidity()); + } + ArrayNode supportedIdentityProviders = node.putArray("SupportedIdentityProviders"); + c.getSupportedIdentityProviders().forEach(supportedIdentityProviders::add); + node.set("TokenValidityUnits", objectMapper.valueToTree( + c.getTokenValidityUnits() != null ? c.getTokenValidityUnits() : new HashMap<>())); + ArrayNode writeAttributes = node.putArray("WriteAttributes"); + c.getWriteAttributes().forEach(writeAttributes::add); + node.set("RefreshTokenRotation", objectMapper.valueToTree( + c.getRefreshTokenRotation() != null ? c.getRefreshTokenRotation() : new HashMap<>())); + if (c.getEnableTokenRevocation() != null) { + node.put("EnableTokenRevocation", c.getEnableTokenRevocation()); + } node.put("CreationDate", c.getCreationDate()); node.put("LastModifiedDate", c.getLastModifiedDate()); return node; diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index c1c4c57857..a6d24c321a 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 @@ -286,6 +286,22 @@ public class CognitoService { boolean allowedOAuthFlowsUserPoolClient, List allowedOAuthFlows, List allowedOAuthScopes) { + return createUserPoolClient(userPoolId, clientName, generateSecret, + allowedOAuthFlowsUserPoolClient, allowedOAuthFlows, allowedOAuthScopes, null, + List.of(), null, List.of(), null, null, List.of(), null, List.of(), null, null, + null, List.of(), null, 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) { describeUserPool(userPoolId); String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26); UserPoolClient client = new UserPoolClient(); @@ -296,6 +312,24 @@ public class CognitoService { client.setAllowedOAuthFlowsUserPoolClient(allowedOAuthFlowsUserPoolClient); client.setAllowedOAuthFlows(normalizeStringList(allowedOAuthFlows)); client.setAllowedOAuthScopes(normalizeStringList(allowedOAuthScopes)); + client.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration)); + client.setCallbackURLs(normalizeStringList(callbackURLs)); + client.setDefaultRedirectURI(defaultRedirectURI); + client.setExplicitAuthFlows(normalizeStringList(explicitAuthFlows)); + client.setAccessTokenValidity(accessTokenValidity); + client.setIdTokenValidity(idTokenValidity); + client.setLogoutURLs(normalizeStringList(logoutURLs)); + client.setPreventUserExistenceErrors(preventUserExistenceErrors); + client.setReadAttributes(normalizeStringList(readAttributes)); + client.setRefreshTokenValidity(refreshTokenValidity); + List normalizedSupportedIdentityProviders = normalizeStringList(supportedIdentityProviders); + client.setSupportedIdentityProviders(normalizedSupportedIdentityProviders.isEmpty() + ? List.of("COGNITO") + : normalizedSupportedIdentityProviders); + client.setTokenValidityUnits(copyStringMap(tokenValidityUnits)); + client.setWriteAttributes(normalizeStringList(writeAttributes)); + client.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation)); + client.setEnableTokenRevocation(enableTokenRevocation != null ? enableTokenRevocation : Boolean.TRUE); if (generateSecret) { String clientSecret = generateSecretValue(); client.setClientSecret(clientSecret); @@ -341,6 +375,50 @@ public class CognitoService { Boolean allowedOAuthFlowsUserPoolClient, List allowedOAuthFlows, List allowedOAuthScopes) { + return updateUserPoolClient( + userPoolId, + clientId, + clientName, + allowedOAuthFlowsUserPoolClient, + allowedOAuthFlows, + allowedOAuthScopes, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + 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) { UserPoolClient client = describeUserPoolClient(userPoolId, clientId); if (clientName != null) client.setClientName(clientName); if (allowedOAuthFlowsUserPoolClient != null) { @@ -352,6 +430,51 @@ public class CognitoService { if (allowedOAuthScopes != null) { client.setAllowedOAuthScopes(normalizeStringList(allowedOAuthScopes)); } + if (analyticsConfiguration != null) { + client.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration)); + } + if (callbackURLs != null) { + client.setCallbackURLs(normalizeStringList(callbackURLs)); + } + if (defaultRedirectURI != null) { + client.setDefaultRedirectURI(defaultRedirectURI); + } + if (explicitAuthFlows != null) { + client.setExplicitAuthFlows(normalizeStringList(explicitAuthFlows)); + } + if (accessTokenValidity != null) { + client.setAccessTokenValidity(accessTokenValidity); + } + if (idTokenValidity != null) { + client.setIdTokenValidity(idTokenValidity); + } + if (logoutURLs != null) { + client.setLogoutURLs(normalizeStringList(logoutURLs)); + } + if (preventUserExistenceErrors != null) { + client.setPreventUserExistenceErrors(preventUserExistenceErrors); + } + if (readAttributes != null) { + client.setReadAttributes(normalizeStringList(readAttributes)); + } + if (refreshTokenValidity != null) { + client.setRefreshTokenValidity(refreshTokenValidity); + } + if (supportedIdentityProviders != null) { + client.setSupportedIdentityProviders(normalizeStringList(supportedIdentityProviders)); + } + if (tokenValidityUnits != null) { + client.setTokenValidityUnits(copyStringMap(tokenValidityUnits)); + } + if (writeAttributes != null) { + client.setWriteAttributes(normalizeStringList(writeAttributes)); + } + if (refreshTokenRotation != null) { + client.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation)); + } + if (enableTokenRevocation != null) { + client.setEnableTokenRevocation(enableTokenRevocation); + } client.setLastModifiedDate(System.currentTimeMillis() / 1000L); clientStore.put(clientId, client); @@ -1010,7 +1133,7 @@ public class CognitoService { Map response = new LinkedHashMap<>(); response.put("access_token", generateClientAccessToken(client, pool, normalizedScope)); response.put("token_type", "Bearer"); - response.put("expires_in", 3600); + response.put("expires_in", resolveAccessTokenLifetimeSeconds(client)); return response; } @@ -1078,32 +1201,36 @@ public class CognitoService { if (!client.getUserPoolId().equals(poolId)) { throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400); } + if (isRefreshTokenExpired(client, parts)) { + throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400); + } UserPool pool = describeUserPool(poolId); CognitoUser user = adminGetUser(poolId, username); ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user); Map auth = new HashMap<>(); - auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId, override)); - auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId, override)); - auth.put("ExpiresIn", 3600); + auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override)); + auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override)); + auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client)); auth.put("TokenType", "Bearer"); Map result = new HashMap<>(); result.put("AuthenticationResult", auth); return result; } - Map generateAuthResult(CognitoUser user, UserPool pool, String clientId, ClaimsOverride override) { + Map generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override) { Map auth = new HashMap<>(); - auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId, override)); - auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId, override)); - auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), clientId)); - auth.put("ExpiresIn", 3600); + auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override)); + auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override)); + auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), client.getClientId())); + auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client)); auth.put("TokenType", "Bearer"); return auth; } - String generateSignedJwt(CognitoUser user, UserPool pool, String type, String clientId, ClaimsOverride override) { + String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override) { String header = encodeJwtHeader(pool); long now = System.currentTimeMillis() / 1000L; + long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type); Map claims = new LinkedHashMap<>(); String sub = user.getAttributes().getOrDefault("sub", user.getUsername()); @@ -1113,11 +1240,12 @@ public class CognitoService { claims.put("token_use", type); claims.put("auth_time", now); claims.put("iss", getIssuer(pool.getId())); - claims.put("exp", now + 3600); + claims.put("exp", now + lifetimeSeconds); claims.put("iat", now); claims.put("username", user.getUsername()); claims.put("email", email); claims.put("cognito:username", user.getUsername()); + String clientId = client != null ? client.getClientId() : null; if (clientId != null && !clientId.isBlank()) { if ("access".equals(type)) claims.put("client_id", clientId); if ("id".equals(type)) claims.put("aud", clientId); @@ -1202,20 +1330,22 @@ public class CognitoService { } } - String generateTokenString(String type, String username, UserPool pool, String clientId) { + String generateTokenString(String type, String username, UserPool pool, UserPoolClient client) { long now = System.currentTimeMillis() / 1000L; + long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type); String headerJson = String.format( "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", escapeJson(getSigningKeyId(pool))); String header = Base64.getUrlEncoder().withoutPadding() .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8)); + String clientId = client != null ? client.getClientId() : null; String audFragment = (clientId != null && !clientId.isBlank() && "id".equals(type)) ? ",\"aud\":\"" + escapeJson(clientId) + "\"" : ""; String payloadJson = String.format( "{\"sub\":\"%s\",\"token_use\":\"%s\",\"iss\":\"%s\"," + "\"exp\":%d,\"iat\":%d,\"username\":\"%s\"%s}", - UUID.randomUUID(), type, escapeJson(getIssuer(pool.getId())), now + 3600, now, username, audFragment + UUID.randomUUID(), type, escapeJson(getIssuer(pool.getId())), now + lifetimeSeconds, now, username, audFragment ); String payload = Base64.getUrlEncoder().withoutPadding() .encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8)); @@ -1230,6 +1360,7 @@ public class CognitoService { .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8)); long now = System.currentTimeMillis() / 1000L; + long lifetimeSeconds = resolveAccessTokenLifetimeSeconds(client); StringBuilder payloadJson = new StringBuilder(); payloadJson.append("{") .append("\"iss\":\"").append(escapeJson(getIssuer(pool.getId()))).append("\",") @@ -1237,7 +1368,7 @@ public class CognitoService { .append("\"sub\":\"").append(escapeJson(client.getClientId())).append("\",") .append("\"client_id\":\"").append(escapeJson(client.getClientId())).append("\",") .append("\"token_use\":\"access\",") - .append("\"exp\":").append(now + 3600).append(",") + .append("\"exp\":").append(now + lifetimeSeconds).append(",") .append("\"iat\":").append(now).append(",") .append("\"jti\":\"").append(UUID.randomUUID()).append("\""); if (scope != null && !scope.isBlank()) { @@ -1331,6 +1462,20 @@ public class CognitoService { return normalized.isEmpty() ? null : String.join(" ", normalized); } + private Map copyObjectMap(Map source) { + if (source == null || source.isEmpty()) { + return null; + } + return new LinkedHashMap<>(source); + } + + private Map copyStringMap(Map source) { + if (source == null || source.isEmpty()) { + return null; + } + return new LinkedHashMap<>(source); + } + private List normalizeScopes(List scopes) { if (scopes == null || scopes.isEmpty()) { return List.of(); @@ -1488,8 +1633,83 @@ public class CognitoService { user.setSrpVerifier(verifierHex); } + int getAccessTokenExpiresInSeconds(UserPoolClient client) { + return resolveAccessTokenLifetimeSeconds(client); + } + + private int resolveAccessTokenLifetimeSeconds(UserPoolClient client) { + return resolveTokenLifetimeSeconds(client, "access"); + } + + private int resolveTokenLifetimeSeconds(UserPoolClient client, String tokenType) { + String normalizedType = tokenType == null ? "" : tokenType.toLowerCase(Locale.ROOT); + int defaultValue; + String defaultUnit; + Integer configuredValue; + if ("refresh".equals(normalizedType)) { + defaultValue = 30; + defaultUnit = "days"; + configuredValue = client != null ? client.getRefreshTokenValidity() : null; + } else if ("id".equals(normalizedType)) { + defaultValue = 1; + defaultUnit = "hours"; + configuredValue = client != null ? client.getIdTokenValidity() : null; + } else { + defaultValue = 1; + defaultUnit = "hours"; + configuredValue = client != null ? client.getAccessTokenValidity() : null; + } + + int value = configuredValue == null ? defaultValue : configuredValue; + if ("refresh".equals(normalizedType) && value == 0) { + value = defaultValue; + } else if (value <= 0) { + value = defaultValue; + } + String unit = resolveTokenValidityUnit(client, normalizedType, defaultUnit); + long seconds = switch (unit) { + case "seconds" -> value; + case "minutes" -> value * 60L; + case "hours" -> value * 3600L; + case "days" -> value * 86400L; + default -> throw new AwsException("InvalidParameterException", "Unsupported token validity unit: " + unit, 400); + }; + if (seconds > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + return (int) seconds; + } + + private String resolveTokenValidityUnit(UserPoolClient client, String tokenType, String defaultUnit) { + Map units = client != null ? client.getTokenValidityUnits() : null; + if (units == null || units.isEmpty()) { + return defaultUnit; + } + String key = switch (tokenType) { + case "refresh" -> "RefreshToken"; + case "id" -> "IdToken"; + default -> "AccessToken"; + }; + String configured = units.get(key); + return configured == null || configured.isBlank() ? defaultUnit : configured.trim().toLowerCase(Locale.ROOT); + } + + private boolean isRefreshTokenExpired(UserPoolClient client, String[] parts) { + if (parts.length < 5) { + return false; + } + try { + long issuedAt = Long.parseLong(parts[3]); + long expiresAt = issuedAt + resolveTokenLifetimeSeconds(client, "refresh"); + return System.currentTimeMillis() / 1000L >= expiresAt; + } catch (NumberFormatException ignored) { + return false; + } + } + String buildRefreshToken(String poolId, String username, String clientId) { - String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID(); + long issuedAt = System.currentTimeMillis() / 1000L; + String raw = poolId + "|" + username + "|" + clientId + "|" + issuedAt + "|" + UUID.randomUUID(); return Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); } @@ -1497,9 +1717,12 @@ public class CognitoService { try { byte[] decoded = Base64.getDecoder().decode(refreshToken); String raw = new String(decoded, StandardCharsets.UTF_8); - String[] parts = raw.split("\\|", 4); + String[] parts = raw.split("\\|", 5); + if (parts.length == 5) { + return parts; // [poolId, username, clientId, issuedAt, nonce] + } if (parts.length == 4) { - return parts; // [poolId, username, clientId, nonce] + return new String[] { parts[0], parts[1], parts[2], "", parts[3] }; } } catch (Exception ignored) { } return null; 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 271f3c1d52..6554cf8f0e 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 @@ -5,6 +5,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.ArrayList; import java.util.List; +import java.util.Map; @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @@ -18,6 +19,21 @@ public class UserPoolClient { private boolean allowedOAuthFlowsUserPoolClient; private List allowedOAuthFlows = new ArrayList<>(); private List allowedOAuthScopes = new ArrayList<>(); + private Map analyticsConfiguration; + private List callbackURLs = new ArrayList<>(); + private String defaultRedirectURI; + private List explicitAuthFlows = new ArrayList<>(); + private Integer accessTokenValidity; + private Integer idTokenValidity; + private List logoutURLs = new ArrayList<>(); + private String preventUserExistenceErrors; + private List readAttributes = new ArrayList<>(); + private Integer refreshTokenValidity; + private List supportedIdentityProviders = new ArrayList<>(); + private Map tokenValidityUnits; + private List writeAttributes = new ArrayList<>(); + private Map refreshTokenRotation; + private Boolean enableTokenRevocation; private long creationDate; private long lastModifiedDate; @@ -60,6 +76,61 @@ public class UserPoolClient { public List getAllowedOAuthScopes() { return allowedOAuthScopes; } public void setAllowedOAuthScopes(List allowedOAuthScopes) { this.allowedOAuthScopes = allowedOAuthScopes; } + public Map getAnalyticsConfiguration() { return analyticsConfiguration; } + public void setAnalyticsConfiguration(Map analyticsConfiguration) { + this.analyticsConfiguration = analyticsConfiguration; + } + + public List getCallbackURLs() { return callbackURLs; } + public void setCallbackURLs(List callbackURLs) { this.callbackURLs = callbackURLs; } + + public String getDefaultRedirectURI() { return defaultRedirectURI; } + public void setDefaultRedirectURI(String defaultRedirectURI) { this.defaultRedirectURI = defaultRedirectURI; } + + public List getExplicitAuthFlows() { return explicitAuthFlows; } + public void setExplicitAuthFlows(List explicitAuthFlows) { this.explicitAuthFlows = explicitAuthFlows; } + + public Integer getAccessTokenValidity() { return accessTokenValidity; } + public void setAccessTokenValidity(Integer accessTokenValidity) { this.accessTokenValidity = accessTokenValidity; } + + public Integer getIdTokenValidity() { return idTokenValidity; } + public void setIdTokenValidity(Integer idTokenValidity) { this.idTokenValidity = idTokenValidity; } + + public List getLogoutURLs() { return logoutURLs; } + public void setLogoutURLs(List logoutURLs) { this.logoutURLs = logoutURLs; } + + public String getPreventUserExistenceErrors() { return preventUserExistenceErrors; } + public void setPreventUserExistenceErrors(String preventUserExistenceErrors) { + this.preventUserExistenceErrors = preventUserExistenceErrors; + } + + public List getReadAttributes() { return readAttributes; } + public void setReadAttributes(List readAttributes) { this.readAttributes = readAttributes; } + + public Integer getRefreshTokenValidity() { return refreshTokenValidity; } + public void setRefreshTokenValidity(Integer refreshTokenValidity) { this.refreshTokenValidity = refreshTokenValidity; } + + public List getSupportedIdentityProviders() { return supportedIdentityProviders; } + public void setSupportedIdentityProviders(List supportedIdentityProviders) { + this.supportedIdentityProviders = supportedIdentityProviders; + } + + public Map getTokenValidityUnits() { return tokenValidityUnits; } + public void setTokenValidityUnits(Map tokenValidityUnits) { this.tokenValidityUnits = tokenValidityUnits; } + + public List getWriteAttributes() { return writeAttributes; } + public void setWriteAttributes(List writeAttributes) { this.writeAttributes = writeAttributes; } + + public Map getRefreshTokenRotation() { return refreshTokenRotation; } + public void setRefreshTokenRotation(Map refreshTokenRotation) { + this.refreshTokenRotation = refreshTokenRotation; + } + + public Boolean getEnableTokenRevocation() { return enableTokenRevocation; } + public void setEnableTokenRevocation(Boolean enableTokenRevocation) { + this.enableTokenRevocation = enableTokenRevocation; + } + public long getCreationDate() { return creationDate; } public void setCreationDate(long creationDate) { this.creationDate = creationDate; } 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 2b2c41af8c..e6ec589171 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 @@ -1514,6 +1514,253 @@ class CognitoIntegrationTest { assertFalse(hasGenderAfterDelete, "custom:gender should be deleted"); } + // ========================================================================= + // Issue #1306 — User pool client extended configuration and token validity + // ========================================================================= + + @Test + @Order(95) + void userPoolClientPersistsExtendedConfigurationFields() throws Exception { + JsonNode poolResponse = cognitoJson("CreateUserPool", """ + { + "PoolName": "ExtendedClientPool" + } + """); + String extendedPoolId = poolResponse.path("UserPool").path("Id").asText(); + + JsonNode createResp = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "extended-client", + "GenerateSecret": true, + "AllowedOAuthFlowsUserPoolClient": true, + "AllowedOAuthFlows": ["code"], + "AllowedOAuthScopes": ["aws.cognito.signin.user.admin", "openid"], + "AnalyticsConfiguration": { + "ApplicationId": "d70b2ba36a8c4dc5a04a0451a31a1e12", + "ExternalId": "my-external-id", + "RoleArn": "arn:aws:iam::123456789012:role/test-cognitouserpool-role", + "UserDataShared": true + }, + "CallbackURLs": ["https://example.com", "http://localhost", "myapp://example"], + "DefaultRedirectURI": "https://example.com", + "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"], + "AccessTokenValidity": 15, + "IdTokenValidity": 20, + "LogoutURLs": ["https://example.com/logout"], + "ReadAttributes": ["email", "address", "preferred_username"], + "RefreshTokenValidity": 7, + "TokenValidityUnits": { + "AccessToken": "minutes", + "IdToken": "minutes", + "RefreshToken": "days" + }, + "RefreshTokenRotation": { + "Feature": "ENABLED", + "RetryGracePeriodSeconds": 30 + }, + "EnableTokenRevocation": true, + "PreventUserExistenceErrors": "ENABLED", + "SupportedIdentityProviders": ["COGNITO", "Google"], + "WriteAttributes": ["family_name", "email"] + } + """.formatted(extendedPoolId)); + + JsonNode created = createResp.path("UserPoolClient"); + String extendedClientId = created.path("ClientId").asText(); + assertTrue(created.path("AllowedOAuthFlowsUserPoolClient").asBoolean()); + assertEquals(1, created.path("AllowedOAuthFlows").size()); + assertEquals("code", created.path("AllowedOAuthFlows").get(0).asText()); + assertEquals(2, created.path("AllowedOAuthScopes").size()); + assertEquals("d70b2ba36a8c4dc5a04a0451a31a1e12", + created.path("AnalyticsConfiguration").path("ApplicationId").asText()); + assertEquals("my-external-id", created.path("AnalyticsConfiguration").path("ExternalId").asText()); + assertEquals("arn:aws:iam::123456789012:role/test-cognitouserpool-role", + created.path("AnalyticsConfiguration").path("RoleArn").asText()); + assertTrue(created.path("AnalyticsConfiguration").path("UserDataShared").asBoolean()); + assertEquals(3, created.path("CallbackURLs").size()); + assertEquals("https://example.com", created.path("DefaultRedirectURI").asText()); + assertEquals(2, created.path("ExplicitAuthFlows").size()); + assertEquals(15, created.path("AccessTokenValidity").asInt()); + assertEquals(20, created.path("IdTokenValidity").asInt()); + assertEquals(1, created.path("LogoutURLs").size()); + assertEquals(3, created.path("ReadAttributes").size()); + assertEquals(7, created.path("RefreshTokenValidity").asInt()); + assertEquals("minutes", created.path("TokenValidityUnits").path("AccessToken").asText()); + assertEquals("minutes", created.path("TokenValidityUnits").path("IdToken").asText()); + assertEquals("days", created.path("TokenValidityUnits").path("RefreshToken").asText()); + assertEquals("ENABLED", created.path("RefreshTokenRotation").path("Feature").asText()); + assertEquals(30, created.path("RefreshTokenRotation").path("RetryGracePeriodSeconds").asInt()); + assertTrue(created.path("EnableTokenRevocation").asBoolean()); + assertEquals("ENABLED", created.path("PreventUserExistenceErrors").asText()); + assertEquals(2, created.path("SupportedIdentityProviders").size()); + assertEquals(2, created.path("WriteAttributes").size()); + + cognitoJson("UpdateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientId": "%s", + "AllowedOAuthFlowsUserPoolClient": false, + "AllowedOAuthFlows": ["implicit"], + "AllowedOAuthScopes": ["email"], + "AnalyticsConfiguration": { + "ApplicationId": "updated-app-id", + "ExternalId": "updated-external-id", + "RoleArn": "arn:aws:iam::123456789012:role/updated-role", + "UserDataShared": false + }, + "CallbackURLs": ["https://updated.example.com/callback"], + "DefaultRedirectURI": "https://updated.example.com/callback", + "ExplicitAuthFlows": ["ALLOW_USER_SRP_AUTH"], + "AccessTokenValidity": 25, + "IdTokenValidity": 30, + "LogoutURLs": ["https://updated.example.com/logout"], + "ReadAttributes": ["email"], + "RefreshTokenValidity": 14, + "TokenValidityUnits": { + "AccessToken": "minutes", + "IdToken": "minutes", + "RefreshToken": "days" + }, + "RefreshTokenRotation": { + "Feature": "DISABLED", + "RetryGracePeriodSeconds": 0 + }, + "EnableTokenRevocation": false, + "PreventUserExistenceErrors": "LEGACY", + "SupportedIdentityProviders": ["COGNITO"], + "WriteAttributes": ["email"] + } + """.formatted(extendedPoolId, extendedClientId)); + + JsonNode describeResp = cognitoJson("DescribeUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientId": "%s" + } + """.formatted(extendedPoolId, extendedClientId)); + JsonNode described = describeResp.path("UserPoolClient"); + + assertFalse(described.path("AllowedOAuthFlowsUserPoolClient").asBoolean()); + assertEquals(1, described.path("AllowedOAuthFlows").size()); + assertEquals("implicit", described.path("AllowedOAuthFlows").get(0).asText()); + assertEquals(1, described.path("AllowedOAuthScopes").size()); + assertEquals("email", described.path("AllowedOAuthScopes").get(0).asText()); + assertEquals("updated-app-id", described.path("AnalyticsConfiguration").path("ApplicationId").asText()); + assertEquals("updated-external-id", described.path("AnalyticsConfiguration").path("ExternalId").asText()); + assertEquals("arn:aws:iam::123456789012:role/updated-role", + described.path("AnalyticsConfiguration").path("RoleArn").asText()); + assertFalse(described.path("AnalyticsConfiguration").path("UserDataShared").asBoolean()); + assertEquals(1, described.path("CallbackURLs").size()); + assertEquals("https://updated.example.com/callback", described.path("DefaultRedirectURI").asText()); + assertEquals(1, described.path("ExplicitAuthFlows").size()); + assertEquals("ALLOW_USER_SRP_AUTH", described.path("ExplicitAuthFlows").get(0).asText()); + assertEquals(25, described.path("AccessTokenValidity").asInt()); + assertEquals(30, described.path("IdTokenValidity").asInt()); + assertEquals(1, described.path("LogoutURLs").size()); + assertEquals(1, described.path("ReadAttributes").size()); + assertEquals(14, described.path("RefreshTokenValidity").asInt()); + assertEquals("minutes", described.path("TokenValidityUnits").path("AccessToken").asText()); + assertEquals("minutes", described.path("TokenValidityUnits").path("IdToken").asText()); + assertEquals("days", described.path("TokenValidityUnits").path("RefreshToken").asText()); + assertEquals("DISABLED", described.path("RefreshTokenRotation").path("Feature").asText()); + assertEquals(0, described.path("RefreshTokenRotation").path("RetryGracePeriodSeconds").asInt()); + assertFalse(described.path("EnableTokenRevocation").asBoolean()); + assertEquals("LEGACY", described.path("PreventUserExistenceErrors").asText()); + assertEquals(1, described.path("SupportedIdentityProviders").size()); + assertEquals("COGNITO", described.path("SupportedIdentityProviders").get(0).asText()); + assertEquals(1, described.path("WriteAttributes").size()); + assertEquals("email", described.path("WriteAttributes").get(0).asText()); + } + + @Test + @Order(96) + void configuredTokenValidityControlsAuthResultAndJwtExpiry() throws Exception { + JsonNode poolResponse = cognitoJson("CreateUserPool", """ + { + "PoolName": "TokenValidityPool" + } + """); + String validityPoolId = poolResponse.path("UserPool").path("Id").asText(); + String validityUsername = "validity+" + UUID.randomUUID() + "@example.com"; + String validityPassword = "Perm1234!"; + + JsonNode clientResp = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "token-validity-client", + "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"], + "AccessTokenValidity": 15, + "IdTokenValidity": 20, + "RefreshTokenValidity": 7, + "TokenValidityUnits": { + "AccessToken": "minutes", + "IdToken": "minutes", + "RefreshToken": "days" + } + } + """.formatted(validityPoolId)); + String validityClientId = clientResp.path("UserPoolClient").path("ClientId").asText(); + + cognitoAction("AdminCreateUser", """ + { + "UserPoolId": "%s", + "Username": "%s", + "UserAttributes": [ + { "Name": "email", "Value": "%s" }, + { "Name": "email_verified", "Value": "true" } + ], + "MessageAction": "SUPPRESS" + } + """.formatted(validityPoolId, validityUsername, validityUsername)) + .then() + .statusCode(200); + + cognitoAction("AdminSetUserPassword", """ + { + "UserPoolId": "%s", + "Username": "%s", + "Password": "%s", + "Permanent": true + } + """.formatted(validityPoolId, validityUsername, validityPassword)) + .then() + .statusCode(200); + + JsonNode auth = cognitoJson("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_PASSWORD_AUTH", + "AuthParameters": { + "USERNAME": "%s", + "PASSWORD": "%s" + } + } + """.formatted(validityClientId, validityUsername, validityPassword)); + + JsonNode result = auth.path("AuthenticationResult"); + JsonNode accessPayload = decodeJwtPayload(result.path("AccessToken").asText()); + JsonNode idPayload = decodeJwtPayload(result.path("IdToken").asText()); + + assertEquals(900, result.path("ExpiresIn").asInt()); + assertEquals(900L, accessPayload.path("exp").asLong() - accessPayload.path("iat").asLong()); + assertEquals(1200L, idPayload.path("exp").asLong() - idPayload.path("iat").asLong()); + + JsonNode refreshAuth = cognitoJson("GetTokensFromRefreshToken", """ + { + "ClientId": "%s", + "RefreshToken": "%s" + } + """.formatted(validityClientId, result.path("RefreshToken").asText())); + JsonNode refreshResult = refreshAuth.path("AuthenticationResult"); + JsonNode refreshedAccessPayload = decodeJwtPayload(refreshResult.path("AccessToken").asText()); + JsonNode refreshedIdPayload = decodeJwtPayload(refreshResult.path("IdToken").asText()); + + assertEquals(900, refreshResult.path("ExpiresIn").asInt()); + assertEquals(900L, refreshedAccessPayload.path("exp").asLong() - refreshedAccessPayload.path("iat").asLong()); + 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) diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java index bf432202eb..eb4807c308 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java @@ -268,6 +268,79 @@ class CognitoJsonHandlerTest { assertTrue(emailAttr.get("Required").asBoolean(), "email must be required per the override"); } + // ========================================================================= + // Issue #1306 — DescribeUserPoolClient extended configuration + // ========================================================================= + + @Test + void describeUserPoolClientReturnsExtendedConfigurationFields() { + ObjectNode poolReq = mapper.createObjectNode(); + poolReq.put("PoolName", "client-pool"); + JsonNode poolBody = (JsonNode) handler.handle("CreateUserPool", poolReq, "us-east-1").getEntity(); + String poolId = poolBody.get("UserPool").get("Id").asText(); + + ObjectNode clientReq = mapper.createObjectNode(); + clientReq.put("UserPoolId", poolId); + clientReq.put("ClientName", "extended-client"); + clientReq.put("GenerateSecret", true); + clientReq.put("AllowedOAuthFlowsUserPoolClient", true); + clientReq.putArray("AllowedOAuthFlows").add("code"); + clientReq.putArray("AllowedOAuthScopes").add("openid").add("email"); + clientReq.putObject("AnalyticsConfiguration") + .put("ApplicationId", "d70b2ba36a8c4dc5a04a0451a31a1e12") + .put("ExternalId", "my-external-id") + .put("RoleArn", "arn:aws:iam::123456789012:role/test-cognitouserpool-role") + .put("UserDataShared", true); + clientReq.putArray("CallbackURLs").add("https://example.com").add("http://localhost"); + clientReq.put("DefaultRedirectURI", "https://example.com"); + clientReq.putArray("ExplicitAuthFlows").add("ALLOW_USER_AUTH").add("ALLOW_REFRESH_TOKEN_AUTH"); + clientReq.put("AccessTokenValidity", 6); + clientReq.put("IdTokenValidity", 7); + clientReq.putArray("LogoutURLs").add("https://example.com/logout"); + clientReq.put("PreventUserExistenceErrors", "ENABLED"); + clientReq.putArray("ReadAttributes").add("email").add("address"); + clientReq.put("RefreshTokenValidity", 8); + clientReq.putArray("SupportedIdentityProviders").add("COGNITO").add("Google"); + clientReq.putObject("TokenValidityUnits") + .put("AccessToken", "hours") + .put("IdToken", "minutes") + .put("RefreshToken", "days"); + clientReq.putArray("WriteAttributes").add("family_name").add("email"); + clientReq.putObject("RefreshTokenRotation") + .put("Feature", "ENABLED") + .put("RetryGracePeriodSeconds", 30); + clientReq.put("EnableTokenRevocation", true); + + JsonNode clientBody = (JsonNode) handler.handle("CreateUserPoolClient", clientReq, "us-east-1").getEntity(); + String clientId = clientBody.get("UserPoolClient").get("ClientId").asText(); + + ObjectNode describeReq = mapper.createObjectNode(); + describeReq.put("UserPoolId", poolId); + describeReq.put("ClientId", clientId); + + JsonNode describeBody = (JsonNode) handler.handle("DescribeUserPoolClient", describeReq, "us-east-1").getEntity(); + JsonNode client = describeBody.get("UserPoolClient"); + + assertTrue(client.get("AllowedOAuthFlowsUserPoolClient").asBoolean()); + assertEquals("code", client.get("AllowedOAuthFlows").get(0).asText()); + assertEquals("openid", client.get("AllowedOAuthScopes").get(0).asText()); + assertEquals("d70b2ba36a8c4dc5a04a0451a31a1e12", client.get("AnalyticsConfiguration").get("ApplicationId").asText()); + assertEquals("https://example.com", client.get("CallbackURLs").get(0).asText()); + assertEquals("https://example.com", client.get("DefaultRedirectURI").asText()); + assertEquals("ALLOW_USER_AUTH", client.get("ExplicitAuthFlows").get(0).asText()); + assertEquals(6, client.get("AccessTokenValidity").asInt()); + assertEquals(7, client.get("IdTokenValidity").asInt()); + assertEquals("https://example.com/logout", client.get("LogoutURLs").get(0).asText()); + assertEquals("ENABLED", client.get("PreventUserExistenceErrors").asText()); + assertEquals("email", client.get("ReadAttributes").get(0).asText()); + assertEquals(8, client.get("RefreshTokenValidity").asInt()); + assertEquals("COGNITO", client.get("SupportedIdentityProviders").get(0).asText()); + assertEquals("hours", client.get("TokenValidityUnits").get("AccessToken").asText()); + assertEquals("family_name", client.get("WriteAttributes").get(0).asText()); + assertEquals("ENABLED", client.get("RefreshTokenRotation").get("Feature").asText()); + assertTrue(client.get("EnableTokenRevocation").asBoolean()); + } + @Test void tagResourceRejectsReservedKey() { ObjectNode createRequest = mapper.createObjectNode(); 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 54fa2a6b6c..96f3c2729b 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 @@ -12,6 +12,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -120,6 +121,191 @@ class CognitoServiceTest { assertEquals("ResourceConflictException", exception.getErrorCode()); } + // ========================================================================= + // Issue #1306 — CreateUserPoolClient extended configuration + // ========================================================================= + + @Test + void createUserPoolClientPersistsExtendedConfiguration() { + UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1"); + + Map analyticsConfiguration = Map.of( + "ApplicationId", "d70b2ba36a8c4dc5a04a0451a31a1e12", + "ExternalId", "my-external-id", + "RoleArn", "arn:aws:iam::123456789012:role/test-cognitouserpool-role", + "UserDataShared", true + ); + Map tokenValidityUnits = Map.of( + "AccessToken", "hours", + "IdToken", "minutes", + "RefreshToken", "days" + ); + Map refreshTokenRotation = Map.of( + "Feature", "ENABLED", + "RetryGracePeriodSeconds", 30 + ); + + UserPoolClient client = service.createUserPoolClient( + pool.getId(), + "my-test-app-client", + true, + true, + List.of(" code ", "code"), + List.of("aws.cognito.signin.user.admin", "openid"), + analyticsConfiguration, + List.of("https://example.com", "http://localhost", "myapp://example"), + "https://example.com", + List.of("ALLOW_USER_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_USER_PASSWORD_AUTH", + "ALLOW_REFRESH_TOKEN_AUTH"), + 6, + 6, + List.of("https://example.com/logout"), + "ENABLED", + List.of("email", "address", "preferred_username"), + 6, + List.of("SignInWithApple", "MySSO"), + tokenValidityUnits, + List.of("family_name", "email"), + refreshTokenRotation, + true + ); + + assertNotNull(client.getClientId()); + assertEquals(pool.getId(), client.getUserPoolId()); + assertEquals("my-test-app-client", client.getClientName()); + assertTrue(client.isGenerateSecret()); + assertNotNull(client.getClientSecret()); + assertEquals(1, client.getUserPoolClientSecrets().size()); + assertTrue(client.isAllowedOAuthFlowsUserPoolClient()); + assertEquals(List.of("code"), client.getAllowedOAuthFlows()); + assertEquals(List.of("aws.cognito.signin.user.admin", "openid"), client.getAllowedOAuthScopes()); + assertEquals(analyticsConfiguration, client.getAnalyticsConfiguration()); + assertEquals(List.of("https://example.com", "http://localhost", "myapp://example"), client.getCallbackURLs()); + assertEquals("https://example.com", client.getDefaultRedirectURI()); + assertEquals(List.of("ALLOW_USER_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_USER_PASSWORD_AUTH", + "ALLOW_REFRESH_TOKEN_AUTH"), client.getExplicitAuthFlows()); + assertEquals(6, client.getAccessTokenValidity()); + assertEquals(6, client.getIdTokenValidity()); + assertEquals(List.of("https://example.com/logout"), client.getLogoutURLs()); + assertEquals("ENABLED", client.getPreventUserExistenceErrors()); + assertEquals(List.of("email", "address", "preferred_username"), client.getReadAttributes()); + assertEquals(6, client.getRefreshTokenValidity()); + assertEquals(List.of("SignInWithApple", "MySSO"), client.getSupportedIdentityProviders()); + assertEquals(tokenValidityUnits, client.getTokenValidityUnits()); + assertEquals(List.of("family_name", "email"), client.getWriteAttributes()); + assertEquals(refreshTokenRotation, client.getRefreshTokenRotation()); + assertEquals(Boolean.TRUE, client.getEnableTokenRevocation()); + } + + @Test + void createUserPoolClientGeneratesIdSecretTimestampsAndNormalizesLists() { + UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1"); + + UserPoolClient client = service.createUserPoolClient( + pool.getId(), + "basic-client", + true, + true, + List.of(" code ", "code", "implicit", "", "implicit"), + new ArrayList<>(java.util.Arrays.asList(" openid ", "openid", "email", null, "email")) + ); + + assertNotNull(client.getClientId()); + assertEquals(26, client.getClientId().length()); + assertTrue(client.getClientId().chars().allMatch(Character::isLetterOrDigit)); + + assertTrue(client.isGenerateSecret()); + assertNotNull(client.getClientSecret()); + assertFalse(client.getClientSecret().isBlank()); + assertEquals(1, client.getUserPoolClientSecrets().size()); + assertEquals(client.getClientSecret(), client.getUserPoolClientSecrets().get(0).getClientSecretValue()); + + assertTrue(client.getCreationDate() > 0); + assertTrue(client.getLastModifiedDate() > 0); + assertEquals(client.getCreationDate(), client.getLastModifiedDate()); + + assertEquals(List.of("code", "implicit"), client.getAllowedOAuthFlows()); + assertEquals(List.of("openid", "email"), client.getAllowedOAuthScopes()); + } + + @Test + void createUserPoolClientAppliesAwsLikeDefaultsForSupportedIdentityProvidersAndTokenRevocation() { + UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1"); + + UserPoolClient client = service.createUserPoolClient( + pool.getId(), + "defaulted-client", + false, + false, + List.of(), + List.of() + ); + + assertEquals(List.of("COGNITO"), client.getSupportedIdentityProviders()); + assertEquals(Boolean.TRUE, client.getEnableTokenRevocation()); + } + + @Test + void updateUserPoolClientAllowsClearingListFieldsWithEmptyArrays() { + UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1"); + + UserPoolClient client = service.createUserPoolClient( + pool.getId(), + "client", + false, + false, + List.of(), + List.of(), + null, + List.of("https://example.com"), + "https://example.com", + List.of("ALLOW_USER_AUTH"), + null, + null, + List.of("https://example.com/logout"), + null, + List.of("email"), + null, + List.of("COGNITO", "Google"), + null, + List.of("family_name"), + null, + null + ); + + service.updateUserPoolClient( + pool.getId(), + client.getClientId(), + null, + null, + null, + null, + null, + List.of(), + null, + List.of(), + null, + null, + List.of(), + null, + List.of(), + null, + List.of(), + null, + List.of(), + null, + null + ); + + UserPoolClient updated = service.describeUserPoolClient(pool.getId(), client.getClientId()); + assertEquals(List.of(), updated.getCallbackURLs()); + assertEquals(List.of(), updated.getExplicitAuthFlows()); + assertEquals(List.of(), updated.getLogoutURLs()); + assertEquals(List.of(), updated.getReadAttributes()); + assertEquals(List.of(), updated.getSupportedIdentityProviders()); + assertEquals(List.of(), updated.getWriteAttributes()); + } + @Test void createUserPoolWithBlankOverrideIdThrowsValidation() { AwsException exception = assertThrows( @@ -888,11 +1074,12 @@ class CognitoServiceTest { assertNotNull(refreshToken); // Should be parseable as base64 structured token String decoded = new String(Base64.getDecoder().decode(refreshToken), StandardCharsets.UTF_8); - String[] parts = decoded.split("\\|", 4); - assertEquals(4, parts.length, "Refresh token should encode 4 pipe-separated fields"); + String[] parts = decoded.split("\\|", 5); + assertEquals(5, parts.length, "Refresh token should encode 5 pipe-separated fields"); assertEquals(pool.getId(), parts[0]); assertEquals("alice", parts[1]); assertEquals(client.getClientId(), parts[2]); + assertFalse(parts[3].isBlank(), "Refresh token should encode its issued-at timestamp"); } @Test @@ -923,6 +1110,46 @@ class CognitoServiceTest { service.getTokensFromRefreshToken(client.getClientId(), "not-a-valid-refresh-token")); } + // ========================================================================= + // Issue #1306 — Refresh token expiry respects client token validity + // ========================================================================= + + @Test + void getTokensFromRefreshTokenExpiredTokenThrows() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), + "c", + false, + false, + List.of(), + List.of(), + null, + List.of(), + null, + List.of(), + null, + null, + List.of(), + null, + List.of(), + 1, + List.of(), + Map.of("RefreshToken", "seconds"), + List.of(), + null, + null + ); + + long issuedAt = (System.currentTimeMillis() / 1000L) - 5; + String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAt + "|" + java.util.UUID.randomUUID(); + String expiredRefreshToken = Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + + AwsException exception = assertThrows(AwsException.class, () -> + service.getTokensFromRefreshToken(client.getClientId(), expiredRefreshToken)); + assertEquals("NotAuthorizedException", exception.getErrorCode()); + } + @Test void refreshTokenAuthFlowReturnsNewTokens() { UserPool pool = createPoolAndUser();