diff --git a/docs/services/cognito.md b/docs/services/cognito.md index f076ef2144..c67d30f48e 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -881,6 +881,20 @@ curl -s -b jar -o /dev/null -w '%{http_code} %{redirect_url}\n' \ - Authorization-code redemption validates the client, callback URI and one-time code binding. - It requires `AllowedOAuthFlowsUserPoolClient=true` and `AllowedOAuthFlows=["client_credentials"]`. - It doesn't require a Cognito domain. +- Client-credentials invokes the pre token generation trigger with triggerSource + `TokenGeneration_ClientCredentials` when, as on AWS, the pool's + `PreTokenGenerationConfig.LambdaVersion` is `V3_0`; a `V1_0` or `V2_0` trigger is not invoked. + The event carries `version` `3`, `userName` `ClientCredentials`, the granted `scopes`, empty `userAttributes`, a + null `groupConfiguration`, the request's `aws_client_metadata` (a URL-encoded JSON object of + strings) as `clientMetadata`, and `response.claimsAndScopeOverrideDetails` set to null, so a + function must build the response object rather than write into it. Metadata that is not a JSON + object, or a value that is not a JSON string (a number, boolean, null, object or array), refuses + the request with `invalid_request`. + Only `accessTokenGeneration` applies: its claims and scope changes reach the access token, while + `idTokenGeneration` and `groupOverrideDetails` are ignored. The trigger cannot add, change or + suppress `sub`, `client_id`, `token_use`, `version`, `username`, `iss`, `exp`, `iat`, `jti` or any + `cognito:` claim, and an `aud` it adds must equal the client ID. It changes `scope` only through + `scopesToAdd` and `scopesToSuppress`. - Client-credentials returns only `access_token`, `token_type`, and `expires_in`; authorization-code redemption returns the Cognito access and refresh tokens, and an ID token when the granted scopes include `openid`; a refresh returns the same tokens without a refresh token. diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java index 51aa85370e..785a68dd21 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java @@ -63,6 +63,7 @@ final class CognitoAuthFlowHandler { private static final String CUSTOM_MESSAGE_USERNAME_PARAMETER = "{username}"; /** The {@code callerContext.clientId} AWS sends for an admin action, which names no app client. */ private static final String CLIENT_ID_NOT_APPLICABLE = "CLIENT_ID_NOT_APPLICABLE"; + private static final String CLIENT_CREDENTIALS_TRIGGER_SOURCE = "TokenGeneration_ClientCredentials"; /** The message of a wrong password, which managed login also shows for an unknown user. */ static final String INCORRECT_CREDENTIALS = "Incorrect username or password"; static final int MAX_USER_AUTH_SESSIONS_PER_PARTITION = 4_096; @@ -1917,10 +1918,15 @@ final class CognitoAuthFlowHandler { private Map triggerEvent(UserPool pool, String clientId, CognitoUser user, String triggerKey, String triggerSource, Map request) { Map event = new HashMap<>(); - event.put("version", "1"); + event.put("version", CLIENT_CREDENTIALS_TRIGGER_SOURCE.equals(triggerSource) ? "3" : "1"); event.put("region", regionForPool(pool)); event.put("userPoolId", pool.getId()); - event.put("userName", user == null ? null : user.getUsername()); + String userName = user == null ? null : user.getUsername(); + if (CLIENT_CREDENTIALS_TRIGGER_SOURCE.equals(triggerSource)) { + // A client-credentials grant has no user; AWS sends this fixed name in its place. + userName = "ClientCredentials"; + } + event.put("userName", userName); event.put("callerContext", Map.of( "awsSdkVersion", "floci", "clientId", clientId)); @@ -1945,6 +1951,9 @@ final class CognitoAuthFlowHandler { response.put("emailSubject", null); response.put("smsMessage", null); } + if (CLIENT_CREDENTIALS_TRIGGER_SOURCE.equals(triggerSource)) { + response.put("claimsAndScopeOverrideDetails", null); + } event.put("response", response); return event; } @@ -2181,7 +2190,13 @@ final class CognitoAuthFlowHandler { Map clientMetadata, String triggerSource, List scopes) { Map req = new HashMap<>(); - req.put("groupConfiguration", buildGroupConfiguration(user)); + if (user == null) { + // A machine identity has neither attributes nor groups. + req.put("userAttributes", Map.of()); + req.put("groupConfiguration", null); + } else { + req.put("groupConfiguration", buildGroupConfiguration(user)); + } req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata); // V2 lambdas (CognitoEventUserPoolsPreTokenGenV2) require `scopes` to deserialize. // V1 lambdas tolerate the extra field. Only an OAuth flow has requested scopes to send; @@ -2637,6 +2652,32 @@ final class CognitoAuthFlowHandler { return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_HostedAuth", scopes); } + /** + * Fires PreTokenGeneration for a client-credentials grant, with triggerSource + * {@code TokenGeneration_ClientCredentials}. AWS invokes the trigger for a machine identity only + * when the pool's {@code PreTokenGenerationConfig.LambdaVersion} is {@code V3_0}; a V1 or V2 + * trigger is skipped and the token is issued unchanged. {@code clientMetadata} is the token + * request's {@code aws_client_metadata}. + */ + CognitoService.ClaimsOverride preTokenGenerationForClientCredentials(UserPool pool, UserPoolClient client, + List scopes, + Map clientMetadata) { + if (!"V3_0".equals(preTokenGenerationLambdaVersion(pool))) { + return null; + } + return firePreTokenGeneration(pool, client, null, clientMetadata, + CLIENT_CREDENTIALS_TRIGGER_SOURCE, scopes); + } + + private static String preTokenGenerationLambdaVersion(UserPool pool) { + Map cfg = pool.getLambdaConfig(); + if (cfg != null && cfg.get("PreTokenGenerationConfig") instanceof Map m + && m.get("LambdaVersion") instanceof String version) { + return version; + } + return "V1_0"; + } + private static String resolveTriggerArn(UserPool pool, String triggerKey) { Map cfg = pool.getLambdaConfig(); if (cfg == null) return null; diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoOAuthController.java b/src/main/java/io/floci/aws/services/cognito/CognitoOAuthController.java index f526216c63..ff104bd5b0 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoOAuthController.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoOAuthController.java @@ -1,5 +1,7 @@ package io.floci.aws.services.cognito; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; @@ -551,10 +553,15 @@ public class CognitoOAuthController { "Only client_credentials, authorization_code and refresh_token are supported"); } String scope = trimToNull(formParams.getFirst("scope")); + Optional> clientMetadata = + parseClientMetadata(trimToNull(formParams.getFirst("aws_client_metadata"))); + if (clientMetadata.isEmpty()) { + return oauthError("invalid_request", "aws_client_metadata must be a JSON object of strings"); + } try { Map result = cognitoService.issueClientCredentialsToken( - clientId, clientSecret, scope, domainPoolId); + clientId, clientSecret, scope, domainPoolId, clientMetadata.get()); return Response.ok(objectMapper.valueToTree(result)) .type(MediaType.APPLICATION_JSON) .header("Cache-Control", "no-store") @@ -578,6 +585,37 @@ public class CognitoOAuthController { } } + /** + * The client-credentials {@code aws_client_metadata} parameter, or empty when it is not a JSON + * object of string values. An absent parameter is an empty map. + */ + private Optional> parseClientMetadata(String raw) { + if (raw == null) { + return Optional.of(Map.of()); + } + JsonNode root; + try { + root = objectMapper.readTree(raw); + } catch (JsonProcessingException e) { + LOG.debugv(e, "Rejecting malformed aws_client_metadata"); + return Optional.empty(); + } + if (root == null || root.isNull()) { + return Optional.of(Map.of()); + } + if (!root.isObject()) { + return Optional.empty(); + } + Map metadata = new LinkedHashMap<>(); + for (Map.Entry member : root.properties()) { + if (!member.getValue().isTextual()) { + return Optional.empty(); + } + metadata.put(member.getKey(), member.getValue().textValue()); + } + return Optional.of(metadata); + } + private Response redeemAuthorizationCode(String clientId, String clientSecret, MultivaluedMap formParams, String domainPoolId) { String code = trimToNull(formParams.getFirst("code")); diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoService.java b/src/main/java/io/floci/aws/services/cognito/CognitoService.java index ed906b1293..9e9f99677c 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoService.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoService.java @@ -157,6 +157,12 @@ public class CognitoService implements ResourceProvider { private static final Set NAMED_PROVIDER_TYPES = Set.of("Facebook", "Google", "LoginWithAmazon", "SignInWithApple"); + // scope is included because AWS changes it only through scopesToAdd and scopesToSuppress. + private static final Set MACHINE_TOKEN_PROTECTED_CLAIMS = Set.of( + "sub", "client_id", "event_id", "version", "acr", "amr", "auth_time", "azp", "exp", "iat", + "iss", "jti", "nbf", "nonce", "origin_jti", "token_use", "username", "device_key", "at_hash", + "scope"); + /** * Claim overrides returned by a PreTokenGeneration Lambda trigger. @@ -4750,6 +4756,16 @@ public class CognitoService implements ResourceProvider { */ public Map issueClientCredentialsToken(String clientId, String clientSecret, String scope, String requiredPoolId) { + return issueClientCredentialsToken(clientId, clientSecret, scope, requiredPoolId, Map.of()); + } + + /** + * @param clientMetadata the token request's {@code aws_client_metadata}, passed to a V3_0 pre + * token generation trigger + */ + public Map issueClientCredentialsToken(String clientId, String clientSecret, String scope, + String requiredPoolId, + Map clientMetadata) { UserPoolClient client = clientStore.get(clientId) .filter(c -> requiredPoolId == null || requiredPoolId.equals(c.getUserPoolId())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400)); @@ -4757,9 +4773,11 @@ public class CognitoService implements ResourceProvider { validateClientAllowsClientCredentials(client); validateClientSecret(client, clientSecret); String normalizedScope = resolveAuthorizedScopes(client, pool.getId(), scope); + ClaimsOverride override = authFlowHandler.preTokenGenerationForClientCredentials(pool, client, + List.of(normalizedScope.split(" ")), clientMetadata); Map response = new LinkedHashMap<>(); - response.put("access_token", generateClientAccessToken(client, pool, normalizedScope)); + response.put("access_token", generateClientAccessToken(client, pool, normalizedScope, override)); response.put("token_type", "Bearer"); response.put("expires_in", resolveAccessTokenLifetimeSeconds(client)); return response; @@ -5219,8 +5237,14 @@ public class CognitoService implements ResourceProvider { if (override.preferredRole() != null) { claims.put("cognito:preferred_role", override.preferredRole()); } - // V2 access-token scope mutations. - if (isAccess && (override.scopesToAdd() != null || override.scopesToSuppress() != null)) { + if (isAccess) { + applyScopeOverride(claims, override); + } + } + + /** V2/V3 access-token scope mutations. */ + private static void applyScopeOverride(Map claims, ClaimsOverride override) { + if (override.scopesToAdd() != null || override.scopesToSuppress() != null) { Object existing = claims.get("scope"); List current = new ArrayList<>(); if (existing instanceof String s && !s.isBlank()) { @@ -5284,31 +5308,62 @@ public class CognitoService implements ResourceProvider { return signJwt(header, payload, getSigningPrivateKey(pool)); } - private String generateClientAccessToken(UserPoolClient client, UserPool pool, String scope) { - String headerJson = String.format( - "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", - escapeJson(getSigningKeyId(pool))); - String header = Base64Url.encode(headerJson); - + private String generateClientAccessToken(UserPoolClient client, UserPool pool, String scope, + ClaimsOverride override) { long now = System.currentTimeMillis() / 1000L; long lifetimeSeconds = resolveAccessTokenLifetimeSeconds(client); - StringBuilder payloadJson = new StringBuilder(); - payloadJson.append("{") - .append("\"iss\":\"").append(escapeJson(getIssuer(pool.getId()))).append("\",") - .append("\"version\":2,") - .append("\"sub\":\"").append(escapeJson(client.getClientId())).append("\",") - .append("\"client_id\":\"").append(escapeJson(client.getClientId())).append("\",") - .append("\"token_use\":\"access\",") - .append("\"exp\":").append(now + lifetimeSeconds).append(",") - .append("\"iat\":").append(now).append(",") - .append("\"jti\":\"").append(UUID.randomUUID()).append("\""); + Map claims = new LinkedHashMap<>(); + claims.put("iss", getIssuer(pool.getId())); + claims.put("version", 2); + claims.put("sub", client.getClientId()); + claims.put("client_id", client.getClientId()); + claims.put("token_use", "access"); + claims.put("exp", now + lifetimeSeconds); + claims.put("iat", now); + claims.put("jti", UUID.randomUUID().toString()); if (scope != null && !scope.isBlank()) { - payloadJson.append(",\"scope\":\"").append(escapeJson(scope)).append("\""); + claims.put("scope", scope); } - payloadJson.append("}"); + applyClientCredentialsOverride(claims, override, client.getClientId()); + return signJwt(encodeJwtHeader(pool), encodeJsonBase64Url(claims), getSigningPrivateKey(pool)); + } - String payload = Base64Url.encode(payloadJson.toString()); - return signJwt(header, payload, getSigningPrivateKey(pool)); + /** + * Applies a V3_0 pre token generation response to a client-credentials access token. Only + * {@code accessTokenGeneration} reaches a machine identity: it has no ID token and no groups, so + * {@code idTokenGeneration} and {@code groupOverrideDetails} are ignored, as on AWS. + */ + private static void applyClientCredentialsOverride(Map claims, ClaimsOverride override, + String clientId) { + if (override == null) { + return; + } + if (override.accessClaimsToSuppress() != null) { + override.accessClaimsToSuppress().stream() + .filter(claim -> !isMachineTokenProtectedClaim(claim)) + .forEach(claims::remove); + } + if (override.accessClaimsToAddOrOverride() != null) { + override.accessClaimsToAddOrOverride().forEach((claim, value) -> { + if (isMachineTokenProtectedClaim(claim)) { + return; + } + // AWS accepts an aud claim only when it names the client the token is issued to. + if ("aud".equals(claim) && !clientId.equals(value)) { + return; + } + claims.put(claim, value); + }); + } + applyScopeOverride(claims, override); + } + + /** + * The claims AWS lets no pre token generation trigger add, modify or suppress in an access token + * issued to a machine identity, and any claim in the reserved {@code cognito:} namespace. + */ + private static boolean isMachineTokenProtectedClaim(String claim) { + return MACHINE_TOKEN_PROTECTED_CLAIMS.contains(claim) || claim.startsWith("cognito:"); } private void validateClientSecret(UserPoolClient client, String clientSecret) { diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java index be6c2b2d0a..1bd458d113 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.acm.AcmService; import io.floci.aws.services.cognito.model.CognitoUser; +import io.floci.aws.services.cognito.model.ResourceServerScope; import io.floci.aws.services.cognito.model.UserPool; import io.floci.aws.services.cognito.model.UserPoolClient; import io.floci.aws.services.cognito.verification.CognitoMessageDispatcher; @@ -1351,6 +1352,166 @@ class CognitoLambdaTriggersTest { assertNotNull(req.get("userAttributes")); } + // ========================================================================= + // PreTokenGeneration for client credentials (M2M) + // ========================================================================= + + private UserPool createPoolWithPreTokenGenerationVersion(String lambdaVersion) { + return createPoolWithLambdaConfig(Map.of( + "PreTokenGeneration", "arn:aws:lambda:::pre-token", + "PreTokenGenerationConfig", Map.of( + "LambdaArn", "arn:aws:lambda:::pre-token", + "LambdaVersion", lambdaVersion))); + } + + private UserPoolClient createM2mClient(UserPool pool) { + ResourceServerScope read = new ResourceServerScope(); + read.setScopeName("read"); + ResourceServerScope write = new ResourceServerScope(); + write.setScopeName("write"); + service.createResourceServer(pool.getId(), "notes", "Notes", List.of(read, write)); + return service.createUserPoolClient(pool.getId(), "m2m", true, true, + List.of("client_credentials"), List.of("notes/read", "notes/write")); + } + + private Map clientCredentialsClaims(UserPoolClient client, Map metadata) + throws IOException { + String accessToken = (String) service.issueClientCredentialsToken(client.getClientId(), + client.getClientSecret(), "notes/read", null, metadata).get("access_token"); + return MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {}); + } + + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationV3FiresForClientCredentialsWithAMachineIdentityEvent() throws Exception { + UserPool pool = createPoolWithPreTokenGenerationVersion("V3_0"); + UserPoolClient client = createM2mClient(pool); + ArgumentCaptor payloadCap = ArgumentCaptor.forClass(byte[].class); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), + eq(InvocationType.RequestResponse))).thenReturn(ok(Map.of())); + + clientCredentialsClaims(client, Map.of("environment", "dev")); + + Map event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {}); + Map request = (Map) event.get("request"); + Map callerContext = (Map) event.get("callerContext"); + Map response = (Map) event.get("response"); + assertAll( + () -> assertEquals("TokenGeneration_ClientCredentials", event.get("triggerSource")), + () -> assertEquals("3", event.get("version")), + () -> assertEquals("ClientCredentials", event.get("userName")), + () -> assertTrue(response.containsKey("claimsAndScopeOverrideDetails")), + () -> assertNull(response.get("claimsAndScopeOverrideDetails")), + () -> assertEquals(pool.getId(), event.get("userPoolId")), + () -> assertEquals(client.getClientId(), callerContext.get("clientId")), + () -> assertEquals(List.of("notes/read"), request.get("scopes")), + () -> assertEquals(Map.of("environment", "dev"), request.get("clientMetadata")), + () -> assertEquals(Map.of(), request.get("userAttributes")), + () -> assertTrue(request.containsKey("groupConfiguration")), + () -> assertNull(request.get("groupConfiguration"))); + } + + @Test + void preTokenGenerationV3AddsClaimsAndScopesToTheClientCredentialsToken() throws Exception { + UserPool pool = createPoolWithPreTokenGenerationVersion("V3_0"); + UserPoolClient client = createM2mClient(pool); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "idTokenGeneration", Map.of("claimsToAddOrOverride", Map.of("id_only", "x")), + "accessTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of("marker", "yes", "tenant", Map.of("id", 7)), + "scopesToAdd", List.of("notes/write")), + "groupOverrideDetails", Map.of("groupsToOverride", List.of("admins")))))); + + Map claims = clientCredentialsClaims(client, Map.of()); + + assertAll( + () -> assertEquals("yes", claims.get("marker")), + () -> assertEquals(Map.of("id", 7), claims.get("tenant")), + () -> assertEquals("notes/read notes/write", claims.get("scope")), + () -> assertFalse(claims.containsKey("id_only"), "an M2M grant issues no ID token"), + () -> assertFalse(claims.containsKey("cognito:groups"), "a machine identity has no groups")); + } + + @Test + void preTokenGenerationV3CannotChangeTheClaimsThatIdentifyTheClient() throws Exception { + UserPool pool = createPoolWithPreTokenGenerationVersion("V3_0"); + UserPoolClient client = createM2mClient(pool); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of( + "sub", "other", "client_id", "other", "token_use", "id", + "cognito:username", "bob", "aud", "someone-else", + "username", "alice"), + "claimsToSuppress", List.of("iss", "exp", "jti", "version")))))); + + Map claims = clientCredentialsClaims(client, Map.of()); + + assertAll( + () -> assertFalse(claims.containsKey("username"), "a machine token names no user"), + () -> assertEquals(client.getClientId(), claims.get("sub")), + () -> assertEquals(client.getClientId(), claims.get("client_id")), + () -> assertEquals("access", claims.get("token_use")), + () -> assertEquals(2, claims.get("version")), + () -> assertNotNull(claims.get("iss")), + () -> assertNotNull(claims.get("exp")), + () -> assertNotNull(claims.get("jti")), + () -> assertFalse(claims.containsKey("cognito:username")), + () -> assertFalse(claims.containsKey("aud"), "aud must name the token's own client")); + } + + @Test + void preTokenGenerationV3ChangesTheClientCredentialsScopeOnlyThroughTheScopeFields() throws Exception { + UserPool pool = createPoolWithPreTokenGenerationVersion("V3_0"); + UserPoolClient client = createM2mClient(pool); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "claimsToAddOrOverride", Map.of("scope", "admin/all"), + "claimsToSuppress", List.of("scope")))))); + + Map claims = clientCredentialsClaims(client, Map.of()); + + assertEquals("notes/read", claims.get("scope"), + "claimsToAddOrOverride and claimsToSuppress must not replace the granted scope"); + } + + @ParameterizedTest + @ValueSource(strings = {"V1_0", "V2_0"}) + void preTokenGenerationBelowV3IsNotInvokedForClientCredentials(String lambdaVersion) throws Exception { + UserPool pool = createPoolWithPreTokenGenerationVersion(lambdaVersion); + UserPoolClient client = createM2mClient(pool); + + Map claims = clientCredentialsClaims(client, Map.of()); + + assertEquals("notes/read", claims.get("scope")); + verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any()); + } + + @Test + void preTokenGenerationWithoutAVersionIsNotInvokedForClientCredentials() throws Exception { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + UserPoolClient client = createM2mClient(pool); + + clientCredentialsClaims(client, Map.of()); + + verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any()); + } + + @Test + void preTokenGenerationV3LambdaErrorBlocksTheClientCredentialsToken() { + UserPool pool = createPoolWithPreTokenGenerationVersion("V3_0"); + UserPoolClient client = createM2mClient(pool); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(lambdaError("Unhandled", "denied")); + + AwsException failure = assertThrows(AwsException.class, + () -> clientCredentialsClaims(client, Map.of())); + + assertEquals("UserLambdaValidationException", failure.getErrorCode()); + } + // ========================================================================= // UserMigration // ========================================================================= diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java index 294ee48cd3..f35550bac3 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoOAuthTokenIntegrationTest.java @@ -12,6 +12,8 @@ import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -847,6 +849,57 @@ class CognitoOAuthTokenIntegrationTest { refreshWithBodySecret(user.clientId(), "wrongsecret", user.refreshToken()).then().statusCode(200); } + @Test + @Order(41) + void clientCredentialsAcceptsAwsClientMetadata() throws Exception { + Response response = given() + .header("Authorization", basic(confidentialClientId, confidentialClientSecret)) + .formParam("grant_type", "client_credentials") + .formParam("aws_client_metadata", "{\"environment\": \"dev\", \"language\": \"en-US\"}") + .when() + .post("/cognito-idp/oauth2/token"); + + response.then().statusCode(200); + JsonNode payload = decodeJwtPayload(response.jsonPath().getString("access_token")); + assertEquals(confidentialClientId, payload.path("client_id").asText()); + } + + @Test + @Order(42) + void clientCredentialsRejectsMalformedAwsClientMetadata() { + given() + .header("Authorization", basic(confidentialClientId, confidentialClientSecret)) + .formParam("grant_type", "client_credentials") + .formParam("aws_client_metadata", "not-json") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + + @ParameterizedTest + @Order(43) + @ValueSource(strings = { + "{\"environment\": null}", + "{\"retries\": 3}", + "{\"enabled\": true}", + "{\"nested\": {\"a\": \"b\"}}", + "{\"list\": [\"a\"]}", + "[\"environment\"]", + "\"environment\""}) + void clientCredentialsRejectsAwsClientMetadataThatIsNotAnObjectOfStrings(String metadata) { + given() + .header("Authorization", basic(confidentialClientId, confidentialClientSecret)) + .formParam("grant_type", "client_credentials") + .formParam("aws_client_metadata", metadata) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + private static String confidentialRefreshToken(String confidentialId, String secret) throws Exception { String username = "confidential-" + System.nanoTime(); cognitoAction("AdminCreateUser", """