fix(cognito): fire PreTokenGeneration for client_credentials tokens (#7891)

* fix(cognito): fire PreTokenGeneration for client_credentials tokens

The token endpoint issued client_credentials access tokens without ever
invoking the pool's pre token generation trigger, so claims and scopes a
V3_0 function returned never reached M2M tokens.

As on AWS, the trigger now fires with triggerSource
TokenGeneration_ClientCredentials when PreTokenGenerationConfig's
LambdaVersion is V3_0, and is skipped for V1_0 and V2_0. The event
matches the one AWS documents for the token endpoint: userName
ClientCredentials, the granted scopes, empty userAttributes, a null
groupConfiguration, the request's aws_client_metadata, and a response
whose claimsAndScopeOverrideDetails is null. Only accessTokenGeneration
applies to the token; claims that identify the client (sub, client_id,
token_use, version, iss, exp, iat, jti and the cognito: namespace)
cannot be changed, and an added aud must equal the client ID.

Fixes #7792

* fix(cognito): protect username and scope in client-credentials tokens

Addresses review feedback on the client-credentials pre token generation
trigger.

A V3_0 trigger could add a username claim to a machine access token, and
could replace or suppress the granted scope through claimsToAddOrOverride
and claimsToSuppress. As on AWS, username (along with device_key and
at_hash) is now protected in machine tokens, and scope changes only
through scopesToAdd and scopesToSuppress.

aws_client_metadata with a null value is now refused with
invalid_request, like any other value that is not a string.

* fix(cognito): send version 3 and accept only string metadata for client credentials

The client-credentials pre token generation event now carries version "3",
as in the AWS token endpoint example. aws_client_metadata is read as a JSON
tree and refused unless it is an object whose values are all JSON strings,
so numbers and booleans are no longer coerced to strings.
This commit is contained in:
Nikola Genčić authored and GitHub committed 2026-11-10 11:01:14 -04:00
1 parent 2964140717
commit 43ad134107
6 files changed
+389 -27

No files matched your search

+14
View File
@@ -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.
@@ -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<String, Object> triggerEvent(UserPool pool, String clientId, CognitoUser user, String triggerKey,
String triggerSource, Map<String, Object> request) {
Map<String, Object> 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<String, String> clientMetadata, String triggerSource,
List<String> scopes) {
Map<String, Object> 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<String> scopes,
Map<String, String> 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<String, Object> 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<String, Object> cfg = pool.getLambdaConfig();
if (cfg == null) return null;
@@ -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<Map<String, String>> 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<String, Object> 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<Map<String, String>> 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<String, String> metadata = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> 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<String, String> formParams, String domainPoolId) {
String code = trimToNull(formParams.getFirst("code"));
@@ -157,6 +157,12 @@ public class CognitoService implements ResourceProvider {
private static final Set<String> 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<String> 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<String, Object> 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<String, Object> issueClientCredentialsToken(String clientId, String clientSecret, String scope,
String requiredPoolId,
Map<String, String> 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<String, Object> 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<String, Object> claims, ClaimsOverride override) {
if (override.scopesToAdd() != null || override.scopesToSuppress() != null) {
Object existing = claims.get("scope");
List<String> 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<String, Object> 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<String, Object> 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) {
@@ -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<String, Object> clientCredentialsClaims(UserPoolClient client, Map<String, String> 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<byte[]> 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<String, Object> event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {});
Map<String, Object> request = (Map<String, Object>) event.get("request");
Map<String, Object> callerContext = (Map<String, Object>) event.get("callerContext");
Map<String, Object> response = (Map<String, Object>) 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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
// =========================================================================
@@ -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", """