mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cognito): fire PreTokenGeneration when the token endpoint redeems a code (#4438)
* fix(cognito): fire PreTokenGeneration when the token endpoint redeems a code Managed login and federated sign-in both mint their tokens at POST /oauth2/token, which called generateAuthResult directly and so never invoked the pre token generation trigger. A pool whose trigger adds claims got them from InitiateAuth but not from a hosted-UI sign-in, so an application that authorizes on a custom claim rejected every token a browser obtained while the same user's tokens from InitiateAuth were accepted. Redemption now mints through a hosted-auth path that fires the trigger with triggerSource TokenGeneration_HostedAuth, which is what AWS uses for a sign-in through the hosted UI, for a pool's own users and federated users alike. The authorization request's nonce is applied after the trigger's claims so a trigger cannot displace it; AWS likewise does not let this trigger override nonce. * fix(cognito): pass the requested scopes to the hosted-auth trigger Review feedback. The authorization code stores the scopes the authorize request asked for, but the hosted-auth trigger call sent an empty list, so a V2 lambda that branches on requested scopes had nothing to branch on. Thread the code's scopes through to the trigger event. The other call sites keep sending an empty list, which is what their non-OAuth flows carry. Also replace the em-dashes in the new comments, per AGENTS.md. * fix(cognito): narrow the trigger's scopes to the client's allowed set Review feedback. An authorization request names its own scopes and nothing checks them against the client's AllowedOAuthScopes when the code is issued, so a stored code can carry a scope the client may not use. Passing those straight through meant a V2 trigger could grant claims, or add scopes, from a scope the client was never entitled to request. The hosted-auth path now narrows the requested scopes to the client's allowed set before the trigger is told about them, dropping the rest the way AWS ignores a scope that is not associated with the client. The narrowing lives in the service method rather than at the call site, so every caller gets it. * style(cognito): brace the new conditionals Review feedback. AGENTS.md requires braces in all conditionals, and the four early returns in the claims-merge helpers omitted them.
This commit is contained in:
1 parent
e186a772a8
commit
b4d8483348
7 files changed
+374
-15
No files matched your search
+27
-6
@@ -436,7 +436,7 @@ final class CognitoAuthFlowHandler {
|
||||
throw ae;
|
||||
}
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
|
||||
clientMetadata, "TokenGeneration_RefreshTokens");
|
||||
clientMetadata, "TokenGeneration_RefreshTokens", List.of());
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
@@ -1291,13 +1291,15 @@ final class CognitoAuthFlowHandler {
|
||||
}
|
||||
|
||||
private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
Map<String, String> clientMetadata, String triggerSource) {
|
||||
Map<String, String> clientMetadata, String triggerSource,
|
||||
List<String> scopes) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
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.
|
||||
req.put("scopes", List.of());
|
||||
// V1 lambdas tolerate the extra field. Only an OAuth flow has requested scopes to send;
|
||||
// the others pass an empty list, which is what the request carries there.
|
||||
req.put("scopes", scopes == null ? List.of() : List.copyOf(scopes));
|
||||
TriggerResult result = invokeTrigger(pool, client, user, "PreTokenGeneration", triggerSource, req);
|
||||
if (!result.configured() || result.errored()) return null;
|
||||
|
||||
@@ -1457,12 +1459,31 @@ final class CognitoAuthFlowHandler {
|
||||
private Map<String, Object> issueTokens(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String triggerSource, Map<String, String> clientMetadata) {
|
||||
firePostAuthentication(pool, client, user, clientMetadata, false);
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource);
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource,
|
||||
List.of());
|
||||
return service.generateAuthResult(user, pool, client, override);
|
||||
}
|
||||
|
||||
CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user) {
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens");
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens", List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires PreTokenGeneration for a sign-in whose tokens the OAuth token endpoint mints when it
|
||||
* redeems an authorization code: managed login and federated sign-in both land here.
|
||||
*
|
||||
* <p>Separate from {@link #issueTokens} because the authorization-code flow splits authentication
|
||||
* from token issuance: the user authenticates at the authorize/login endpoints, and the tokens are
|
||||
* minted later, on a different request, by whoever presents the code. PostAuthentication has
|
||||
* already fired at sign-in, so only PreTokenGeneration is owed here.
|
||||
*
|
||||
* <p>AWS names this trigger source {@code TokenGeneration_HostedAuth}, which it uses for sign-in
|
||||
* through the hosted UI regardless of whether the user is native or federated. {@code scopes} are
|
||||
* the scopes the authorization request asked for, which a V2 lambda may branch on.
|
||||
*/
|
||||
CognitoService.ClaimsOverride preTokenGenerationForHostedAuth(UserPool pool, UserPoolClient client,
|
||||
CognitoUser user, List<String> scopes) {
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_HostedAuth", scopes);
|
||||
}
|
||||
|
||||
private static String resolveTriggerArn(UserPool pool, String triggerKey) {
|
||||
|
||||
+2
-2
@@ -417,8 +417,8 @@ public class CognitoOAuthController {
|
||||
try {
|
||||
UserPool pool = cognitoService.describeUserPool(consumedCode.userPoolId());
|
||||
CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId());
|
||||
Map<String, Object> authentication = cognitoService.generateAuthResult(user, pool, client,
|
||||
nonceClaim(consumedCode.nonce()));
|
||||
Map<String, Object> authentication = cognitoService.generateAuthResultForHostedAuth(user, pool, client,
|
||||
nonceClaim(consumedCode.nonce()), consumedCode.scopes());
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("access_token", (String) authentication.get("AccessToken"));
|
||||
body.put("id_token", (String) authentication.get("IdToken"));
|
||||
|
||||
@@ -3296,6 +3296,85 @@ public class CognitoService implements ResourceProvider {
|
||||
return generateAuthResult(user, pool, client, override, originJti);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints the tokens the OAuth token endpoint returns for a redeemed authorization code, firing
|
||||
* PreTokenGeneration first, as AWS does for a hosted-UI sign-in, so a pool that customises its
|
||||
* claims gets the same tokens here as it does from {@code InitiateAuth}.
|
||||
*
|
||||
* <p>{@code protocolClaims} carries claims the OIDC flow itself owns, currently the request's
|
||||
* {@code nonce}. They are applied <em>after</em> the trigger's, so a trigger cannot displace them:
|
||||
* AWS likewise refuses to let this trigger override {@code nonce} and the other reserved claims.
|
||||
* Passing {@code null} for either side leaves the other's claims untouched. {@code requestedScopes}
|
||||
* are the scopes the authorization request asked for, narrowed to the ones the client may actually
|
||||
* use before the trigger is told about them.
|
||||
*/
|
||||
Map<String, Object> generateAuthResultForHostedAuth(CognitoUser user, UserPool pool, UserPoolClient client,
|
||||
ClaimsOverride protocolClaims, List<String> requestedScopes) {
|
||||
ClaimsOverride trigger = authFlowHandler.preTokenGenerationForHostedAuth(pool, client, user,
|
||||
scopesAllowedForClient(client, requestedScopes));
|
||||
return generateAuthResult(user, pool, client, mergeUnderProtocolClaims(trigger, protocolClaims));
|
||||
}
|
||||
|
||||
/**
|
||||
* The requested scopes the client is allowed to use, in the order requested and without duplicates.
|
||||
*
|
||||
* <p>An authorization request names its own scopes, and nothing checks them against the client's
|
||||
* AllowedOAuthScopes when the code is issued, so the stored code can carry a scope the client may
|
||||
* not use. A V2 trigger is free to grant claims or add scopes based on what it is told was
|
||||
* requested, so it is told only what the client was entitled to ask for. An unallowed scope is
|
||||
* dropped rather than refused, which is how AWS treats a scope that is not associated with the
|
||||
* client.
|
||||
*/
|
||||
private static List<String> scopesAllowedForClient(UserPoolClient client, List<String> requestedScopes) {
|
||||
if (requestedScopes == null || requestedScopes.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> allowed = client.getAllowedOAuthScopes();
|
||||
if (allowed == null || allowed.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> kept = new ArrayList<>();
|
||||
for (String scope : requestedScopes) {
|
||||
if (allowed.contains(scope) && !kept.contains(scope)) {
|
||||
kept.add(scope);
|
||||
}
|
||||
}
|
||||
return List.copyOf(kept);
|
||||
}
|
||||
|
||||
/**
|
||||
* Layers {@code protocolClaims} over {@code trigger}, keeping every other field the trigger set
|
||||
* (suppressions, groups, roles, scopes).
|
||||
*/
|
||||
private static ClaimsOverride mergeUnderProtocolClaims(ClaimsOverride trigger, ClaimsOverride protocolClaims) {
|
||||
if (trigger == null) {
|
||||
return protocolClaims;
|
||||
}
|
||||
if (protocolClaims == null) {
|
||||
return trigger;
|
||||
}
|
||||
return new ClaimsOverride(
|
||||
claimsWithProtocolLast(trigger.idClaimsToAddOrOverride(), protocolClaims.idClaimsToAddOrOverride()),
|
||||
trigger.idClaimsToSuppress(),
|
||||
claimsWithProtocolLast(trigger.accessClaimsToAddOrOverride(), protocolClaims.accessClaimsToAddOrOverride()),
|
||||
trigger.accessClaimsToSuppress(),
|
||||
trigger.scopesToAdd(), trigger.scopesToSuppress(),
|
||||
trigger.groupsToOverride(), trigger.iamRolesToOverride(), trigger.preferredRole());
|
||||
}
|
||||
|
||||
private static Map<String, Object> claimsWithProtocolLast(Map<String, Object> triggerClaims,
|
||||
Map<String, Object> protocolClaims) {
|
||||
if (protocolClaims == null || protocolClaims.isEmpty()) {
|
||||
return triggerClaims;
|
||||
}
|
||||
if (triggerClaims == null || triggerClaims.isEmpty()) {
|
||||
return protocolClaims;
|
||||
}
|
||||
Map<String, Object> merged = new HashMap<>(triggerClaims);
|
||||
merged.putAll(protocolClaims);
|
||||
return merged;
|
||||
}
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti));
|
||||
|
||||
Reference in new issue
Block a user