Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): accept the refresh_token grant on the OAuth token endpoint (#4948)
Mario Toffia2d7ebcb51c4c
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex c0f534ae5c..8767ed35f9 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -502,7 +502,7 @@ plain, so branding is stored and returned rather than rendered. Two divergences| `GET /cognito-idp/oauth2/idpresponse` | OIDC provider callback endpoint || `GET`, `POST /cognito-idp/login` | Managed login sign-in form || `GET /cognito-idp/logout` | Managed login sign-out |-| `POST /cognito-idp/oauth2/token` | OAuth authorization-code and client-credentials token endpoint |+| `POST /cognito-idp/oauth2/token` | OAuth code, refresh-token and client-credentials token endpoint || `POST /cognito-idp/oauth2/revoke` | OAuth refresh token revocation endpoint || `GET`, `POST /cognito-idp/oauth2/userInfo` | OIDC userInfo endpoint, for a user's access token |@@ -518,6 +518,38 @@ client-credentials flow:- `POST /cognito-idp/oauth2/token` redeems that authorization code once, checking its PKCE`code_verifier` when the authorization request sent a `code_challenge`, or issues a machinetoken for `grant_type=client_credentials`.+- `POST /cognito-idp/oauth2/token` with `grant_type=refresh_token` and a `refresh_token` renews a+ session as `GetTokensFromRefreshToken` does, firing the pre token generation trigger with+ `TokenGeneration_RefreshTokens`. It accepts a refresh token from managed login or from a+ sign-in through the API, and, as on AWS, it requires neither `ALLOW_REFRESH_TOKEN_AUTH`, which+ `InitiateAuth` `REFRESH_TOKEN_AUTH` requires, nor any OAuth setting on the client. A public+ client sends `client_id`, and a `client_secret` it sends+ in the body is ignored. A client with a secret sends `client_secret` in the body or Basic+ credentials; a Basic header names the client whatever the body's `client_id` says. The access+ token keeps the original grant's `scope` (for a sign-in through the API,+ `aws.cognito.signin.user.admin`), its `origin_jti` and its `auth_time`, with a new `jti` and+ `iat`, as it does from `InitiateAuth` `REFRESH_TOKEN_AUTH` and `GetTokensFromRefreshToken`. A+ `scope` parameter is ignored. The answer has `access_token`,+ `expires_in`, `token_type`, and an `id_token` exactly when the original sign-in issued one. It+ has no `refresh_token`: refresh token rotation is not implemented, whatever the client's+ `RefreshTokenRotation` says. Errors are 400 without a `WWW-Authenticate` header, as on AWS:+ - `{"error":"invalid_request"}` for a request without `grant_type`, as for every grant.+ - `{"error":"invalid_client"}` for a missing or unknown client, a malformed Basic header, Basic+ credentials of a public client with an empty secret, or, on a custom domain, a client of+ another pool. The client is checked before the refresh token.+ - `{"error":"invalid_client","error_description":"invalid_client_secret"}` for a client with a+ secret that sends none, or a wrong one, and for Basic credentials of a public client with a+ secret.+ - `{"error":"invalid_request","error_description":"invalid_refresh_token"}` for an empty or+ absent `refresh_token`.+ - `{"error":"invalid_grant"}` for a refresh token that is not valid, expired, revoked, or issued+ to another client or pool, and for a grant holding a scope the client no longer allows: AWS+ refuses the refresh rather than narrowing the grant.++ `GetTokensFromRefreshToken` and `InitiateAuth` `REFRESH_TOKEN_AUTH` refuse another client's+ refresh token with `NotAuthorizedException` `Refresh Token has different Client`, and a grant+ holding a scope the client no longer allows with `NotAuthorizedException`+ `Client is not allowed to request these scopes`.- `POST /cognito-idp/oauth2/revoke` revokes a refresh token (`token`), and with it every accessand ID token minted from it, as `RevokeToken` does. A public client sends `client_id`; a clientwith a secret sends it in a Basic `Authorization` header. Unlike the token endpoint, it ignores a@@ -662,7 +694,7 @@ curl -s -b jar -o /dev/null -w '%{http_code} %{redirect_url}\n' \- It doesn't require a Cognito domain.- Client-credentials returns only `access_token`, `token_type`, and `expires_in`; authorization-coderedemption returns the Cognito access and refresh tokens, and an ID token when the granted scopes- include `openid`.+ include `openid`; a refresh returns the same tokens without a refresh token.- 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://<domain>/oauth2/token` when the pool has a custom domain (see Custom domains above).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.javaindex 530df037d1..ff8e4d84c9 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@@ -657,6 +657,9 @@ final class CognitoAuthFlowHandler {if (!pool.getId().equals(parts[0])) {throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);}+ CognitoService.requireRefreshTokenOfClient(client, parts);+ List<String> scopes = CognitoService.refreshTokenScopes(parts);+ CognitoService.requireScopesStillAllowed(client, scopes);String username = parts[1];long iat;try {@@ -685,14 +688,10 @@ final class CognitoAuthFlowHandler {throw ae;}CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,- 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));- auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));- auth.put("TokenType", "Bearer");+ clientMetadata, "TokenGeneration_RefreshTokens", scopes);Map<String, Object> result = new HashMap<>();- result.put("AuthenticationResult", auth);+ result.put("AuthenticationResult", service.accessAndIdTokens(user, pool, client, override, refreshTokenUuid,+ scopes, iat / 1000L));return result;}@@ -2068,8 +2067,10 @@ final class CognitoAuthFlowHandler {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", List.of());+ /** {@code scopes} are those of the grant being refreshed, or null for a sign-in through the API. */+ CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user,+ List<String> scopes) {+ return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens", scopes);}/**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.javaindex 1169a867c9..c59a108c5a 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@@ -511,7 +511,10 @@ public class CognitoOAuthController {String domainPoolId) {String grantType = trimToNull(formParams.getFirst("grant_type"));if (grantType == null) {- return oauthError("invalid_request", "grant_type is required");+ return oauthError("invalid_request");+ }+ if ("refresh_token".equals(grantType)) {+ return refreshTokens(authorization, formParams, domainPoolId);}BasicCredentials basicCredentials;try {@@ -543,7 +546,8 @@ public class CognitoOAuthController {return redeemAuthorizationCode(clientId, clientSecret, formParams, domainPoolId);}if (!"client_credentials".equals(grantType)) {- return oauthError("unsupported_grant_type", "Only client_credentials and authorization_code are supported");+ return oauthError("unsupported_grant_type",+ "Only client_credentials, authorization_code and refresh_token are supported");}String scope = trimToNull(formParams.getFirst("scope"));@@ -586,8 +590,7 @@ public class CognitoOAuthController {} catch (AwsException e) {return oauthError("invalid_client", "Client not found");}- if (client.getClientSecret() != null && !client.getClientSecret().isBlank()- && !secretsEqual(client.getClientSecret(), clientSecret)) {+ if (!clientSecretMatches(client, clientSecret)) {return oauthError("invalid_client", "Client secret is invalid");}@@ -617,23 +620,90 @@ public class CognitoOAuthController {CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId());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"));- // 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"));- return Response.ok(body).type(MediaType.APPLICATION_JSON)- .header("Cache-Control", "no-store").header("Pragma", "no-cache").build();+ return tokenResponse(authentication);} catch (AwsException e) {LOG.error("Failed to redeem Cognito authorization code", e);return oauthError("invalid_grant", e.getMessage());}}+ /**+ * Renews a session through the refresh shared with {@code GetTokensFromRefreshToken}, answering as+ * AWS does. The client is checked before the refresh token: a Basic header names it whatever the+ * body says, and authenticates it with the header's secret. A public client has none, so a secret+ * there is wrong and an empty one names no client; its body {@code client_secret} is ignored.+ * On a custom domain it must be a client of the domain's pool. Unlike the API's refresh, AWS does+ * not require {@code ALLOW_REFRESH_TOKEN_AUTH} or any OAuth setting here. A refreshed access token+ * keeps the scopes of the original grant, so no {@code scope} is read, and, as refresh token+ * rotation is not implemented, no new refresh token is issued.+ */+ private Response refreshTokens(String authorization, MultivaluedMap<String, String> formParams,+ String domainPoolId) {+ BasicCredentials basic;+ try {+ basic = parseBasicCredentials(authorization);+ } catch (IllegalArgumentException e) {+ return oauthError("invalid_client");+ }+ String clientId = basic != null ? basic.clientId() : trimToNull(formParams.getFirst("client_id"));+ String clientSecret = basic != null ? basic.clientSecret() : trimToNull(formParams.getFirst("client_secret"));+ UserPoolClient client = clientId == null ? null : clientOfDomain(clientId, domainPoolId);+ if (client == null || (basic != null && !hasSecret(client) && clientSecret == null)) {+ return oauthError("invalid_client");+ }+ if (!clientSecretMatches(client, clientSecret) || (basic != null && !hasSecret(client))) {+ return oauthError("invalid_client", "invalid_client_secret");+ }+ String refreshToken = trimToNull(formParams.getFirst("refresh_token"));+ if (refreshToken == null) {+ return oauthError("invalid_request", "invalid_refresh_token");+ }+ try {+ Map<String, Object> result = cognitoService.getTokensFromRefreshToken(clientId, refreshToken);+ return tokenResponse((Map<?, ?>) result.get("AuthenticationResult"));+ } catch (AwsException e) {+ LOG.debugv("Refused a refresh_token grant for client {0}: {1} {2}", clientId, e.getErrorCode(),+ e.getMessage());+ return oauthError("invalid_grant");+ }+ }++ /** The client, or null when it does not exist or, on a custom domain, belongs to another pool. */+ private UserPoolClient clientOfDomain(String clientId, String domainPoolId) {+ UserPoolClient client;+ try {+ client = cognitoService.findClientById(clientId);+ } catch (AwsException e) {+ return null;+ }+ return domainPoolId == null || domainPoolId.equals(client.getUserPoolId()) ? client : null;+ }++ private static boolean hasSecret(UserPoolClient client) {+ return client.getClientSecret() != null && !client.getClientSecret().isBlank();+ }++ /** A client with a secret must present it; a public client needs none. */+ private boolean clientSecretMatches(UserPoolClient client, String clientSecret) {+ return !hasSecret(client) || secretsEqual(client.getClientSecret(), clientSecret);+ }++ /** The token endpoint's answer for minted tokens, with an ID or refresh token only when one was minted. */+ private Response tokenResponse(Map<?, ?> authentication) {+ ObjectNode body = objectMapper.createObjectNode();+ body.put("access_token", (String) authentication.get("AccessToken"));+ if (authentication.get("IdToken") instanceof String idToken) {+ body.put("id_token", idToken);+ }+ if (authentication.get("RefreshToken") instanceof String refreshToken) {+ body.put("refresh_token", refreshToken);+ }+ body.put("expires_in", ((Number) authentication.get("ExpiresIn")).longValue());+ body.put("token_type", (String) authentication.get("TokenType"));+ return Response.ok(body).type(MediaType.APPLICATION_JSON)+ .header("Cache-Control", "no-store").header("Pragma", "no-cache").build();+ }+private Response redirect(String redirectUri, Map<String, String> parameters) {String location = redirectUri + (redirectUri.contains("?") ? '&' : '?') + formEncode(parameters);return Response.status(Response.Status.FOUND).location(URI.create(location)).build();@@ -990,6 +1060,11 @@ public class CognitoOAuthController {return scopes;}+ /** A 400 with no {@code error_description}, as AWS answers several token endpoint errors. */+ private Response oauthError(String error) {+ return oauthError(Response.Status.BAD_REQUEST, error, null);+ }+private Response oauthError(String error, String description) {return oauthError(Response.Status.BAD_REQUEST, error, description);}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.javaindex e9da88e9e3..b4aaf727c3 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@@ -113,6 +113,11 @@ public class CognitoService implements ResourceProvider {/** 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);+ /**+ * Starts the refresh token field that holds an OAuth grant's scopes. A family id, a UUID, never+ * starts with it, so a token whose username holds a pipe is never read as one with scopes.+ */+ private static final String REFRESH_TOKEN_SCOPE_FIELD = "scope=";private static final String IDENTITIES_ATTRIBUTE = "identities";@@ -4013,6 +4018,11 @@ public class CognitoService implements ResourceProvider {.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));}+ /**+ * Mints new access and ID tokens from a refresh token, as the sign-in that issued it did: an OAuth+ * grant's access token keeps the grant's scopes, and has an ID token only with {@code openid}.+ * Shared by {@code GetTokensFromRefreshToken} and the OAuth token endpoint's refresh_token grant.+ */public Map<String, Object> getTokensFromRefreshToken(String clientId, String refreshToken) {if (refreshToken == null) {throw new AwsException("InvalidParameterException", "RefreshToken is required", 400);@@ -4030,6 +4040,9 @@ public class CognitoService implements ResourceProvider {if (!client.getUserPoolId().equals(poolId)) {throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400);}+ requireRefreshTokenOfClient(client, parts);+ List<String> scopes = refreshTokenScopes(parts);+ requireScopesStillAllowed(client, scopes);if (isRefreshTokenExpired(client, parts)) {throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400);}@@ -4044,19 +4057,37 @@ public class CognitoService implements ResourceProvider {UserPool pool = describeUserPool(poolId);CognitoUser user = adminGetUser(poolId, username);- ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user);+ ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user, scopes);// Use refresh token UUID as origin_jti for derived tokens- Map<String, Object> auth = new HashMap<>();- auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));- auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));- auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));- auth.put("TokenType", "Bearer");Map<String, Object> result = new HashMap<>();- result.put("AuthenticationResult", auth);+ result.put("AuthenticationResult", accessAndIdTokens(user, pool, client, override, refreshTokenUuid,+ scopes, issuedAt / 1000L));return result;}+ /**+ * Refuses a refresh token issued to another client of the pool, as AWS does for+ * {@code GetTokensFromRefreshToken} and {@code InitiateAuth} {@code REFRESH_TOKEN_AUTH} alike.+ */+ static void requireRefreshTokenOfClient(UserPoolClient client, String[] refreshTokenParts) {+ if (!client.getClientId().equals(refreshTokenParts[2])) {+ throw new AwsException("NotAuthorizedException", "Refresh Token has different Client", 400);+ }+ }++ /**+ * Refuses to refresh an OAuth grant holding a scope the client no longer allows. AWS refuses+ * rather than narrows the grant, on both APIs and the token endpoint. {@code scopes} null, a+ * sign-in through the API, holds none.+ */+ static void requireScopesStillAllowed(UserPoolClient client, List<String> scopes) {+ List<String> allowed = client.getAllowedOAuthScopes() == null ? List.of() : client.getAllowedOAuthScopes();+ if (scopes != null && !allowed.containsAll(scopes)) {+ throw new AwsException("NotAuthorizedException", "Client is not allowed to request these scopes", 400);+ }+ }+public void revokeToken(String clientId, String token, String clientSecret) {if (token == null || token.isBlank()) {throw new AwsException("InvalidParameterException", "Token is required", 400);@@ -4137,7 +4168,7 @@ public class CognitoService implements ResourceProvider {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"));+ UUID.randomUUID().toString(), scopes);}/**@@ -4210,18 +4241,42 @@ 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);+ return generateAuthResult(user, pool, client, override, originJti, null);}+ /**+ * @param grantedScopes the scopes of the OAuth grant the tokens are minted for, or null for a+ * sign-in through the API. The refresh token keeps them, so that a refresh+ * mints the same kind of tokens.+ */private Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client,ClaimsOverride override, String originJti,- List<String> accessScopes, boolean withIdToken) {+ List<String> grantedScopes) {+ long issuedAt = System.currentTimeMillis();+ Map<String, Object> auth = accessAndIdTokens(user, pool, client, override, originJti, grantedScopes,+ issuedAt / 1000L);+ auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), issuedAt,+ originJti, grantedScopes));+ return auth;+ }++ /**+ * An OAuth grant's access token carries the grant's scopes, and it has an ID token only when they+ * include {@code openid}, as on AWS. A sign-in through the API, {@code grantedScopes} null, has the+ * {@code aws.cognito.signin.user.admin} scope and always an ID token. {@code authTime} is when the+ * user signed in, which a refresh keeps.+ */+ Map<String, Object> accessAndIdTokens(CognitoUser user, UserPool pool, UserPoolClient client,+ ClaimsOverride override, String originJti,+ List<String> grantedScopes, long authTime) {+ List<String> accessScopes = grantedScopes == null ? API_SIGN_IN_SCOPES : grantedScopes;Map<String, Object> auth = new HashMap<>();- 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("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti, accessScopes,+ authTime));+ if (grantedScopes == null || grantedScopes.contains("openid")) {+ auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti, accessScopes,+ authTime));}- auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), originJti));auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));auth.put("TokenType", "Bearer");return auth;@@ -4232,15 +4287,17 @@ 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);+ return generateSignedJwt(user, pool, type, client, override, originJti, API_SIGN_IN_SCOPES, null);}/*** @param accessScopes the access token's {@code scope} claim before any V2 trigger changes, left* out when empty; ignored for an ID token+ * @param authTime the {@code auth_time} claim, epoch seconds, or null for now*/private String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client,- ClaimsOverride override, String originJti, List<String> accessScopes) {+ ClaimsOverride override, String originJti, List<String> accessScopes,+ Long authTime) {String header = encodeJwtHeader(pool);long now = System.currentTimeMillis() / 1000L;long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type);@@ -4250,7 +4307,7 @@ public class CognitoService implements ResourceProvider {claims.put("sub", sub);claims.put("event_id", UUID.randomUUID().toString());claims.put("token_use", type);- claims.put("auth_time", now);+ claims.put("auth_time", authTime != null ? authTime : now);claims.put("iss", getIssuer(pool.getId()));claims.put("exp", now + lifetimeSeconds);claims.put("iat", now);@@ -4937,10 +4994,6 @@ public class CognitoService implements ResourceProvider {: Boolean.parseBoolean(String.valueOf(value));}- int getAccessTokenExpiresInSeconds(UserPoolClient client) {- return resolveAccessTokenLifetimeSeconds(client);- }-private int resolveAccessTokenLifetimeSeconds(UserPoolClient client) {return resolveTokenLifetimeSeconds(client, "access");}@@ -5014,13 +5067,21 @@ public class CognitoService implements ResourceProvider {}}- String buildRefreshToken(UserPool pool, String username, String clientId, String originJti) {+ /**+ * A signed {@code poolId|username|clientId|issuedAt|familyId} token. An OAuth grant's token adds a+ * field holding its scopes, base64url-encoded because a scope may contain the pipe that separates+ * the fields; a sign-in through the API, {@code grantedScopes} null, has none.+ */+ String buildRefreshToken(UserPool pool, String username, String clientId, long issuedAt, String originJti,+ List<String> grantedScopes) {if (ensureRefreshTokenSecret(pool)) {poolStore.put(pool.getId(), pool);}- long issuedAt = System.currentTimeMillis();String familyId = originJti != null ? originJti : UUID.randomUUID().toString();String raw = pool.getId() + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId;+ if (grantedScopes != null) {+ raw += "|" + REFRESH_TOKEN_SCOPE_FIELD + Base64Url.encode(String.join(" ", grantedScopes));+ }String signature = hmacSha256(refreshTokenSecretBytes(pool), raw);return Base64.getEncoder().withoutPadding().encodeToString((raw + "|" + signature).getBytes(StandardCharsets.UTF_8));@@ -5035,29 +5096,54 @@ public class CognitoService implements ResourceProvider {|| Boolean.TRUE.equals(client.getEnableTokenRevocation());}+ /**+ * The fields of a refresh token whose signature verifies: {@code [poolId, username, clientId,+ * issuedAt, familyId]}, and for an OAuth grant's token a sixth, its scopes separated by spaces.+ * Only the username can hold a pipe, so the fields after it are read from the end of the token.+ */String[] parseRefreshToken(String refreshToken) {try {byte[] decoded = Base64.getDecoder().decode(refreshToken);String raw = new String(decoded, StandardCharsets.UTF_8);- String[] parts = raw.split("\\|", 6);- if (parts.length != 6) {+ int signatureAt = raw.lastIndexOf('|');+ String payload = raw.substring(0, signatureAt);+ String[] parts = payload.split("\\|", -1);+ boolean hasScopes = parts[parts.length - 1].startsWith(REFRESH_TOKEN_SCOPE_FIELD);+ int trailing = hasScopes ? 4 : 3;+ if (parts.length < 2 + trailing) {return null;}UserPool pool = poolStore.get(parts[0]).orElse(null);if (pool == null || pool.getSigningSecret() == null || pool.getSigningSecret().isBlank()) {return null;}- String payload = String.join("|", Arrays.copyOf(parts, 5));byte[] expectedSignature = Base64.getDecoder().decode(hmacSha256(refreshTokenSecretBytes(pool), payload));- byte[] actualSignature = Base64.getDecoder().decode(parts[5]);+ byte[] actualSignature = Base64.getDecoder().decode(raw.substring(signatureAt + 1));if (!MessageDigest.isEqual(expectedSignature, actualSignature)) {return null;}- return Arrays.copyOf(parts, 5); // [poolId, username, clientId, issuedAt, nonce]+ int usernameEnd = parts.length - trailing;+ String[] fields = new String[hasScopes ? 6 : 5];+ fields[0] = parts[0];+ fields[1] = String.join("|", Arrays.copyOfRange(parts, 1, usernameEnd));+ System.arraycopy(parts, usernameEnd, fields, 2, 3);+ if (hasScopes) {+ fields[5] = new String(Base64.getUrlDecoder().decode(+ parts[parts.length - 1].substring(REFRESH_TOKEN_SCOPE_FIELD.length())), StandardCharsets.UTF_8);+ }+ return fields;} catch (Exception ignored) { }return null;}+ /** The scopes of the OAuth grant a parsed refresh token belongs to, or null for a sign-in through the API. */+ static List<String> refreshTokenScopes(String[] parts) {+ if (parts.length < 6) {+ return null;+ }+ return parts[5].isEmpty() ? List.of() : List.of(parts[5].split(" "));+ }+record VerifiedAccessToken(String username, String poolId, String subject, String clientId) {}/** Verified JWT details for services that enforce Cognito user-pool authorizers. */diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.javaindex 1cac69b95d..a2c931858a 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.java@@ -139,6 +139,18 @@ final class CognitoCustomDomainFixtures {""".formatted(user.clientId(), user.refreshToken()));}+ /** A public client's refresh_token grant at the token endpoint, on {@code host} when one is given. */+ static Response refreshGrant(String host, String clientId, String refreshToken) {+ RequestSpecification request = given()+ .formParam("grant_type", "refresh_token")+ .formParam("client_id", clientId)+ .formParam("refresh_token", refreshToken);+ if (host != null) {+ request.header("Host", host);+ }+ return request.when().post(host == null ? "/cognito-idp/oauth2/token" : "/oauth2/token");+ }+/** A client-credentials request with Basic authentication, on {@code host} when one is given. */static Response tokenRequest(String host, String clientId, String secret, String path) {RequestSpecification request = given()diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.javaindex b2916357a3..8049709288 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.cognito;import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.SignedInUser;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;@@ -28,6 +29,7 @@ import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFiximport static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.expect;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refresh;+import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refreshGrant;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.signIn;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.tokenRequest;@@ -36,6 +38,8 @@ import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.emptyString;import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.not;import static org.hamcrest.Matchers.nullValue;import static org.hamcrest.Matchers.startsWith;import static org.junit.jupiter.api.Assertions.assertEquals;@@ -50,6 +54,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;class CognitoCustomDomainOAuthContractIntegrationTest {private static final String DOMAIN = "auth-c-" + System.nanoTime() + ".teos.localhost.floci.io";+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();private static String poolA;private static String poolB;@@ -343,4 +348,62 @@ class CognitoCustomDomainOAuthContractIntegrationTest {pool.shutdownNow();}}++ @Test+ @Order(16)+ void refreshGrantIsServedOnTheCustomDomain() throws Exception {+ SignedInUser user = signIn(poolA);++ Response response = refreshGrant(DOMAIN, user.clientId(), user.refreshToken());++ response.then()+ .statusCode(200)+ .header("Cache-Control", equalTo("no-store"))+ .body("token_type", equalTo("Bearer"))+ .body("$", not(hasKey("refresh_token")));+ JsonNode claims = jwtPayload(response.path("access_token"));+ assertEquals(FLOCI_URL + "/" + poolA, claims.path("iss").asText());+ assertEquals(user.clientId(), claims.path("client_id").asText());+ }++ /** AWS: a client of another pool does not exist on a pool's custom domain. */+ @Test+ @Order(17)+ void refreshGrantRefusesAClientOfAnotherPool() throws Exception {+ SignedInUser user = signIn(poolB);++ assertBody(refreshGrant(DOMAIN, user.clientId(), user.refreshToken()), "{\"error\":\"invalid_client\"}");++ refreshGrant(null, user.clientId(), user.refreshToken()).then().statusCode(200);+ }++ /** AWS: the pool's own client cannot refresh another pool's refresh token on the pool's custom domain. */+ @Test+ @Order(18)+ void refreshGrantRefusesARefreshTokenOfAnotherPool() throws Exception {+ SignedInUser poolAUser = signIn(poolA);+ SignedInUser poolBUser = signIn(poolB);++ assertBody(refreshGrant(DOMAIN, poolAUser.clientId(), poolBUser.refreshToken()),+ "{\"error\":\"invalid_grant\"}");+ }++ /** AWS: a client of a pool, with its own refresh token, does not exist on another pool's custom domain. */+ @Test+ @Order(19)+ void refreshGrantOnAnotherPoolsDomainRefusesTheClient() throws Exception {+ String poolBDomain = "auth-c-b-" + System.nanoTime() + ".teos.localhost.floci.io";+ cognitoJson("CreateUserPoolDomain", customDomain(poolBDomain, poolB, requestCertificate(poolBDomain)));+ SignedInUser poolAUser = signIn(poolA);++ assertBody(refreshGrant(poolBDomain, poolAUser.clientId(), poolAUser.refreshToken()),+ "{\"error\":\"invalid_client\"}");+ }++ /** A 400 without a WWW-Authenticate challenge, whose JSON body is exactly {@code expectedBody}. */+ private static void assertBody(Response response, String expectedBody) throws Exception {+ response.then().statusCode(400).contentType(containsString("application/json"))+ .header("WWW-Authenticate", nullValue());+ assertEquals(OBJECT_MAPPER.readTree(expectedBody), OBJECT_MAPPER.readTree(response.asString()));+ }}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.javaindex 4af468aea9..5ab96eca95 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@@ -1395,6 +1395,32 @@ class CognitoLambdaTriggersTest {assertEquals(List.of(), scopes, "a client allowed no scopes grants the trigger none");}+ /** A refresh of a code grant's refresh token tells a V2 trigger the scopes its access token carries, on both APIs. */+ @Test+ @SuppressWarnings("unchecked")+ void preTokenGenerationForARefreshOfACodeGrantIsToldTheGrantedScopes() throws Exception {+ 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");+ ArgumentCaptor<byte[]> payloadCap = ArgumentCaptor.forClass(byte[].class);+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))+ .thenReturn(ok(Map.of()));+ String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null,+ List.of("openid", "email")).get("RefreshToken");++ service.getTokensFromRefreshToken(client.getClientId(), refreshToken);+ service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH", Map.of("REFRESH_TOKEN", refreshToken));++ List<byte[]> payloads = payloadCap.getAllValues();+ for (byte[] payload : payloads.subList(payloads.size() - 2, payloads.size())) {+ Map<String, Object> event = MAPPER.readValue(payload, new TypeReference<>() {});+ assertEquals("TokenGeneration_RefreshTokens", event.get("triggerSource"));+ assertEquals(List.of("openid", "email"), ((Map<String, Object>) event.get("request")).get("scopes"),+ "a V2 lambda may branch on the scopes of the grant being refreshed");+ }+ }+/*** The OIDC flow owns {@code nonce}, and AWS lists it among the claims this trigger cannot* override or suppress. A trigger that tries must not displace the request's value.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.javaindex e425b9e891..3fa82c33a0 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@@ -27,6 +27,7 @@ import java.util.regex.Pattern;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload;+import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refreshGrant;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate;import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;@@ -36,6 +37,7 @@ import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.startsWith;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;@@ -315,6 +317,133 @@ class CognitoManagedLoginIntegrationTest {}}+ /**+ * AWS: an app that signed in through managed login refreshes at the token endpoint. The new+ * access token keeps the code's scope claim exactly, its family and its auth_time; an ID token+ * comes exactly when the redemption issued one, which is with {@code openid}; and, without+ * refresh token rotation, no new refresh token is issued. InitiateAuth REFRESH_TOKEN_AUTH mints+ * the same kind of tokens.+ */+ @Test+ void refreshKeepsTheGrantedScopesAndIssuesAnIdTokenOnlyWithOpenid() throws Exception {+ Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));+ Map<String, Set<String>> expectedFields = new LinkedHashMap<>();+ expectedFields.put("openid email", Set.of("access_token", "id_token", "expires_in", "token_type"));+ expectedFields.put("email", Set.of("access_token", "expires_in", "token_type"));+ expectedFields.put(ADMIN_SCOPE, Set.of("access_token", "expires_in", "token_type"));++ for (Map.Entry<String, Set<String>> request : expectedFields.entrySet()) {+ Map<String, String> query = withField(authorizeRequest(pool.clientId()), "scope", request.getKey());+ Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER);+ tokens.then().statusCode(200);++ Response refreshed = refreshGrant(null, pool.clientId(), tokens.path("refresh_token"));++ refreshed.then().statusCode(200).body("token_type", equalTo("Bearer")).body("expires_in", equalTo(3600));+ assertEquals(request.getValue(), fieldNames(refreshed), "scope=" + request.getKey());+ JsonNode redeemedClaims = jwtPayload(tokens.path("access_token"));+ JsonNode refreshedClaims = jwtPayload(refreshed.path("access_token"));+ assertEquals(request.getKey(), refreshedClaims.path("scope").asText());+ assertEquals(redeemedClaims.path("scope").asText(), refreshedClaims.path("scope").asText());+ assertNotEquals(redeemedClaims.path("jti").asText(), refreshedClaims.path("jti").asText());+ assertEquals(redeemedClaims.path("origin_jti").asText(), refreshedClaims.path("origin_jti").asText());+ assertEquals(redeemedClaims.path("auth_time").asLong(), refreshedClaims.path("auth_time").asLong());++ JsonNode viaApi = cognitoJson("InitiateAuth", """+ {"ClientId":"%s","AuthFlow":"REFRESH_TOKEN_AUTH","AuthParameters":{"REFRESH_TOKEN":"%s"}}+ """.formatted(pool.clientId(), tokens.path("refresh_token"))).path("AuthenticationResult");+ assertEquals(request.getKey(), jwtPayload(viaApi.path("AccessToken").asText()).path("scope").asText());+ assertEquals(request.getValue().contains("id_token"), viaApi.has("IdToken"), "scope=" + request.getKey());+ }+ }++ /**+ * AWS refuses, rather than narrows, a refresh of a grant holding a scope the client no longer+ * allows: the token endpoint answers invalid_grant, and both APIs NotAuthorizedException.+ */+ @Test+ void refreshOfAGrantHoldingAScopeTheClientNoLongerAllowsIsRefused() throws Exception {+ Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));+ String refreshToken = redeem(null, pool.clientId(), code(signIn(null, pool,+ withField(authorizeRequest(pool.clientId()), "scope", "openid email"))), VERIFIER)+ .then().statusCode(200).extract().path("refresh_token");+ allowScopes(pool, List.of("openid", ADMIN_SCOPE));++ assertInvalidGrant(refreshGrant(null, pool.clientId(), refreshToken));+ for (Response refused : List.of(+ cognitoAction("GetTokensFromRefreshToken", """+ {"ClientId":"%s","RefreshToken":"%s"}+ """.formatted(pool.clientId(), refreshToken)),+ cognitoAction("InitiateAuth", """+ {"ClientId":"%s","AuthFlow":"REFRESH_TOKEN_AUTH","AuthParameters":{"REFRESH_TOKEN":"%s"}}+ """.formatted(pool.clientId(), refreshToken)))) {+ refused.then().statusCode(400)+ .body("__type", equalTo("NotAuthorizedException"))+ .body("message", equalTo("Client is not allowed to request these scopes"));+ }+ }++ /** AWS ignores a scope parameter on the refresh grant, so a refresh cannot change the granted scopes. */+ @Test+ void refreshIgnoresAScopeParameter() throws Exception {+ Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));+ String refreshToken = redeem(null, pool.clientId(),+ code(signIn(null, pool, withField(authorizeRequest(pool.clientId()), "scope", "email"))), VERIFIER)+ .then().statusCode(200).extract().path("refresh_token");++ Response refreshed = given()+ .formParam("grant_type", "refresh_token")+ .formParam("client_id", pool.clientId())+ .formParam("refresh_token", refreshToken)+ .formParam("scope", "openid email " + ADMIN_SCOPE)+ .when().post("/cognito-idp/oauth2/token");++ refreshed.then().statusCode(200);+ assertEquals(Set.of("access_token", "expires_in", "token_type"), fieldNames(refreshed));+ assertEquals("email", jwtPayload(refreshed.path("access_token")).path("scope").asText());+ }++ @Test+ void refreshAfterTheRevocationEndpointOrRevokeTokenIsInvalidGrant() throws Exception {+ Pool pool = newPool();+ String revokedAtTheEndpoint = refreshToken(pool);+ String revokedThroughTheApi = refreshToken(pool);++ given().formParam("token", revokedAtTheEndpoint).formParam("client_id", pool.clientId())+ .when().post("/cognito-idp/oauth2/revoke").then().statusCode(200);+ cognitoAction("RevokeToken", """+ {"Token":"%s","ClientId":"%s"}+ """.formatted(revokedThroughTheApi, pool.clientId())).then().statusCode(200);++ for (String refreshToken : List.of(revokedAtTheEndpoint, revokedThroughTheApi)) {+ assertInvalidGrant(refreshGrant(null, pool.clientId(), refreshToken));+ }+ }++ @Test+ void refreshWithATokenIssuedToAnotherClientIsInvalidGrant() throws Exception {+ Pool pool = newPool();+ String anotherClient = codeClient(pool.poolId());++ assertInvalidGrant(refreshGrant(null, anotherClient, refreshToken(pool)));+ }++ @Test+ void refreshOnTheCustomDomainKeepsTheGrantedScopes() throws Exception {+ Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));+ String domain = "managed-login-refresh-" + System.nanoTime() + ".teos.localhost.floci.io";+ cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain)));+ String refreshToken = redeem(domain, pool.clientId(),+ code(signIn(domain, pool, withField(authorizeRequest(pool.clientId()), "scope", "email"))), VERIFIER)+ .then().statusCode(200).extract().path("refresh_token");++ Response refreshed = refreshGrant(domain, pool.clientId(), refreshToken);++ refreshed.then().statusCode(200);+ assertEquals(Set.of("access_token", "expires_in", "token_type"), fieldNames(refreshed));+ assertEquals(Set.of("email"), scopes(refreshed.path("access_token")));+ }+/*** 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@@ -1353,6 +1482,12 @@ class CognitoManagedLoginIntegrationTest {.then().statusCode(200).extract().path("access_token");}+ /** The refresh token of a fresh sign-in of the pool's user. */+ private static String refreshToken(Pool pool) {+ return redeem(null, pool.clientId(), code(signIn(null, pool, authorizeRequest(pool.clientId()))), VERIFIER)+ .then().statusCode(200).extract().path("refresh_token");+ }+private static String code(Response callbackRedirect) {callbackRedirect.then().statusCode(302);String code = queryOf(callbackRedirect.getHeader("Location")).get("code");@@ -1362,6 +1497,12 @@ class CognitoManagedLoginIntegrationTest {// ──────────────────────────── Parsing ────────────────────────────+ /** AWS's answer to a refresh token it refuses: 400 and exactly {@code {"error":"invalid_grant"}}. */+ private static void assertInvalidGrant(Response response) throws Exception {+ response.then().statusCode(400);+ assertEquals(MAPPER.readTree("{\"error\":\"invalid_grant\"}"), MAPPER.readTree(response.asString()));+ }+/** The access token's scopes, as a set: AWS does not promise their order. */private static Set<String> scopes(String accessToken) throws Exception {return Set.of(jwtPayload(accessToken).path("scope").asText().split(" "));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.javaindex da2f62e79e..e059c7d046 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@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.cognito.model.UserPool;import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;import jakarta.ws.rs.container.ContainerRequestContext;import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.Response;import org.junit.jupiter.api.BeforeEach;@@ -31,6 +32,7 @@ import java.time.Instant;import java.time.ZoneOffset;import java.util.ArrayList;import java.util.Base64;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.stream.Stream;@@ -536,6 +538,186 @@ class CognitoOAuthControllerTest {verify(cognitoService, never()).generateAuthResult(any(CognitoUser.class), any(UserPool.class), any(), any());}+ /** AWS: a public client names itself; without refresh token rotation, no new refresh token is issued. */+ @Test+ void tokenRefreshesThroughTheSharedRefreshForAPublicClient() {+ refreshesTo(Map.of("AccessToken", "access-token", "IdToken", "id-token", "ExpiresIn", 3600,+ "TokenType", "Bearer"));++ Response response = controller.token(null, requestContext(null), refreshForm());++ assertEquals(200, response.getStatus());+ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());+ assertEquals("no-store", response.getHeaderString("Cache-Control"));+ JsonNode body = (JsonNode) response.getEntity();+ assertEquals(List.of("access_token", "id_token", "expires_in", "token_type"), fieldNames(body));+ assertEquals("access-token", body.path("access_token").asText());+ assertEquals("id-token", body.path("id_token").asText());+ assertEquals(3600, body.path("expires_in").asInt());+ assertEquals("Bearer", body.path("token_type").asText());+ }++ @Test+ void tokenRefreshLeavesTheIdTokenOutWhenNoneWasMinted() {+ refreshesTo(Map.of("AccessToken", "access-token", "ExpiresIn", 3600, "TokenType", "Bearer"));++ Response response = controller.token(null, requestContext(null), refreshForm());++ assertEquals(200, response.getStatus());+ assertEquals(List.of("access_token", "expires_in", "token_type"), fieldNames((JsonNode) response.getEntity()));+ }++ /** AWS: Basic credentials authenticate a confidential client, with or without a client_id in the body. */+ @Test+ void tokenRefreshAuthenticatesAConfidentialClientWithBasicCredentials() {+ client.setClientSecret("client-secret");+ refreshesTo(Map.of("AccessToken", "access-token", "ExpiresIn", 3600, "TokenType", "Bearer"));++ Response withoutClientId = controller.token(basicAuthorization(CLIENT_ID, "client-secret"),+ requestContext(null), form("grant_type", "refresh_token", "refresh_token", "refresh-token"));+ Response withClientId = controller.token(basicAuthorization(CLIENT_ID, "client-secret"),+ requestContext(null), refreshForm());++ assertEquals(200, withoutClientId.getStatus());+ assertEquals(200, withClientId.getStatus());+ }++ @Test+ void tokenRefreshAuthenticatesAConfidentialClientWithTheSecretInTheBody() {+ client.setClientSecret("client-secret");+ refreshesTo(Map.of("AccessToken", "access-token", "ExpiresIn", 3600, "TokenType", "Bearer"));++ Response response = controller.token(null, requestContext(null), form("grant_type", "refresh_token",+ "client_id", CLIENT_ID, "client_secret", "client-secret", "refresh_token", "refresh-token"));++ assertEquals(200, response.getStatus());+ }++ /** AWS refreshes for the client of the Basic header when the body names another. */+ @Test+ void tokenRefreshTakesTheClientOfTheBasicHeaderOverTheBody() {+ UserPoolClient confidential = client("confidential-client");+ confidential.setClientSecret("client-secret");+ when(cognitoService.findClientById("confidential-client")).thenReturn(confidential);+ when(cognitoService.getTokensFromRefreshToken("confidential-client", "refresh-token"))+ .thenReturn(Map.of("AuthenticationResult",+ Map.of("AccessToken", "access-token", "ExpiresIn", 3600, "TokenType", "Bearer")));++ Response response = controller.token(basicAuthorization("confidential-client", "client-secret"),+ requestContext(null), refreshForm());++ assertEquals(200, response.getStatus());+ verify(cognitoService, never()).getTokensFromRefreshToken(eq(CLIENT_ID), any());+ }++ /** AWS: a missing secret, or a wrong one in the body or the Basic header, is the same 400. */+ @Test+ void tokenRefreshRefusesAConfidentialClientWithoutItsSecret() throws Exception {+ client.setClientSecret("client-secret");+ Map<String, Response> responses = new LinkedHashMap<>();+ responses.put("no secret", controller.token(null, requestContext(null), refreshForm()));+ responses.put("wrong secret in the body", controller.token(null, requestContext(null),+ form("grant_type", "refresh_token", "client_id", CLIENT_ID, "client_secret", "wrong-secret",+ "refresh_token", "refresh-token")));+ responses.put("wrong secret in Basic", controller.token(basicAuthorization(CLIENT_ID, "wrong-secret"),+ requestContext(null), form("grant_type", "refresh_token", "refresh_token", "refresh-token")));++ for (Map.Entry<String, Response> response : responses.entrySet()) {+ assertOAuthBody(response.getKey(), response.getValue(),+ "{\"error\":\"invalid_client\",\"error_description\":\"invalid_client_secret\"}");+ }+ verify(cognitoService, never()).getTokensFromRefreshToken(any(), any());+ }++ /**+ * AWS answers 400 invalid_client, without a description, for a client it cannot identify, and+ * checks the client before the refresh token. A public client has no secret to send in Basic.+ */+ @Test+ void tokenRefreshRefusesAClientItCannotIdentifyBeforeLookingAtTheToken() throws Exception {+ when(cognitoService.findClientById("missing-client"))+ .thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400));+ Map<String, Response> responses = new LinkedHashMap<>();+ responses.put("unknown client", controller.token(null, requestContext(null),+ form("grant_type", "refresh_token", "client_id", "missing-client", "refresh_token", "not-a-token")));+ responses.put("no client", controller.token(null, requestContext(null),+ form("grant_type", "refresh_token", "refresh_token", "refresh-token")));+ responses.put("public client in Basic", controller.token(basicAuthorization(CLIENT_ID, ""),+ requestContext(null), form("grant_type", "refresh_token", "refresh_token", "refresh-token")));+ responses.put("malformed Basic", controller.token("Basic not-base64!", requestContext(null),+ refreshForm()));+ responses.put("client of another pool on a custom domain", controller.token(null,+ requestContext("other-pool"), refreshForm()));++ for (Map.Entry<String, Response> response : responses.entrySet()) {+ assertOAuthBody(response.getKey(), response.getValue(), "{\"error\":\"invalid_client\"}");+ }+ verify(cognitoService, never()).getTokensFromRefreshToken(any(), any());+ }++ /** AWS: an empty or absent refresh_token. */+ @Test+ void tokenRefreshWithoutARefreshTokenIsInvalidRequest() throws Exception {+ Response absent = controller.token(null, requestContext(null),+ form("grant_type", "refresh_token", "client_id", CLIENT_ID));+ Response empty = controller.token(null, requestContext(null),+ form("grant_type", "refresh_token", "client_id", CLIENT_ID, "refresh_token", ""));++ String expected = "{\"error\":\"invalid_request\",\"error_description\":\"invalid_refresh_token\"}";+ assertOAuthBody("absent", absent, expected);+ assertOAuthBody("empty", empty, expected);+ verify(cognitoService, never()).getTokensFromRefreshToken(any(), any());+ }++ @Test+ void tokenRefreshOnTheCustomDomainOfTheClientsPoolRefreshes() {+ refreshesTo(Map.of("AccessToken", "access-token", "ExpiresIn", 3600, "TokenType", "Bearer"));++ Response response = controller.token(null, requestContext(POOL_ID), refreshForm());++ assertEquals(200, response.getStatus());+ }++ /** AWS refreshes at the token endpoint whatever the client's ExplicitAuthFlows and OAuth settings. */+ @Test+ void tokenRefreshDoesNotRequireTheRefreshFlowOrAnOAuthClient() {+ client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH"));+ client.setAllowedOAuthFlowsUserPoolClient(false);+ client.setAllowedOAuthFlows(List.of());+ client.setSupportedIdentityProviders(List.of());+ refreshesTo(Map.of("AccessToken", "access-token", "ExpiresIn", 3600, "TokenType", "Bearer"));++ Response response = controller.token(null, requestContext(null), refreshForm());++ assertEquals(200, response.getStatus());+ }++ @Test+ void tokenWithoutAGrantTypeIsInvalidRequestWithoutADescription() throws Exception {+ Response response = controller.token(null, requestContext(null),+ form("client_id", CLIENT_ID, "refresh_token", "refresh-token"));++ assertOAuthBody("no grant_type", response, "{\"error\":\"invalid_request\"}");+ }++ /** AWS: an invalid, expired or revoked refresh token, or one of another client, without a description. */+ @ParameterizedTest+ @CsvSource({+ "NotAuthorizedException, Invalid Refresh Token",+ "NotAuthorizedException, Refresh Token has expired",+ "NotAuthorizedException, Refresh Token has been revoked",+ "NotAuthorizedException, Refresh Token has different Client",+ "UserNotFoundException, User does not exist."+ })+ void tokenRefreshMapsARefusedRefreshTokenToInvalidGrant(String errorCode, String message) throws Exception {+ when(cognitoService.getTokensFromRefreshToken(CLIENT_ID, "refresh-token"))+ .thenThrow(new AwsException(errorCode, message, 400));++ Response response = controller.token(null, requestContext(null), refreshForm());++ assertOAuthBody(message, response, "{\"error\":\"invalid_grant\"}");+ }+@Testvoid revokeAnswersOkWithAnEmptyBodyForAPublicClient() {Response response = controller.revoke(null, requestContext(null),@@ -712,6 +894,15 @@ class CognitoOAuthControllerTest {return form;}+ private void refreshesTo(Map<String, Object> authenticationResult) {+ when(cognitoService.getTokensFromRefreshToken(CLIENT_ID, "refresh-token"))+ .thenReturn(Map.of("AuthenticationResult", authenticationResult));+ }++ private static MultivaluedHashMap<String, String> refreshForm() {+ return form("grant_type", "refresh_token", "client_id", CLIENT_ID, "refresh_token", "refresh-token");+ }+private static MultivaluedHashMap<String, String> validAuthorizationCodeForm(String code) {return form("grant_type", "authorization_code", "client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI);}@@ -804,6 +995,13 @@ class CognitoOAuthControllerTest {return names;}+ /** A 400 whose JSON body is exactly {@code expectedBody}, without a WWW-Authenticate challenge. */+ private void assertOAuthBody(String message, Response response, String expectedBody) throws Exception {+ assertEquals(400, response.getStatus(), message);+ assertEquals(objectMapper.readTree(expectedBody), response.getEntity(), message);+ assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE), message);+ }+private void assertOAuthError(Response response, String error) {assertOAuthError(response, 400, error);}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.javaindex d2d7a37f27..8a63a21c2c 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java@@ -6,12 +6,15 @@ import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.Simport io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;import io.restassured.response.Response;+import io.restassured.specification.RequestSpecification;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;+import javax.crypto.Mac;+import javax.crypto.spec.SecretKeySpec;import java.math.BigInteger;import java.nio.charset.StandardCharsets;import java.security.KeyFactory;@@ -19,12 +22,15 @@ import java.security.PublicKey;import java.security.Signature;import java.security.spec.RSAPublicKeySpec;import java.util.Base64;+import java.util.HashSet;+import java.util.Set;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.PASSWORD;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.assertInvalidClient;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.assertRevoked;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.basic;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refresh;+import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refreshGrant;import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.signIn;import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;@@ -40,6 +46,7 @@ class CognitoOAuthTokenIntegrationTest {private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();private static final String REVOKE = "/cognito-idp/oauth2/revoke";+ private static final String INVALID_GRANT = "{\"error\":\"invalid_grant\"}";private static String poolId;private static String clientId;@@ -367,23 +374,21 @@ class CognitoOAuthTokenIntegrationTest {.body("error", equalTo("invalid_scope"));}+ /** AWS: 400 with no error_description. */@Test@Order(15)- void missingGrantTypeReturnsInvalidRequest() {- given()+ void missingGrantTypeReturnsInvalidRequest() throws Exception {+ assertBody(given().formParam("client_id", clientId).when()- .post("/cognito-idp/oauth2/token")- .then()- .statusCode(400)- .body("error", equalTo("invalid_request"));+ .post("/cognito-idp/oauth2/token"), 400, "{\"error\":\"invalid_request\"}");}@Test@Order(16)void unsupportedGrantTypeReturnsUnsupportedGrantType() {given()- .formParam("grant_type", "refresh_token")+ .formParam("grant_type", "password").formParam("client_id", clientId).when().post("/cognito-idp/oauth2/token")@@ -653,6 +658,248 @@ class CognitoOAuthTokenIntegrationTest {tokens.path("RefreshToken").asText());}+ /**+ * AWS accepts a refresh token from a sign-in through the API at the token endpoint: a new access+ * token with the API sign-in scope, the same family and auth_time, an ID token as the sign-in had,+ * and no new refresh token.+ */+ @Test+ @Order(30)+ void refreshGrantRenewsTheTokensOfAPublicClient() throws Exception {+ SignedInUser user = signIn(poolId);++ Response response = refreshGrant(null, user.clientId(), user.refreshToken());++ response.then()+ .statusCode(200)+ .contentType(containsString("application/json"))+ .header("Cache-Control", equalTo("no-store"))+ .body("token_type", equalTo("Bearer"))+ .body("expires_in", equalTo(3600));+ assertEquals(Set.of("access_token", "id_token", "expires_in", "token_type"), fieldNames(response));+ JsonNode signedIn = decodeJwtPayload(user.accessToken());+ JsonNode refreshed = decodeJwtPayload(response.path("access_token"));+ assertEquals("aws.cognito.signin.user.admin", refreshed.path("scope").asText());+ assertNotEquals(signedIn.path("jti").asText(), refreshed.path("jti").asText());+ assertEquals(signedIn.path("origin_jti").asText(), refreshed.path("origin_jti").asText());+ assertEquals(signedIn.path("auth_time").asLong(), refreshed.path("auth_time").asLong());+ assertTrue(refreshed.path("iat").asLong() >= signedIn.path("iat").asLong());+ assertEquals(user.clientId(), decodeJwtPayload(response.path("id_token")).path("aud").asText());+ getUser(response.path("access_token")).then().statusCode(200);+ }++ @Test+ @Order(31)+ void refreshGrantWithAnEmptyOrAbsentRefreshTokenIsInvalidRequest() throws Exception {+ SignedInUser user = signIn(poolId);+ String expected = "{\"error\":\"invalid_request\",\"error_description\":\"invalid_refresh_token\"}";++ assertBody(given().formParam("grant_type", "refresh_token").formParam("client_id", user.clientId())+ .when().post("/cognito-idp/oauth2/token"), 400, expected);+ assertBody(refreshGrant(null, user.clientId(), ""), 400, expected);+ }++ @Test+ @Order(32)+ void refreshGrantIsInvalidGrantAfterRevokeToken() throws Exception {+ SignedInUser user = signIn(poolId);+ cognitoAction("RevokeToken", """+ {"Token": "%s", "ClientId": "%s"}+ """.formatted(user.refreshToken(), user.clientId())).then().statusCode(200);++ assertBody(refreshGrant(null, user.clientId(), user.refreshToken()), 400, INVALID_GRANT);+ }++ @Test+ @Order(33)+ void refreshGrantIsInvalidGrantAfterTheRevocationEndpoint() throws Exception {+ SignedInUser user = signIn(poolId);+ revoke(user.refreshToken(), user.clientId()).then().statusCode(200);++ assertBody(refreshGrant(null, user.clientId(), user.refreshToken()), 400, INVALID_GRANT);+ }++ @Test+ @Order(34)+ void refreshGrantRefusesATokenIssuedToAnotherClient() throws Exception {+ SignedInUser user = signIn(poolId);+ SignedInUser otherClientsUser = signIn(poolId);++ assertBody(refreshGrant(null, otherClientsUser.clientId(), user.refreshToken()), 400, INVALID_GRANT);+ }++ /** AWS: both API operations that refresh refuse another client's refresh token with the same answer. */+ @Test+ @Order(35)+ void theApiRefusesARefreshTokenIssuedToAnotherClient() throws Exception {+ SignedInUser user = signIn(poolId);+ SignedInUser otherClientsUser = signIn(poolId);+ String expected = "{\"__type\":\"NotAuthorizedException\",\"message\":\"Refresh Token has different Client\"}";++ assertBody(cognitoAction("GetTokensFromRefreshToken", """+ {"ClientId": "%s", "RefreshToken": "%s"}+ """.formatted(otherClientsUser.clientId(), user.refreshToken())), 400, expected);+ assertBody(refresh(new SignedInUser(otherClientsUser.clientId(), null, user.refreshToken())), 400, expected);+ }++ @Test+ @Order(36)+ void refreshGrantWithAGarbageOrAlteredRefreshTokenIsInvalidGrant() throws Exception {+ SignedInUser user = signIn(poolId);+ char original = user.refreshToken().charAt(10);+ String altered = user.refreshToken().substring(0, 10) + (original == 'A' ? 'B' : 'A')+ + user.refreshToken().substring(11);++ assertBody(refreshGrant(null, user.clientId(), "not-a-refresh-token"), 400, INVALID_GRANT);+ assertBody(refreshGrant(null, user.clientId(), altered), 400, INVALID_GRANT);+ }++ /** AWS checks the client before the refresh token, and answers without a description. */+ @Test+ @Order(37)+ void refreshGrantRefusesAClientItCannotIdentify() throws Exception {+ SignedInUser user = signIn(poolId);+ String expected = "{\"error\":\"invalid_client\"}";++ assertBody(refreshGrant(null, "unknown-client", "not-a-refresh-token"), 400, expected);+ assertBody(refreshGrant(null, "not a client id!", "not-a-refresh-token"), 400, expected);+ assertBody(given().formParam("grant_type", "refresh_token").formParam("refresh_token", user.refreshToken())+ .when().post("/cognito-idp/oauth2/token"), 400, expected);+ assertBody(given().header("Authorization", "Basic " + Base64.getEncoder()+ .encodeToString((user.clientId() + ":").getBytes(StandardCharsets.UTF_8)))+ .formParam("grant_type", "refresh_token").formParam("refresh_token", user.refreshToken())+ .when().post("/cognito-idp/oauth2/token"), 400, expected);+ }++ /**+ * AWS: a client with a secret sends it in the body or in Basic, and a Basic header names the+ * client whatever the body's client_id says. A missing or wrong secret is the same 400.+ */+ @Test+ @Order(38)+ void refreshGrantAuthenticatesAConfidentialClient() throws Exception {+ JsonNode created = cognitoJson("CreateUserPoolClient", """+ {"UserPoolId": "%s", "ClientName": "confidential-refresh-client", "GenerateSecret": true,+ "ExplicitAuthFlows": ["ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]}+ """.formatted(poolId)).path("UserPoolClient");+ String confidentialId = created.path("ClientId").asText();+ String secret = created.path("ClientSecret").asText();+ String refreshToken = confidentialRefreshToken(confidentialId, secret);+ String publicClientId = signIn(poolId).clientId();+ String invalidSecret = "{\"error\":\"invalid_client\",\"error_description\":\"invalid_client_secret\"}";++ assertBody(refreshGrant(null, confidentialId, refreshToken), 400, invalidSecret);+ assertBody(refreshWithBodySecret(confidentialId, "not-the-secret", refreshToken), 400, invalidSecret);+ assertBody(refreshWithBasic(basic(confidentialId, "not-the-secret"), null, refreshToken), 400, invalidSecret);+ refreshWithBodySecret(confidentialId, secret, refreshToken).then().statusCode(200);+ refreshWithBasic(basic(confidentialId, secret), null, refreshToken).then().statusCode(200);+ refreshWithBasic(basic(confidentialId, secret), confidentialId, refreshToken).then().statusCode(200);+ Response basicWins = refreshWithBasic(basic(confidentialId, secret), publicClientId, refreshToken);+ basicWins.then().statusCode(200);+ assertEquals(confidentialId, decodeJwtPayload(basicWins.path("access_token")).path("client_id").asText());+ }++ /**+ * AWS refreshes at the token endpoint for a client without ALLOW_REFRESH_TOKEN_AUTH and without+ * any OAuth settings, unlike the refresh operations of the API.+ */+ @Test+ @Order(39)+ void refreshGrantDoesNotRequireTheRefreshFlowOrAnOAuthClient() throws Exception {+ String passwordOnlyClient = cognitoJson("CreateUserPoolClient", """+ {"UserPoolId": "%s", "ClientName": "password-only-client",+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH"]}+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();+ String username = "password-only-" + System.nanoTime();+ cognitoAction("AdminCreateUser", """+ {"UserPoolId": "%s", "Username": "%s"}+ """.formatted(poolId, username)).then().statusCode(200);+ cognitoAction("AdminSetUserPassword", """+ {"UserPoolId": "%s", "Username": "%s", "Password": "%s", "Permanent": true}+ """.formatted(poolId, username, PASSWORD)).then().statusCode(200);+ String refreshToken = cognitoJson("InitiateAuth", """+ {"ClientId": "%s", "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}}+ """.formatted(passwordOnlyClient, username, PASSWORD))+ .path("AuthenticationResult").path("RefreshToken").asText();++ Response response = refreshGrant(null, passwordOnlyClient, refreshToken);++ response.then().statusCode(200);+ assertEquals(Set.of("access_token", "id_token", "expires_in", "token_type"), fieldNames(response));+ }++ /**+ * AWS: a public client has no secret, so in a Basic header a secret is wrong and an empty one, or+ * none, names no client. A client_secret in the body of a public client is ignored.+ */+ @Test+ @Order(40)+ void refreshGrantRefusesBasicCredentialsOfAPublicClient() throws Exception {+ SignedInUser user = signIn(poolId);+ String bareInvalidClient = "{\"error\":\"invalid_client\"}";++ assertBody(refreshWithBasic(basic(user.clientId(), "wrongsecret"), null, user.refreshToken()), 400,+ "{\"error\":\"invalid_client\",\"error_description\":\"invalid_client_secret\"}");+ assertBody(refreshWithBasic(basic(user.clientId(), ""), user.clientId(), user.refreshToken()), 400,+ bareInvalidClient);+ assertBody(refreshWithBasic("Basic " + Base64.getEncoder().encodeToString(+ user.clientId().getBytes(StandardCharsets.UTF_8)), null, user.refreshToken()), 400, bareInvalidClient);+ refreshWithBodySecret(user.clientId(), "wrongsecret", user.refreshToken()).then().statusCode(200);+ }++ private static String confidentialRefreshToken(String confidentialId, String secret) throws Exception {+ String username = "confidential-" + System.nanoTime();+ cognitoAction("AdminCreateUser", """+ {"UserPoolId": "%s", "Username": "%s"}+ """.formatted(poolId, username)).then().statusCode(200);+ cognitoAction("AdminSetUserPassword", """+ {"UserPoolId": "%s", "Username": "%s", "Password": "%s", "Permanent": true}+ """.formatted(poolId, username, PASSWORD)).then().statusCode(200);+ Mac mac = Mac.getInstance("HmacSHA256");+ mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));+ String secretHash = Base64.getEncoder().encodeToString(+ mac.doFinal((username + confidentialId).getBytes(StandardCharsets.UTF_8)));+ return cognitoJson("AdminInitiateAuth", """+ {"UserPoolId": "%s", "ClientId": "%s", "AuthFlow": "ADMIN_USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s", "SECRET_HASH": "%s"}}+ """.formatted(poolId, confidentialId, username, PASSWORD, secretHash))+ .path("AuthenticationResult").path("RefreshToken").asText();+ }++ private static Response refreshWithBodySecret(String clientId, String clientSecret, String refreshToken) {+ return given()+ .formParam("grant_type", "refresh_token")+ .formParam("client_id", clientId)+ .formParam("client_secret", clientSecret)+ .formParam("refresh_token", refreshToken)+ .when()+ .post("/cognito-idp/oauth2/token");+ }++ private static Response refreshWithBasic(String authorization, String bodyClientId, String refreshToken) {+ RequestSpecification request = given()+ .header("Authorization", authorization)+ .formParam("grant_type", "refresh_token")+ .formParam("refresh_token", refreshToken);+ if (bodyClientId != null) {+ request.formParam("client_id", bodyClientId);+ }+ return request.when().post("/cognito-idp/oauth2/token");+ }++ /** The response's status, no WWW-Authenticate challenge, and a JSON body with exactly {@code expectedBody}'s fields and values. */+ private static void assertBody(Response response, int status, String expectedBody) throws Exception {+ response.then().statusCode(status).header("WWW-Authenticate", nullValue());+ assertEquals(OBJECT_MAPPER.readTree(expectedBody), OBJECT_MAPPER.readTree(response.asString()));+ }++ private static Set<String> fieldNames(Response response) throws Exception {+ Set<String> names = new HashSet<>();+ OBJECT_MAPPER.readTree(response.asString()).fieldNames().forEachRemaining(names::add);+ return names;+ }+private static Response revoke(String token, String clientId) {return given().formParam("token", token)diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javaindex 15322c1647..8ee0077c03 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -45,6 +45,7 @@ import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;+import java.util.UUID;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -4610,6 +4611,197 @@ class CognitoServiceTest {assertEquals("NotAuthorizedException", exception.getErrorCode());}+ // =========================================================================+ // A refresh keeps the scopes of the OAuth grant+ // =========================================================================++ /** A scope may contain a pipe, the field separator, so the scopes travel base64url-encoded. */+ @Test+ void refreshTokenOfACodeGrantKeepsItsFieldsAndCarriesTheGrantedScopes() {+ UserPool pool = createPoolAndUser();++ String[] parts = service.parseRefreshToken(service.buildRefreshToken(pool, "alice", "client-id",+ 1_790_000_000_123L, "family-id", List.of("openid", "notes/read|write")));++ assertEquals(List.of(pool.getId(), "alice", "client-id", "1790000000123", "family-id",+ "openid notes/read|write"), List.of(parts));+ }++ @Test+ void refreshTokenOfACodeGrantWithoutScopesHasAnEmptyScopeField() {+ UserPool pool = createPoolAndUser();++ String[] parts = service.parseRefreshToken(+ service.buildRefreshToken(pool, "alice", "client-id", 1_790_000_000_123L, "family-id", List.of()));++ assertEquals(6, parts.length);+ assertEquals("", parts[5]);+ }++ @Test+ void refreshTokenOfAnApiSignInHasNoScopeField() {+ UserPool pool = createPoolAndUser();++ String[] parts = service.parseRefreshToken(+ service.buildRefreshToken(pool, "alice", "client-id", 1_790_000_000_123L, "family-id", null));++ assertEquals(List.of(pool.getId(), "alice", "client-id", "1790000000123", "family-id"), List.of(parts));+ }++ /**+ * AWS accepts a username holding a pipe, the field separator, and refreshes its tokens. Only the+ * username can hold one, so a refresh token is read from both ends.+ */+ @Test+ @SuppressWarnings("unchecked")+ void aUsernameHoldingAPipeRefreshesOnBothApis() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");+ service.adminCreateUser(pool.getId(), "pipe|user", Map.of("email", "[email protected]"), "TempPass1!");+ service.adminSetUserPassword(pool.getId(), "pipe|user", "Perm1234!", true);+ UserPoolClient client = openClient(service, pool.getId(), "c", false);+ String refreshToken = (String) ((Map<String, Object>) service.initiateAuth(client.getClientId(),+ "USER_PASSWORD_AUTH", Map.of("USERNAME", "pipe|user", "PASSWORD", "Perm1234!"))+ .get("AuthenticationResult")).get("RefreshToken");++ assertEquals("pipe|user", service.parseRefreshToken(refreshToken)[1]);+ assertNotNull(service.getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult"));+ assertNotNull(service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",+ Map.of("REFRESH_TOKEN", refreshToken)).get("AuthenticationResult"));+ assertEquals(List.of(pool.getId(), "pipe|user", "client-id", "1790000000123", "family-id", "openid"),+ List.of(service.parseRefreshToken(service.buildRefreshToken(pool, "pipe|user", "client-id",+ 1_790_000_000_123L, "family-id", List.of("openid")))));+ }++ @Test+ @SuppressWarnings("unchecked")+ void getTokensFromRefreshTokenOfACodeGrantKeepsItsScopesAndIssuesAnIdTokenOnlyWithOpenid() throws Exception {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, true, List.of("code"),+ List.of("openid", "email", "aws.cognito.signin.user.admin"), null, List.of("https://app.example.test/cb"),+ null, List.of(), null, null, List.of(), null, List.of(), null, null, null, List.of(), null, null);+ CognitoUser user = service.adminGetUser(pool.getId(), "alice");++ for (List<String> granted : List.of(List.of("openid", "email"), List.of("email"))) {+ String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null, granted)+ .get("RefreshToken");++ Map<String, Object> refreshed = (Map<String, Object>) service+ .getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult");++ JsonNode accessClaims = MAPPER.readTree(jwtPayload((String) refreshed.get("AccessToken")));+ assertEquals(String.join(" ", granted), accessClaims.path("scope").asText(), "granted " + granted);+ assertEquals(granted.contains("openid"), refreshed.containsKey("IdToken"), "granted " + granted);+ assertNull(refreshed.get("RefreshToken"));+ }+ }++ /** A code grant of a client that allows no scopes has no scope claim and no ID token, nor does its refresh. */+ @Test+ @SuppressWarnings("unchecked")+ void getTokensFromRefreshTokenOfACodeGrantWithoutScopesDoesNotGainTheApiSignInScope() throws Exception {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());+ CognitoUser user = service.adminGetUser(pool.getId(), "alice");+ String refreshToken = (String) service.generateAuthResultForHostedAuth(user, pool, client, null, List.of())+ .get("RefreshToken");++ Map<String, Object> refreshed = (Map<String, Object>) service+ .getTokensFromRefreshToken(client.getClientId(), refreshToken).get("AuthenticationResult");++ assertFalse(MAPPER.readTree(jwtPayload((String) refreshed.get("AccessToken"))).has("scope"));+ assertFalse(refreshed.containsKey("IdToken"));+ }++ /** A token minted before refresh tokens carried scopes refreshes as an API sign-in does. */+ @Test+ @SuppressWarnings("unchecked")+ void getTokensFromRefreshTokenWithoutTheScopeFieldIssuesTheApiSignInScopeAndAnIdToken() throws Exception {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = openClient(service, pool.getId(), "c", false);+ String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + System.currentTimeMillis() + "|"+ + UUID.randomUUID();++ Map<String, Object> refreshed = (Map<String, Object>) service+ .getTokensFromRefreshToken(client.getClientId(), signRawRefreshToken(pool, raw))+ .get("AuthenticationResult");++ JsonNode accessClaims = MAPPER.readTree(jwtPayload((String) refreshed.get("AccessToken")));+ assertEquals("aws.cognito.signin.user.admin", accessClaims.path("scope").asText());+ assertNotNull(refreshed.get("IdToken"));+ }++ @Test+ @SuppressWarnings("unchecked")+ void getTokensFromRefreshTokenRefusesATokenIssuedToAnotherClient() {+ UserPool pool = createPoolAndUser();+ UserPoolClient issuedTo = openClient(service, pool.getId(), "issued-to", false);+ UserPoolClient other = openClient(service, pool.getId(), "other", false);+ String refreshToken = (String) ((Map<String, Object>) service.initiateAuth(issuedTo.getClientId(),+ "USER_PASSWORD_AUTH", Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"))+ .get("AuthenticationResult")).get("RefreshToken");++ AwsException exception = assertThrows(AwsException.class, () ->+ service.getTokensFromRefreshToken(other.getClientId(), refreshToken));++ assertEquals("NotAuthorizedException", exception.getErrorCode());+ assertEquals("Refresh Token has different Client", exception.getMessage());+ }++ @Test+ @SuppressWarnings("unchecked")+ void refreshTokenAuthFlowRefusesATokenIssuedToAnotherClient() {+ UserPool pool = createPoolAndUser();+ UserPoolClient issuedTo = openClient(service, pool.getId(), "issued-to", false);+ UserPoolClient other = openClient(service, pool.getId(), "other", false);+ String refreshToken = (String) ((Map<String, Object>) service.initiateAuth(issuedTo.getClientId(),+ "USER_PASSWORD_AUTH", Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"))+ .get("AuthenticationResult")).get("RefreshToken");++ AwsException exception = assertThrows(AwsException.class, () -> service.initiateAuth(other.getClientId(),+ "REFRESH_TOKEN_AUTH", Map.of("REFRESH_TOKEN", refreshToken)));++ assertEquals("NotAuthorizedException", exception.getErrorCode());+ assertEquals("Refresh Token has different Client", exception.getMessage());+ }++ /** A sign-in's tokens are authenticated at the moment its refresh token is issued. */+ @Test+ @SuppressWarnings("unchecked")+ void signInAuthTimeIsTheIssuedAtOfItsRefreshToken() throws Exception {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = openClient(service, pool.getId(), "c", false);++ Map<String, Object> auth = (Map<String, Object>) service.initiateAuth(client.getClientId(),+ "USER_PASSWORD_AUTH", Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")).get("AuthenticationResult");++ long issuedAtSeconds = Long.parseLong(service.parseRefreshToken((String) auth.get("RefreshToken"))[3]) / 1000L;+ assertEquals(issuedAtSeconds, MAPPER.readTree(jwtPayload((String) auth.get("AccessToken"))).path("auth_time").asLong());+ assertEquals(issuedAtSeconds, MAPPER.readTree(jwtPayload((String) auth.get("IdToken"))).path("auth_time").asLong());+ }++ /** AWS: a refresh does not authenticate the user again, so the new tokens keep the sign-in's auth_time. */+ @Test+ @SuppressWarnings("unchecked")+ void refreshKeepsTheAuthTimeOfTheSignInOnBothApis() throws Exception {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = openClient(service, pool.getId(), "c", false);+ long issuedAtMillis = System.currentTimeMillis() - 120_000L;+ String refreshToken = signRawRefreshToken(pool,+ pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAtMillis + "|" + UUID.randomUUID());++ for (Map<String, Object> response : List.of(+ service.getTokensFromRefreshToken(client.getClientId(), refreshToken),+ service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",+ Map.of("REFRESH_TOKEN", refreshToken)))) {+ Map<String, Object> refreshed = (Map<String, Object>) response.get("AuthenticationResult");+ for (String token : List.of((String) refreshed.get("AccessToken"), (String) refreshed.get("IdToken"))) {+ JsonNode claims = MAPPER.readTree(jwtPayload(token));+ assertEquals(issuedAtMillis / 1000L, claims.path("auth_time").asLong());+ assertTrue(claims.path("iat").asLong() > claims.path("auth_time").asLong());+ }+ }+ }+// =========================================================================// deleteUserPool cascades groups// =========================================================================