mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
2964140717
commit
43ad134107
6 files changed
+389
-27
No files matched your search
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user