fix(cognito): scope OAuth tokens to the requested scopes (#4771)

* fix(cognito): scope OAuth tokens to the requested scopes

* fix(cognito): require the admin scope on access-token operations

* fix(cognito): bind an authorization code to the scopes granted at authorize

* fix(cognito): keep the provider's requested scopes apart from Cognito's grant
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-01 13:54:01 -04:00
1 parent c60da16c54
commit f1d718cae2
11 files changed
+642 -115

No files matched your search

@@ -1778,7 +1778,7 @@ final class CognitoAuthFlowHandler {
*
* <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.
* the scopes the authorization request was granted, which a V2 lambda may branch on.
*/
CognitoService.ClaimsOverride preTokenGenerationForHostedAuth(UserPool pool, UserPoolClient client,
CognitoUser user, List<String> scopes) {
@@ -40,18 +40,23 @@ public class CognitoFederationService {
this.clock = clock;
}
/** Grants exactly the requested {@code scopes}. */
public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List<String> scopes,
String nonce, String providerName) {
return beginAuthorization(userPoolId, clientId, redirectUri, scopes, nonce, providerName, null, null);
return beginAuthorization(userPoolId, clientId, redirectUri, scopes, scopes, nonce, providerName, null, null);
}
/**
* @param codeChallenge the relying party's S256 PKCE challenge, or null. It stays with Cognito:
* the relying party proves it at Cognito's token endpoint, not the provider's.
* @param requestedScopes the scopes the authorization request named, which the provider is asked
* for when it has no {@code authorize_scopes}
* @param grantedScopes the scopes Cognito granted the request, which the transaction and then
* the authorization code keep; they never reach the provider
* @param codeChallenge the relying party's S256 PKCE challenge, or null. It stays with Cognito:
* the relying party proves it at Cognito's token endpoint, not the provider's.
*/
public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List<String> scopes,
String nonce, String providerName, String relyingPartyState,
String codeChallenge) {
public String beginAuthorization(String userPoolId, String clientId, String redirectUri,
List<String> requestedScopes, List<String> grantedScopes, String nonce,
String providerName, String relyingPartyState, String codeChallenge) {
IdentityProvider provider = cognitoService.describeIdentityProvider(userPoolId, providerName);
requireOidcProvider(provider);
String authorizeEndpoint = requiredProviderDetail(provider, "authorize_url", "authorize endpoint");
@@ -59,14 +64,14 @@ public class CognitoFederationService {
validateAuthorizeEndpoint(authorizeEndpoint, provider.getProviderName());
Instant expiresAt = clock.instant().plus(TRANSACTION_LIFETIME);
CognitoAuthorizationTransaction transaction = new CognitoAuthorizationTransaction(userPoolId, clientId,
redirectUri, scopes, nonce, providerName, relyingPartyState, codeChallenge, expiresAt);
redirectUri, grantedScopes, nonce, providerName, relyingPartyState, codeChallenge, expiresAt);
String state = stateStore.putTransaction(transaction);
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("response_type", "code");
parameters.put("client_id", providerClientId);
parameters.put("redirect_uri", cognitoService.getIdentityProviderCallbackEndpoint(userPoolId));
parameters.put("scope", providerScopes(provider, scopes));
parameters.put("scope", providerScopes(provider, requestedScopes));
parameters.put("state", state);
if (nonce != null && !nonce.isBlank()) {
parameters.put("nonce", nonce);
@@ -57,9 +57,11 @@ public class CognitoManagedLoginService {
* Issues an authorization code to the user of the browser's session, or nothing when there is
* no session for the client's pool. Every pool's session travels in the same cookie on Floci's
* own host, so a session of one pool must never sign its user in to another.
*
* @param grantedScopes the scopes the authorization request was granted, which the code keeps
*/
public Optional<String> issueAuthorizationCode(String sessionId, UserPoolClient client, String redirectUri,
List<String> scopes, String nonce, String codeChallenge) {
List<String> grantedScopes, String nonce, String codeChallenge) {
Optional<CognitoManagedLoginSession> session = stateStore.findSession(sessionId)
.filter(candidate -> candidate.userPoolId().equals(client.getUserPoolId()));
if (session.isEmpty()) {
@@ -70,7 +72,7 @@ public class CognitoManagedLoginService {
return Optional.empty();
}
CognitoAuthorizationCode code = new CognitoAuthorizationCode(client.getUserPoolId(), client.getClientId(),
session.get().username(), redirectUri, scopes, nonce, codeChallenge,
session.get().username(), redirectUri, grantedScopes, nonce, codeChallenge,
clock.instant().plus(AUTHORIZATION_CODE_LIFETIME));
return Optional.of(stateStore.putAuthorizationCode(code));
}
@@ -106,10 +106,11 @@ public class CognitoOAuthController {
if (check.error() != null) {
return check.error();
}
List<String> requestedScopes = splitScopes(scope);
try {
String location = federationService.beginAuthorization(check.client().getUserPoolId(), clientId,
redirectUri, splitScopes(scope), trimToNull(nonce), providerName, relyingPartyState,
trimToNull(codeChallenge));
redirectUri, requestedScopes, CognitoService.grantedScopes(check.client(), requestedScopes),
trimToNull(nonce), providerName, relyingPartyState, trimToNull(codeChallenge));
return Response.status(Response.Status.FOUND).location(URI.create(location)).build();
} catch (AwsException e) {
return oauthError("invalid_request", e.getMessage());
@@ -421,7 +422,10 @@ public class CognitoOAuthController {
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"));
// Minted only for a grant with openid; AWS leaves the field out otherwise.
if (authentication.get("IdToken") instanceof String idToken) {
body.put("id_token", idToken);
}
body.put("refresh_token", (String) authentication.get("RefreshToken"));
body.put("expires_in", ((Number) authentication.get("ExpiresIn")).longValue());
body.put("token_type", (String) authentication.get("TokenType"));
@@ -459,16 +463,19 @@ public class CognitoOAuthController {
return redirect(request.redirectUri(), parameters);
}
/** Binds the code to the scopes the request is granted now; redemption never widens them. */
private Optional<String> issueAuthorizationCode(String sessionId, UserPoolClient client,
AuthorizationRequest request) {
return managedLoginService.issueAuthorizationCode(sessionId, client, request.redirectUri(),
splitScopes(request.scope()), trimToNull(request.nonce()), trimToNull(request.codeChallenge()));
CognitoService.grantedScopes(client, splitScopes(request.scope())), trimToNull(request.nonce()),
trimToNull(request.codeChallenge()));
}
/**
* The checks every authorization request passes, for managed login and federation alike. Errors
* are 400 JSON, including those found after redirect_uri is known to be registered, where AWS
* redirects the error to it instead.
* are 400 JSON, including most of those found after redirect_uri is known to be registered, where
* AWS redirects the error to it instead. A scope the client is not allowed is redirected, as AWS
* does.
*/
private AuthorizationCheck checkAuthorizationRequest(ContainerRequestContext requestContext,
AuthorizationRequest request) {
@@ -496,9 +503,28 @@ public class CognitoOAuthController {
if (pkceError != null) {
return AuthorizationCheck.rejected(oauthError("invalid_request", pkceError));
}
if (!allowsEveryScope(client, splitScopes(request.scope()))) {
return AuthorizationCheck.rejected(invalidScopeRedirect(request));
}
return check;
}
private static boolean allowsEveryScope(UserPoolClient client, List<String> scopes) {
List<String> allowed = client.getAllowedOAuthScopes();
return scopes.isEmpty() || (allowed != null && allowed.containsAll(scopes));
}
/** AWS's redirect for a scope the client is not allowed, parameters in the order AWS sends them. */
private Response invalidScopeRedirect(AuthorizationRequest request) {
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("error_description", "invalid_scope");
if (request.state() != null) {
parameters.put("state", request.state());
}
parameters.put("error", "invalid_request");
return redirect(request.redirectUri(), parameters);
}
/** An authorization request that managed login answers, at the authorize, login, and logout endpoints. */
private AuthorizationCheck checkManagedLoginRequest(ContainerRequestContext requestContext,
AuthorizationRequest request) {
@@ -101,6 +101,9 @@ public class CognitoService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(CognitoService.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String INVALID_ACCESS_TOKEN_MESSAGE = "Invalid access token";
/** The scope of every access token from an API sign-in such as InitiateAuth, and what the user's own operations need. */
private static final String USER_ADMIN_SCOPE = "aws.cognito.signin.user.admin";
private static final List<String> API_SIGN_IN_SCOPES = List.of(USER_ADMIN_SCOPE);
private static final String IDENTITIES_ATTRIBUTE = "identities";
@@ -2000,6 +2003,7 @@ public class CognitoService implements ResourceProvider {
}
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
CognitoUser user;
@@ -3012,6 +3016,7 @@ public class CognitoService implements ResourceProvider {
public void changePassword(String accessToken, String previousPassword, String proposedPassword) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
@@ -3079,6 +3084,7 @@ public class CognitoService implements ResourceProvider {
public Map<String, Object> getUser(String accessToken) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
@@ -3107,7 +3113,7 @@ public class CognitoService implements ResourceProvider {
}
throw e;
}
requireScope(accessToken, "aws.cognito.signin.user.admin");
requireScope(accessToken, USER_ADMIN_SCOPE);
CognitoUser user = adminGetUser(token.poolId(), token.username());
Map<String, Object> result = new LinkedHashMap<>();
@@ -3137,6 +3143,7 @@ public class CognitoService implements ResourceProvider {
}
throw e;
}
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
@@ -3195,7 +3202,7 @@ public class CognitoService implements ResourceProvider {
}
throw e;
}
requireScope(accessToken, "aws.cognito.signin.user.admin");
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
@@ -3242,6 +3249,7 @@ public class CognitoService implements ResourceProvider {
public List<Map<String, Object>> updateUserAttributes(String accessToken, Map<String, String> attributes) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
@@ -3336,6 +3344,7 @@ public class CognitoService implements ResourceProvider {
public void deleteUserAttributes(String accessToken, List<String> attributeNames) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
String username = token.username();
String poolId = token.poolId();
@@ -3531,37 +3540,51 @@ public class CognitoService implements ResourceProvider {
* <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.
* Passing {@code null} for either side leaves the other's claims untouched.
*
* <p>{@code grantedScopes} are the scopes the authorization code was granted at authorize (see
* {@link #grantedScopes}). The access token carries them, narrowed to the ones the client still
* allows, rather than the {@code aws.cognito.signin.user.admin} of an API sign-in, and the ID
* token is minted only when they include {@code openid}, as on AWS. The trigger is told the same
* scopes, and a V2 trigger's scope changes apply on top of 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));
ClaimsOverride protocolClaims, List<String> grantedScopes) {
List<String> scopes = scopesStillAllowed(client, grantedScopes);
ClaimsOverride trigger = authFlowHandler.preTokenGenerationForHostedAuth(pool, client, user, scopes);
return generateAuthResult(user, pool, client, mergeUnderProtocolClaims(trigger, protocolClaims),
UUID.randomUUID().toString(), scopes, scopes.contains("openid"));
}
/**
* 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.
* The scopes an authorization request is granted at authorize, where the authorization code is
* bound to them: every scope the client allows when it asked for none, as on AWS, and otherwise
* the requested scopes the client allows, in the order requested and without duplicates.
*/
private static List<String> scopesAllowedForClient(UserPoolClient client, List<String> requestedScopes) {
if (requestedScopes == null || requestedScopes.isEmpty()) {
return List.of();
}
static List<String> grantedScopes(UserPoolClient client, List<String> requestedScopes) {
List<String> allowed = client.getAllowedOAuthScopes();
if (allowed == null || allowed.isEmpty()) {
return List.of();
}
if (requestedScopes == null || requestedScopes.isEmpty()) {
return List.copyOf(new LinkedHashSet<>(allowed));
}
return scopesStillAllowed(client, requestedScopes);
}
/**
* The code's granted scopes that the client still allows, in their order and without duplicates.
* The client's AllowedOAuthScopes can change between authorize and redemption: a scope removed in
* between is dropped, and one added in between is never granted. A V2 trigger is free to grant
* claims or add scopes based on what it is told was granted, so it is told only these.
*/
private static List<String> scopesStillAllowed(UserPoolClient client, List<String> grantedScopes) {
List<String> allowed = client.getAllowedOAuthScopes();
if (allowed == null || grantedScopes == null) {
return List.of();
}
List<String> kept = new ArrayList<>();
for (String scope : requestedScopes) {
for (String scope : grantedScopes) {
if (allowed.contains(scope) && !kept.contains(scope)) {
kept.add(scope);
}
@@ -3603,9 +3626,17 @@ public class CognitoService implements ResourceProvider {
}
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) {
return generateAuthResult(user, pool, client, override, originJti, API_SIGN_IN_SCOPES, true);
}
private Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client,
ClaimsOverride override, String originJti,
List<String> accessScopes, boolean withIdToken) {
Map<String, Object> auth = new HashMap<>();
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti));
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti));
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti, accessScopes));
if (withIdToken) {
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti, accessScopes));
}
auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), originJti));
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
auth.put("TokenType", "Bearer");
@@ -3617,6 +3648,15 @@ public class CognitoService implements ResourceProvider {
}
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override, String originJti) {
return generateSignedJwt(user, pool, type, client, override, originJti, API_SIGN_IN_SCOPES);
}
/**
* @param accessScopes the access token's {@code scope} claim before any V2 trigger changes, left
* out when empty; ignored for an ID token
*/
private String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client,
ClaimsOverride override, String originJti, List<String> accessScopes) {
String header = encodeJwtHeader(pool);
long now = System.currentTimeMillis() / 1000L;
long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type);
@@ -3632,7 +3672,9 @@ public class CognitoService implements ResourceProvider {
claims.put("iat", now);
if ("access".equals(type)) {
claims.put("username", user.getUsername());
claims.put("scope", "aws.cognito.signin.user.admin");
if (!accessScopes.isEmpty()) {
claims.put("scope", String.join(" ", accessScopes));
}
} else if ("id".equals(type)) {
claims.put("cognito:username", user.getUsername());
}
@@ -4615,9 +4657,10 @@ public class CognitoService implements ResourceProvider {
/**
* The scopes in the space-separated {@code scope} claim of an already-verified access token
* (call after {@link #verifyAccessToken}), empty when the claim is absent or blank. Every access
* token Floci mints sets the claim (see {@code generateSignedJwt}); it is missing only when a
* PreTokenGeneration trigger removed it, and such a token grants no scope.
* (call after {@link #verifyAccessToken}), empty when the claim is absent or blank. An access
* token lacks the claim only when a PreTokenGeneration trigger removed it, or when an
* authorization code was granted no scope because its client allows none, which AWS does not let
* an OAuth client do. Such a token grants no scope.
*/
private Set<String> extractScopesFromToken(String token) {
try {
@@ -4639,10 +4682,10 @@ public class CognitoService implements ResourceProvider {
}
/**
* AWS requires an access token carrying the given scope for some operations (for example
* VerifyUserAttribute requires aws.cognito.signin.user.admin), and refuses a token with no
* scope claim. Call after {@link #verifyAccessToken}, which already confirms the token is a
* valid, unexpired access token; this only adds the scope check on top.
* AWS requires an access token carrying the given scope for some operations (every operation
* authorized by the user's access token requires aws.cognito.signin.user.admin), and refuses a
* token with no scope claim. Call after {@link #verifyAccessToken}, which already confirms the
* token is a valid, unexpired access token; this only adds the scope check on top.
*/
void requireScope(String accessToken, String requiredScope) {
Set<String> scopes = extractScopesFromToken(accessToken);
@@ -5149,6 +5192,7 @@ public class CognitoService implements ResourceProvider {
Boolean emailPreferred) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
synchronized (userLock(token.poolId(), token.username())) {
setUserMFAPreferenceUnderUserLock(
token.poolId(), token.username(), emailEnabled, emailPreferred);
@@ -4,9 +4,11 @@ import java.time.Instant;
import java.util.List;
/**
* A one-time authorization code. {@code nonce} and {@code codeChallenge} are the authorization
* request's values, or null when it sent none; the token endpoint puts the nonce in the ID token
* and requires a matching {@code code_verifier} when there is a challenge.
* A one-time authorization code. {@code scopes} are the scopes the authorization request was granted
* when the code was issued, which redemption narrows to the client's current AllowedOAuthScopes but
* never widens. {@code nonce} and {@code codeChallenge} are the authorization request's values, or
* null when it sent none; the token endpoint puts the nonce in the ID token and requires a matching
* {@code code_verifier} when there is a challenge.
*/
public record CognitoAuthorizationCode(
String userPoolId,