diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 059c3b94bd..800efe5437 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -198,6 +198,17 @@ further divergences, both deliberate: | ForgotPassword | Starts the local forgot-password flow for a user. | | ConfirmForgotPassword | Completes the forgot-password flow by setting a replacement password. | +As on AWS, every operation authorized by the user's access token (`GetUser`, +`GetUserAuthFactors`, `UpdateUserAttributes`, `DeleteUserAttributes`, `ChangePassword`, +`GetUserAttributeVerificationCode`, `VerifyUserAttribute`, `SetUserMFAPreference`, +`GlobalSignOut`, and `AssociateSoftwareToken` and `VerifySoftwareToken` with an `AccessToken`) +requires the token's `scope` to include `aws.cognito.signin.user.admin`. Tokens from +`InitiateAuth` and the other API sign-in flows always carry it; a token from the OAuth token +endpoint carries it only when the authorization request asked for it, or asked for no scope and +the client allows it. Without it the call fails with `NotAuthorizedException: +Access Token does not have required scopes`, as it does for a token with no `scope` claim at all, +which a pre token generation trigger leaves when it suppresses every scope. + ### Authentication | Action | Description | @@ -367,7 +378,9 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same 1. `GET /cognito-idp/oauth2/authorize` redirects to `/cognito-idp/login` with the request's parameters. If the browser already has a managed login session in the pool, it skips the - form and redirects straight to the callback with a code, as AWS does. + form and redirects straight to the callback with a code, as AWS does. A `scope` the client's + `AllowedOAuthScopes` does not include is refused first, as on AWS, with a redirect to the + callback carrying `error=invalid_request`, `error_description=invalid_scope` and the `state`. 2. `GET /cognito-idp/login` renders a plain username and password form. The form carries the request in hidden fields and a CSRF token that must match the `XSRF-TOKEN` cookie set with it. 3. `POST /cognito-idp/login` checks the password as `USER_PASSWORD_AUTH` does, including @@ -378,9 +391,12 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same 4. `POST /cognito-idp/oauth2/token` redeems the code. It invokes the pre token generation trigger with triggerSource `TokenGeneration_HostedAuth`, as AWS does for a hosted-UI sign-in, so a pool that customises its claims gets the same tokens here as from - `InitiateAuth`. The trigger is told the scopes the request asked for, narrowed to the - client's `AllowedOAuthScopes`, since the authorize endpoint does not check them itself. The - ID token carries the request's `nonce`, which the trigger cannot override. + `InitiateAuth`. The access token's `scope` is the scopes the request asked for, or every + scope in the client's `AllowedOAuthScopes` when it asked for none, as on AWS, and the + trigger is told the same scopes. The code keeps the scopes granted when it was issued: a + scope the client is allowed only afterwards is not added, and one it no longer allows is + dropped. A V2 trigger's `scopesToAdd` and `scopesToSuppress` apply on top of them. The ID token is issued only when the scopes include `openid`, and it carries + the request's `nonce`, which the trigger cannot override. 5. `GET /cognito-idp/logout?client_id=...&logout_uri=...` ends the session and redirects to `logout_uri`, which must be one of the client's `LogoutURLs`. With `redirect_uri` and `response_type=code` instead of `logout_uri`, it ends the session and redirects to the @@ -399,7 +415,8 @@ Differences from AWS: confirmed, sees an error on the form instead. Sign-up, forgot-password, MFA and passkey pages are not served, and `prompt`, `login_hint`, `lang` and `idp_identifier` are ignored. - **Errors are JSON.** An authorization request error returns `400` with an OAuth error body, - even after `redirect_uri` is validated, where AWS redirects the error to the callback. + even after `redirect_uri` is validated, where AWS redirects the error to the callback. The + exception is an unallowed `scope`, which is redirected as on AWS. - **Relative redirect.** The redirect from `/oauth2/authorize` to the sign-in form has a relative `Location`, where AWS's is absolute. - **One session cookie per host.** Floci's own host serves every pool, so signing in to a @@ -450,7 +467,8 @@ curl -s -b jar -o /dev/null -w '%{http_code} %{redirect_url}\n' \ - It requires `AllowedOAuthFlowsUserPoolClient=true` and `AllowedOAuthFlows=["client_credentials"]`. - It doesn't require a Cognito domain. - Client-credentials returns only `access_token`, `token_type`, and `expires_in`; authorization-code - redemption returns the Cognito access, ID and refresh token set. + redemption returns the Cognito access and refresh tokens, and an ID token when the granted scopes + include `openid`. - It validates requested OAuth scopes against the app client's `AllowedOAuthScopes` and the pool's registered resource-server scopes. - It advertises the prefixed token endpoint in `/{userPoolId}/.well-known/openid-configuration`, or `https:///oauth2/token` when the pool has a custom domain (see Custom domains above). @@ -486,8 +504,8 @@ literal `Username` you supply, unchanged. Floci mirrors AWS's access-token / ID-token split: - **Access token:** `sub`, `username` (the UUID), `scope` (`aws.cognito.signin.user.admin` for API - sign-in), `client_id`, `cognito:groups`, `jti`/`origin_jti`. It does **not** carry `cognito:username` - or user attributes like `email`. + sign-in, the granted OAuth scopes for an authorization code), `client_id`, `cognito:groups`, + `jti`/`origin_jti`. It does **not** carry `cognito:username` or user attributes like `email`. - **ID token:** `sub`, `cognito:username`, `aud`, and readable user attributes (`email`, `email_verified`, `phone_number`, `custom:*`, ...). Attribute claims are filtered by the app client's `ReadAttributes` (an unset/empty list means all attributes are readable). diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index 15cafae333..c649c8794b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -1778,7 +1778,7 @@ final class CognitoAuthFlowHandler { * *

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 scopes) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java index f4b52b78f8..ebcc1d9e1f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java @@ -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 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 scopes, - String nonce, String providerName, String relyingPartyState, - String codeChallenge) { + public String beginAuthorization(String userPoolId, String clientId, String redirectUri, + List requestedScopes, List 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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java index a8731e4871..7c3083a71d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java @@ -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 issueAuthorizationCode(String sessionId, UserPoolClient client, String redirectUri, - List scopes, String nonce, String codeChallenge) { + List grantedScopes, String nonce, String codeChallenge) { Optional 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)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java index f3c034cf42..6ef0b62f44 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java @@ -106,10 +106,11 @@ public class CognitoOAuthController { if (check.error() != null) { return check.error(); } + List 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 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 scopes) { + List 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 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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index bf12d155c5..4208e774c0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -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 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 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 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> updateUserAttributes(String accessToken, Map 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 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 { *

{@code protocolClaims} carries claims the OIDC flow itself owns, currently the request's * {@code nonce}. They are applied after 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. + * + *

{@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 generateAuthResultForHostedAuth(CognitoUser user, UserPool pool, UserPoolClient client, - ClaimsOverride protocolClaims, List requestedScopes) { - ClaimsOverride trigger = authFlowHandler.preTokenGenerationForHostedAuth(pool, client, user, - scopesAllowedForClient(client, requestedScopes)); - return generateAuthResult(user, pool, client, mergeUnderProtocolClaims(trigger, protocolClaims)); + ClaimsOverride protocolClaims, List grantedScopes) { + List 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. - * - *

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 scopesAllowedForClient(UserPoolClient client, List requestedScopes) { - if (requestedScopes == null || requestedScopes.isEmpty()) { - return List.of(); - } + static List grantedScopes(UserPoolClient client, List requestedScopes) { List 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 scopesStillAllowed(UserPoolClient client, List grantedScopes) { + List allowed = client.getAllowedOAuthScopes(); + if (allowed == null || grantedScopes == null) { + return List.of(); + } List 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 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 generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, + ClaimsOverride override, String originJti, + List accessScopes, boolean withIdToken) { Map 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 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 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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java index d13c47311a..5500a7d406 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java @@ -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, diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java index 3bfa5eedd8..8ba0425c49 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java @@ -137,7 +137,7 @@ class CognitoFederationServiceTest { String redirect = federationService.beginAuthorization( pool.getId(), "cognito-client", "https://application.example.test/callback", - List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state", null); + List.of("openid"), List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state", null); CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(queryValue(redirect, "state")).orElseThrow(); assertEquals("relying-party-state", transaction.relyingPartyState()); @@ -149,7 +149,7 @@ class CognitoFederationServiceTest { String challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; String redirect = federationService.beginAuthorization( pool.getId(), "cognito-client", "https://application.example.test/callback", - List.of("openid"), "nonce-value", "ExampleOidc", null, challenge); + List.of("openid"), List.of("openid"), "nonce-value", "ExampleOidc", null, challenge); String authorizationCode = federationService.completeAuthorization(queryValue(redirect, "state"), "provider-code"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index 33fc15f3f8..d63948755a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -34,6 +34,7 @@ import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @@ -854,9 +855,9 @@ class CognitoLambdaTriggersTest { } /** - * Nothing checks an authorization request's scopes against the client's AllowedOAuthScopes when the - * code is issued, so the stored code can name a scope the client may not use. A V2 trigger may grant - * claims or scopes from what it is told was requested, so it must never be told about one. + * The authorize endpoint refuses a scope the client may not use, but a client's AllowedOAuthScopes + * can change before its code is redeemed. A V2 trigger may grant claims or scopes from what it is + * told was requested, so it must never be told about one the client no longer allows. */ @Test @SuppressWarnings("unchecked") @@ -914,7 +915,7 @@ class CognitoLambdaTriggersTest { void redemptionKeepsTheRequestNonceOverATriggerThatTriesToChangeIt() { UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); seedUser(pool, "alice", "Perm1234!"); - UserPoolClient client = createClient(pool); + UserPoolClient client = createOAuthClient(pool, List.of("openid")); CognitoUser user = service.adminGetUser(pool.getId(), "alice"); when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) .thenReturn(ok(Map.of("claimsOverrideDetails", Map.of( @@ -940,7 +941,7 @@ class CognitoLambdaTriggersTest { void redemptionMintsTokensWhenNoPreTokenGenerationTriggerIsConfigured() { UserPool pool = createPoolWithLambdaConfig(Map.of()); seedUser(pool, "alice", "Perm1234!"); - UserPoolClient client = createClient(pool); + UserPoolClient client = createOAuthClient(pool, List.of("openid")); CognitoUser user = service.adminGetUser(pool.getId(), "alice"); Map auth = service.generateAuthResultForHostedAuth(user, pool, client, @@ -960,6 +961,127 @@ class CognitoLambdaTriggersTest { verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any()); } + /** + * AWS grants every scope the client allows to a request that names none, and that grant is what + * the trigger is told and what the access token carries. + */ + @Test + @SuppressWarnings("unchecked") + void aRequestWithoutScopesIsGrantedEveryAllowedScope() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createOAuthClient(pool, List.of("openid", "email", "aws.cognito.signin.user.admin")); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + ArgumentCaptor payloadCap = ArgumentCaptor.forClass(byte[].class); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any())) + .thenReturn(ok(Map.of())); + + List granted = CognitoService.grantedScopes(client, List.of()); + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, granted); + + assertEquals(List.of("openid", "email", "aws.cognito.signin.user.admin"), granted); + Map event; + Map accessClaims; + try { + event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {}); + accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertEquals(granted, ((Map) event.get("request")).get("scopes")); + assertEquals(Set.copyOf(granted), Set.of(((String) accessClaims.get("scope")).split(" "))); + assertNotNull(auth.get("IdToken")); + } + + /** Redemption issues the code's grant and never widens it, even when that grant is empty. */ + @Test + void redemptionNeverWidensTheCodesGrant() { + UserPool pool = createPoolWithLambdaConfig(Map.of()); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createOAuthClient(pool, List.of("openid", "email")); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of()); + + Map accessClaims; + try { + accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertFalse(accessClaims.containsKey("scope"), "an empty grant stays empty: " + accessClaims); + assertFalse(auth.containsKey("IdToken")); + } + + /** A V2 trigger that suppresses every scope of the grant leaves no scope claim. */ + @Test + void preTokenGenerationV2SuppressingTheWholeCodeGrantRemovesTheScopeClaim() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createOAuthClient(pool, List.of("openid", "email")); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of("scopesToSuppress", List.of("email")))))); + + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email")); + + Map accessClaims; + try { + accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertFalse(accessClaims.containsKey("scope"), "suppressing the only granted scope leaves none: " + accessClaims); + } + + /** Only a grant with {@code openid} gets an ID token, and the access token carries just the grant. */ + @Test + void redemptionWithoutOpenidMintsNoIdToken() { + UserPool pool = createPoolWithLambdaConfig(Map.of()); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createOAuthClient(pool, List.of("openid", "email")); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email")); + + Map accessClaims; + try { + accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertEquals("email", accessClaims.get("scope")); + assertFalse(auth.containsKey("IdToken"), "no openid, no ID token: " + auth.keySet()); + assertNotNull(auth.get("RefreshToken")); + } + + /** V2 scope changes apply on top of the grant, not on top of a fixed default scope. */ + @Test + void preTokenGenerationV2ScopeChangesApplyOnTopOfTheCodeGrant() { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createOAuthClient(pool, List.of("openid", "email", "profile")); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "scopesToSuppress", List.of("email"), + "scopesToAdd", List.of("aws.cognito.signin.user.admin")))))); + + Map auth = service.generateAuthResultForHostedAuth(user, pool, client, null, + List.of("openid", "email")); + + Map accessClaims; + try { + accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException(e); + } + assertEquals(Set.of("openid", "aws.cognito.signin.user.admin"), + Set.of(((String) accessClaims.get("scope")).split(" "))); + } + @Test void managedLoginPreAuthenticationErrorBlocksSignIn() { UserPool pool = createPoolWithLambdaConfig(Map.of( diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java index 15aacf359a..da1a0c44cc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java @@ -16,9 +16,11 @@ import org.mockito.ArgumentCaptor; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -39,6 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** @@ -60,6 +64,7 @@ class CognitoManagedLoginIntegrationTest { private static final Pattern HIDDEN_FIELD = Pattern.compile(""); private static final Pattern FORM_ACTION = Pattern.compile("

"); private static final String PRE_TOKEN_GENERATION_ARN = "arn:aws:lambda:::pre-token-generation"; + private static final String ADMIN_SCOPE = "aws.cognito.signin.user.admin"; private static final ObjectMapper MAPPER = new ObjectMapper(); /** Only the PreTokenGeneration trigger is configured on any pool here, so nothing else invokes it. */ @@ -236,52 +241,196 @@ class CognitoManagedLoginIntegrationTest { } /** - * The authorize endpoint stores the scopes the request named without checking them against the - * client's AllowedOAuthScopes, so a request can carry one the client may not use. A V2 trigger can - * grant claims or scopes from what it is told was requested, so an unallowed scope must not reach it. + * AWS refuses a scope outside the client's AllowedOAuthScopes at the authorize endpoint, before + * the sign-in form and even for a browser that is already signed in, by redirecting to the + * callback with {@code error=invalid_request} and {@code error_description=invalid_scope}. No + * code is issued, so a V2 trigger never hears of the scope. */ @Test - void aScopeTheClientIsNotAllowedDoesNotReachTheTrigger() throws Exception { - Pool pool = newPoolWithPreTokenGenerationTrigger(); - Map query = authorizeRequest(pool.clientId()); - query.put("scope", "openid email admin/superuser"); - ArgumentCaptor event = ArgumentCaptor.forClass(byte[].class); - when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), event.capture(), any())) - .thenReturn(triggerResponse(Map.of())); + void aScopeTheClientIsNotAllowedIsRedirectedToTheCallbackAsInvalidScope() throws Exception { + Pool withoutAdmin = newPoolWithPreTokenGenerationTrigger(); + Pool withAdmin = newPool(List.of("openid", "email", ADMIN_SCOPE)); + String session = signIn(null, withoutAdmin, authorizeRequest(withoutAdmin.clientId())).getCookie("cognito"); + Map requests = new LinkedHashMap<>(); + requests.put("openid " + ADMIN_SCOPE, withoutAdmin); + requests.put("openid email admin/superuser", withoutAdmin); + requests.put("openid phone", withAdmin); - Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER); + for (Map.Entry request : requests.entrySet()) { + Map query = withField(authorizeRequest(request.getValue().clientId()), "scope", + request.getKey()); + for (String sessionCookie : new String[] {null, session}) { + String location = browserGet(null, "/cognito-idp/oauth2/authorize", query, sessionCookie) + .then().statusCode(302).extract().header("Location"); - tokens.then().statusCode(200); - assertEquals(List.of("openid", "email"), - MAPPER.convertValue(MAPPER.readTree(event.getValue()).path("request").path("scopes"), List.class), - "admin/superuser is not in the client's AllowedOAuthScopes, so the trigger never sees it"); + assertTrue(location.startsWith(CALLBACK + "?"), location); + assertEquals(Map.of("error", "invalid_request", "error_description", "invalid_scope", + "state", "client-state"), queryOf(location), "scope=" + request.getKey()); + } + } + verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any()); + } + + /** AWS: the requested scopes, or every scope the client allows when the request names none. */ + @Test + void theAccessTokenCarriesTheRequestedScopesOrEveryAllowedScopeWhenNoneAreRequested() throws Exception { + Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE)); + Map> expected = new LinkedHashMap<>(); + expected.put("openid email", Set.of("openid", "email")); + expected.put("openid email " + ADMIN_SCOPE, Set.of("openid", "email", ADMIN_SCOPE)); + expected.put(null, Set.of("openid", "email", ADMIN_SCOPE)); + + for (Map.Entry> request : expected.entrySet()) { + Map query = withField(authorizeRequest(pool.clientId()), "scope", request.getKey()); + + Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER); + + tokens.then().statusCode(200); + assertEquals(request.getValue(), scopes(tokens.path("access_token")), "scope=" + request.getKey()); + assertEquals(Set.of("access_token", "id_token", "refresh_token", "expires_in", "token_type"), + fieldNames(tokens), "scope=" + request.getKey()); + } + } + + /** AWS issues an ID token only for a request with {@code openid}. */ + @Test + void withoutOpenidTheTokenEndpointIssuesNoIdToken() throws Exception { + Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE)); + + for (String requested : new String[] {"email", ADMIN_SCOPE}) { + Map query = withField(authorizeRequest(pool.clientId()), "scope", requested); + + Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER); + + tokens.then().statusCode(200); + assertEquals(Set.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(tokens), + "scope=" + requested); + assertEquals(Set.of(requested), scopes(tokens.path("access_token"))); + } } /** - * GetUserAuthFactors needs {@code aws.cognito.signin.user.admin} in the access token's scope. - * Floci stamps that scope on every code-grant access token whatever the request asked for, so a - * V2 trigger reshapes this token's scope to the {@code openid email} the request named. + * A code carries the scopes granted when it was issued. A request without a scope is granted + * every scope the client allows then, so a scope the client is allowed only afterwards is not + * added when the code is redeemed. */ @Test - void codeGrantAccessTokenWithoutTheAdminScopeCannotReadAuthFactors() throws Exception { - String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of( - "scopesToAdd", List.of("openid", "email"), - "scopesToSuppress", List.of("aws.cognito.signin.user.admin"))); - assertEquals("openid email", jwtPayload(accessToken).path("scope").asText()); + void aScopeTheClientIsAllowedAfterTheCodeWasIssuedIsNotAdded() throws Exception { + Pool pool = newPool(); + String code = code(signIn(null, pool, withField(authorizeRequest(pool.clientId()), "scope", null))); + allowScopes(pool, List.of("openid", "email", ADMIN_SCOPE)); - cognitoAction("GetUserAuthFactors", """ - {"AccessToken":"%s"} - """.formatted(accessToken)) + Response tokens = redeem(null, pool.clientId(), code, VERIFIER); + + tokens.then().statusCode(200); + assertEquals(Set.of("openid", "email"), scopes(tokens.path("access_token"))); + } + + /** + * A scope the client no longer allows is dropped from a code issued before the change, here + * one issued to a browser that was already signed in. + */ + @Test + void aScopeTheClientNoLongerAllowsIsDroppedFromAnIssuedCode() throws Exception { + Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE)); + String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito"); + String code = code(browserGet(null, "/cognito-idp/oauth2/authorize", + withField(authorizeRequest(pool.clientId()), "scope", null), session)); + allowScopes(pool, List.of("openid", ADMIN_SCOPE)); + + Response tokens = redeem(null, pool.clientId(), code, VERIFIER); + + tokens.then().statusCode(200); + assertEquals(Set.of("openid", ADMIN_SCOPE), scopes(tokens.path("access_token"))); + } + + /** + * Floci lets an OAuth client allow no scopes. Its code grant has no scope claim and no ID token, + * and none of the user's own operations accepts a token without a scope. + */ + @Test + void aCodeGrantOfAClientThatAllowsNoScopesCannotCallTheUsersOwnOperations() throws Exception { + Pool pool = newPool(List.of()); + + Response tokens = redeem(null, pool.clientId(), + code(signIn(null, pool, withField(authorizeRequest(pool.clientId()), "scope", null))), VERIFIER); + + tokens.then().statusCode(200); + assertEquals(Set.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(tokens)); + String accessToken = tokens.path("access_token"); + assertFalse(jwtPayload(accessToken).has("scope")); + cognitoAction("GetUser", "{\"AccessToken\":\"%s\"}".formatted(accessToken)) .then().statusCode(400) .body("__type", equalTo("NotAuthorizedException")) .body("message", equalTo("Access Token does not have required scopes")); } - /** A trigger that suppresses the token's only scope leaves no scope claim, which grants nothing. */ + /** + * {@code aws.cognito.signin.user.admin} is what lets an access token call the user's own API + * operations. A code-grant token requested without it is refused with AWS's message, and the + * refused calls change nothing. + */ + @Test + void aCodeGrantTokenWithoutTheAdminScopeCannotCallTheUsersOwnOperations() throws Exception { + Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE)); + String withoutAdmin = accessToken(pool, "openid email"); + String withAdmin = accessToken(pool, "openid email " + ADMIN_SCOPE); + Map requests = new LinkedHashMap<>(); + requests.put("GetUser", "{\"AccessToken\":\"%s\"}"); + requests.put("GetUserAuthFactors", "{\"AccessToken\":\"%s\"}"); + requests.put("UpdateUserAttributes", + "{\"AccessToken\":\"%s\",\"UserAttributes\":[{\"Name\":\"given_name\",\"Value\":\"Changed\"}]}"); + requests.put("DeleteUserAttributes", "{\"AccessToken\":\"%s\",\"UserAttributeNames\":[\"email\"]}"); + requests.put("ChangePassword", + "{\"AccessToken\":\"%s\",\"PreviousPassword\":\"" + PASSWORD + "\",\"ProposedPassword\":\"Other1234!\"}"); + requests.put("GetUserAttributeVerificationCode", "{\"AccessToken\":\"%s\",\"AttributeName\":\"email\"}"); + requests.put("VerifyUserAttribute", "{\"AccessToken\":\"%s\",\"AttributeName\":\"email\",\"Code\":\"123456\"}"); + requests.put("SetUserMFAPreference", "{\"AccessToken\":\"%s\",\"EmailMfaSettings\":{\"Enabled\":true}}"); + requests.put("AssociateSoftwareToken", "{\"AccessToken\":\"%s\"}"); + requests.put("VerifySoftwareToken", "{\"AccessToken\":\"%s\",\"UserCode\":\"123456\"}"); + requests.put("GlobalSignOut", "{\"AccessToken\":\"%s\"}"); + + for (Map.Entry request : requests.entrySet()) { + cognitoAction(request.getKey(), request.getValue().formatted(withoutAdmin)) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Access Token does not have required scopes")); + } + + JsonNode user = cognitoJson("GetUser", "{\"AccessToken\":\"%s\"}".formatted(withAdmin)); + assertEquals(pool.username(), user.path("Username").asText(), "the user was not signed out"); + assertTrue(user.path("UserAttributes").toString().contains("\"email\""), user.toString()); + assertFalse(user.path("UserAttributes").toString().contains("given_name"), user.toString()); + code(signIn(null, pool, authorizeRequest(pool.clientId()))); + } + + /** + * A V2 trigger's {@code scopesToAdd} and {@code scopesToSuppress} apply on top of the scopes the + * request was granted, so a trigger can still give a token the scope that API calls need. + */ + @Test + void preTokenGenerationV2ScopeChangesApplyOnTopOfTheGrantedScopes() throws Exception { + Pool pool = newPoolWithPreTokenGenerationTrigger(); + when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), any(byte[].class), any())) + .thenReturn(triggerResponse(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "scopesToSuppress", List.of("email"), + "scopesToAdd", List.of(ADMIN_SCOPE)))))); + + Response tokens = redeem(null, pool.clientId(), + code(signIn(null, pool, authorizeRequest(pool.clientId()))), VERIFIER); + + tokens.then().statusCode(200); + String accessToken = tokens.path("access_token"); + assertEquals(Set.of("openid", ADMIN_SCOPE), scopes(accessToken)); + cognitoAction("GetUser", "{\"AccessToken\":\"%s\"}".formatted(accessToken)).then().statusCode(200); + } + + /** A trigger that suppresses every scope the request was granted leaves no scope claim, which grants nothing. */ @Test void codeGrantAccessTokenWithEveryScopeSuppressedCannotReadAuthFactors() throws Exception { String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of( - "scopesToSuppress", List.of("aws.cognito.signin.user.admin"))); + "scopesToSuppress", List.of("openid", "email"))); assertFalse(jwtPayload(accessToken).has("scope")); cognitoAction("GetUserAuthFactors", """ @@ -295,7 +444,7 @@ class CognitoManagedLoginIntegrationTest { @Test void codeGrantAccessTokenWithEveryScopeSuppressedCannotVerifyAnAttribute() throws Exception { String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of( - "scopesToSuppress", List.of("aws.cognito.signin.user.admin"))); + "scopesToSuppress", List.of("openid", "email"))); assertFalse(jwtPayload(accessToken).has("scope")); cognitoAction("VerifyUserAttribute", """ @@ -308,15 +457,8 @@ class CognitoManagedLoginIntegrationTest { @Test void codeGrantAccessTokenWithTheAdminScopeReadsAuthFactors() throws Exception { - String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginAdminScopePool\"}") - .path("UserPool").path("Id").asText(); - Pool pool = withUser(poolId, - codeClient(poolId, "\"openid\",\"email\",\"aws.cognito.signin.user.admin\""), - "user-" + System.nanoTime()); - Map query = authorizeRequest(pool.clientId()); - query.put("scope", "openid email aws.cognito.signin.user.admin"); - String accessToken = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER) - .path("access_token"); + Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE)); + String accessToken = accessToken(pool, "openid email " + ADMIN_SCOPE); cognitoAction("GetUserAuthFactors", """ {"AccessToken":"%s"} @@ -471,7 +613,7 @@ class CognitoManagedLoginIntegrationTest { """.formatted(poolId)); String clientId = cognitoJson("CreateUserPoolClient", """ {"UserPoolId":"%s","ClientName":"federated-only","AllowedOAuthFlowsUserPoolClient":true, - "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid"],"CallbackURLs":["%s"], + "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"], "SupportedIdentityProviders":["ExampleOidc"]} """.formatted(poolId, CALLBACK)).path("UserPoolClient").path("ClientId").asText(); Map query = authorizeRequest(clientId); @@ -562,6 +704,26 @@ class CognitoManagedLoginIntegrationTest { .then().statusCode(400).body("error", equalTo("invalid_client")); } + @Test + void customDomainScopesTheCodeGrantTheSameWay() throws Exception { + Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE)); + String domain = "managed-login-scope-" + System.nanoTime() + ".teos.localhost.floci.io"; + cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain))); + + Response tokens = redeem(domain, pool.clientId(), + code(signIn(domain, pool, withField(authorizeRequest(pool.clientId()), "scope", "email"))), VERIFIER); + + tokens.then().statusCode(200); + assertEquals(Set.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(tokens)); + assertEquals(Set.of("email"), scopes(tokens.path("access_token"))); + String refused = browserGet(domain, "/oauth2/authorize", + withField(authorizeRequest(pool.clientId()), "scope", "openid phone"), null) + .then().statusCode(302).extract().header("Location"); + assertTrue(refused.startsWith(CALLBACK + "?"), refused); + assertEquals(Map.of("error", "invalid_request", "error_description", "invalid_scope", "state", "client-state"), + queryOf(refused)); + } + /** Without a custom domain Host, /login stays S3's path-style bucket route. */ @Test void loginOnFlocisOwnHostIsNotManagedLogin() { @@ -585,8 +747,12 @@ class CognitoManagedLoginIntegrationTest { } private static Pool newPool() throws Exception { + return newPool(List.of("openid", "email")); + } + + private static Pool newPool(List allowedScopes) throws Exception { String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginPool\"}").path("UserPool").path("Id").asText(); - return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime()); + return withUser(poolId, codeClient(poolId, allowedScopes), "user-" + System.nanoTime()); } private static Pool newPoolWithPreTokenGenerationTrigger() throws Exception { @@ -615,16 +781,26 @@ class CognitoManagedLoginIntegrationTest { } private static String codeClient(String poolId) throws Exception { - return codeClient(poolId, "\"openid\",\"email\""); + return codeClient(poolId, List.of("openid", "email")); } - /** {@code allowedScopes} is the body of the AllowedOAuthScopes JSON array. */ - private static String codeClient(String poolId, String allowedScopes) throws Exception { + private static String codeClient(String poolId, List allowedScopes) throws Exception { return cognitoJson("CreateUserPoolClient", """ {"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true, - "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":[%s],"CallbackURLs":["%s"], + "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":%s,"CallbackURLs":["%s"], "LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]} - """.formatted(poolId, allowedScopes, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText(); + """.formatted(poolId, MAPPER.writeValueAsString(allowedScopes), CALLBACK, SIGNED_OUT)) + .path("UserPoolClient").path("ClientId").asText(); + } + + /** Replaces the client's AllowedOAuthScopes, sending the rest of its OAuth configuration unchanged. */ + private static void allowScopes(Pool pool, List allowedScopes) throws Exception { + cognitoJson("UpdateUserPoolClient", """ + {"UserPoolId":"%s","ClientId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true, + "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":%s,"CallbackURLs":["%s"], + "LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]} + """.formatted(pool.poolId(), pool.clientId(), MAPPER.writeValueAsString(allowedScopes), CALLBACK, + SIGNED_OUT)); } private static Pool withUser(String poolId, String clientId, String username) throws Exception { @@ -723,6 +899,13 @@ class CognitoManagedLoginIntegrationTest { return request.when().post(host == null ? "/cognito-idp/oauth2/token" : "/oauth2/token"); } + /** An access token for the pool's user from a fresh sign-in that requested {@code scope}. */ + private static String accessToken(Pool pool, String scope) { + Map query = withField(authorizeRequest(pool.clientId()), "scope", scope); + return redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER) + .then().statusCode(200).extract().path("access_token"); + } + private static String code(Response callbackRedirect) { callbackRedirect.then().statusCode(302); String code = queryOf(callbackRedirect.getHeader("Location")).get("code"); @@ -732,6 +915,17 @@ class CognitoManagedLoginIntegrationTest { // ──────────────────────────── Parsing ──────────────────────────── + /** The access token's scopes, as a set: AWS does not promise their order. */ + private static Set scopes(String accessToken) throws Exception { + return Set.of(jwtPayload(accessToken).path("scope").asText().split(" ")); + } + + private static Set fieldNames(Response tokens) throws Exception { + Set names = new HashSet<>(); + MAPPER.readTree(tokens.asString()).fieldNames().forEachRemaining(names::add); + return names; + } + /** The Set-Cookie header that sets {@code name}, or null. */ private static String setCookie(Response response, String name) { for (String header : response.getHeaders().getValues("Set-Cookie")) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java index ed38e4923b..e54ece597c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCod import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; import io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.IdentityProvider; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; import jakarta.ws.rs.container.ContainerRequestContext; @@ -18,10 +19,13 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentCaptor; +import java.net.URI; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; @@ -65,8 +69,8 @@ class CognitoOAuthControllerTest { @Test void authorizeRedirectsToConfiguredIdentityProvider() { - when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), "nonce", "ExampleOidc", - " relying-party-state ", RFC_7636_CHALLENGE)) + when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), List.of("openid"), + "nonce", "ExampleOidc", " relying-party-state ", RFC_7636_CHALLENGE)) .thenReturn("https://provider.example.test/authorize?state=provider-state"); Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce", @@ -156,6 +160,77 @@ class CognitoOAuthControllerTest { } } + /** AWS redirects an unallowed scope to the callback, in this parameter order, before any provider is involved. */ + @Test + void authorizeRedirectsAScopeTheClientIsNotAllowedToTheCallbackForEitherProvider() { + for (String provider : new String[] {null, "COGNITO", "ExampleOidc"}) { + Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid phone", + null, provider, "s1", null, null, null); + + assertEquals(302, response.getStatus()); + assertEquals(CALLBACK_URI + "?error_description=invalid_scope&state=s1&error=invalid_request", + response.getHeaderString("Location")); + } + Response withoutState = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", + "aws.cognito.signin.user.admin", null, null, null, null, null, null); + assertEquals(CALLBACK_URI + "?error_description=invalid_scope&error=invalid_request", + withoutState.getHeaderString("Location")); + verify(federationService, never()).beginAuthorization(any(), any(), any(), any(), any(), any(), any(), any(), + any()); + } + + /** + * Federation asks the provider for what the request named, its {@code authorize_scopes} aside, as + * before; the grant governs only Cognito's own code. A request without a scope therefore asks the + * provider for none, while its code is granted every scope the client allows. + */ + @Test + void authorizeWithoutAScopeAsksTheProviderForNoneWhileTheCodeGetsEveryAllowedScope() throws Exception { + IdentityProvider provider = new IdentityProvider(); + provider.setUserPoolId(POOL_ID); + provider.setProviderName("ExampleOidc"); + provider.setProviderType("OIDC"); + provider.setProviderDetails(Map.of("authorize_url", "https://provider.example.test/authorize", + "client_id", "provider-client")); + when(cognitoService.describeIdentityProvider(POOL_ID, "ExampleOidc")).thenReturn(provider); + when(cognitoService.getIdentityProviderCallbackEndpoint(POOL_ID)) + .thenReturn("http://localhost:4566/cognito-idp/oauth2/idpresponse"); + when(cognitoService.provisionFederatedUser(eq(POOL_ID), eq(provider), eq("provider-subject"), any(), any())) + .thenReturn(user()); + CognitoOidcClient oidcClient = mock(CognitoOidcClient.class); + when(oidcClient.exchangeCode(eq(provider), eq("provider-code"), any())) + .thenReturn(objectMapper.readTree("{\"access_token\":\"provider-access-token\"}")); + when(oidcClient.fetchClaims(provider, "provider-access-token")) + .thenReturn(objectMapper.readTree("{\"sub\":\"provider-subject\"}")); + CognitoOAuthController federating = new CognitoOAuthController(cognitoService, objectMapper, + new CognitoFederationService(cognitoService, stateStore, oidcClient, CLOCK), stateStore, + new CognitoManagedLoginService(cognitoService, stateStore, CLOCK)); + + String toProvider = federating.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null, + "ExampleOidc", "s1", null, null, null).getHeaderString("Location"); + String toCallback = federating.idpResponse(requestContext(null), queryParameter(toProvider, "state"), + "provider-code", null, null).getHeaderString("Location"); + + assertTrue(toProvider.startsWith("https://provider.example.test/authorize?"), toProvider); + assertEquals("", queryParameter(toProvider, "scope")); + assertEquals(List.of("openid", "email"), storedCode(toCallback).scopes()); + } + + @Test + void authorizeWithASessionBindsTheCodeToTheScopesGrantedThen() { + when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user")); + String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user", + CLOCK.instant().plusSeconds(60))); + + String withoutScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null, + null, null, null, null, sessionId).getHeaderString("Location"); + String withScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "email email", + null, null, null, null, null, sessionId).getHeaderString("Location"); + + assertEquals(List.of("openid", "email"), storedCode(withoutScope).scopes()); + assertEquals(List.of("email"), storedCode(withScope).scopes()); + } + @Test void authorizeWithASessionOfThePoolRedirectsWithACodeCarryingTheNonceAndChallenge() { when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user")); @@ -259,6 +334,21 @@ class CognitoOAuthControllerTest { assertOAuthError(replay, "invalid_grant"); } + /** AWS leaves {@code id_token} out of the response, rather than sending it as null, without openid. */ + @Test + void tokenLeavesTheIdTokenOutWhenNoneWasMinted() { + String code = putAuthorizationCode(); + when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any())) + .thenReturn(Map.of("AccessToken", "access-token", "RefreshToken", "refresh-token", + "ExpiresIn", 3600, "TokenType", "Bearer")); + + Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code)); + + assertEquals(200, response.getStatus()); + JsonNode body = (JsonNode) response.getEntity(); + assertEquals(List.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(body)); + } + @Test void tokenRejectsAuthorizationCodeForAnotherClient() { String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode( @@ -421,7 +511,7 @@ class CognitoOAuthControllerTest { assertEquals(200, response.getStatus()); verify(cognitoService).generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), any(), scopes.capture()); - assertEquals(List.of("openid"), scopes.getValue(), "the code's requested scopes reach the trigger"); + assertEquals(List.of("openid"), scopes.getValue(), "the code's granted scopes reach the trigger"); verify(cognitoService, never()).generateAuthResult(any(CognitoUser.class), any(UserPool.class), any(), any()); } @@ -466,6 +556,7 @@ class CognitoOAuthControllerTest { result.setUserPoolId(POOL_ID); result.setAllowedOAuthFlowsUserPoolClient(true); result.setAllowedOAuthFlows(List.of("code")); + result.setAllowedOAuthScopes(List.of("openid", "email")); result.setCallbackURLs(List.of(CALLBACK_URI)); result.setSupportedIdentityProviders(List.of("COGNITO")); return result; @@ -507,6 +598,29 @@ class CognitoOAuthControllerTest { return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); } + /** The code a redirect to the callback carries, as the state store holds it. */ + private CognitoAuthorizationCode storedCode(String location) { + assertTrue(location.startsWith(CALLBACK_URI + "?code="), location); + return stateStore.findAuthorizationCode(queryParameter(location, "code")).orElseThrow(); + } + + /** A query parameter of {@code location}, decoded, or null when it has none of that name. */ + private static String queryParameter(String location, String name) { + for (String pair : URI.create(location).getRawQuery().split("&")) { + String[] parts = pair.split("=", 2); + if (parts[0].equals(name)) { + return parts.length == 2 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : ""; + } + } + return null; + } + + private static List fieldNames(JsonNode body) { + List names = new ArrayList<>(); + body.fieldNames().forEachRemaining(names::add); + return names; + } + private void assertOAuthError(Response response, String error) { assertEquals(400, response.getStatus()); assertNotNull(response.getEntity());