feat(cognito): accept the refresh_token grant on the OAuth token endpoint (#4948)

POST /cognito-idp/oauth2/token, and /oauth2/token on a custom domain, now
renew a session with grant_type=refresh_token through the refresh that
GetTokensFromRefreshToken uses, answering as AWS does. As on AWS, the
grant requires neither ALLOW_REFRESH_TOKEN_AUTH nor any OAuth setting on
the client. The client is checked before the token: a Basic header names
it whatever the body says. A public client's Basic credentials are
refused, and its body client_secret is ignored. Errors are 400 without
WWW-Authenticate: invalid_client for a missing or unknown client, a
public client's Basic credentials with an empty secret, or another pool's
client on a custom domain; invalid_client with invalid_client_secret for
a missing or wrong secret, or a public client's Basic credentials with a
secret; invalid_request with invalid_refresh_token for an empty or absent
token; and invalid_grant for a token that is not valid, expired, revoked,
or another client's. The answer has access_token, expires_in, token_type,
and an id_token exactly when the original sign-in issued one, and no
refresh_token, as rotation is not implemented. A request without
grant_type is now invalid_request with no description, as on AWS.

A code grant's refresh token now carries its granted scopes, base64url
encoded in a field after the family id, so a refresh keeps them instead of
falling back to aws.cognito.signin.user.admin, and the pre token
generation trigger is told them. API sign-ins and tokens minted before
this change have no such field and refresh as before. A refresh keeps the
sign-in's auth_time and origin_jti. InitiateAuth REFRESH_TOKEN_AUTH and
GetTokensFromRefreshToken mint the same tokens as the token endpoint.

As on AWS, a refresh of a grant holding a scope the client no longer
allows is refused rather than narrowed: invalid_grant on the token
endpoint, and NotAuthorizedException "Client is not allowed to request
these scopes" on both APIs. The refresh token is parsed from both ends,
so a username holding a pipe refreshes too.

GetTokensFromRefreshToken and InitiateAuth REFRESH_TOKEN_AUTH now refuse a
refresh token issued to another client with NotAuthorizedException
"Refresh Token has different Client".
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-12 16:34:25 -04:00
1 parent 991bf3ab9e
commit 2d7ebcb51c
11 files changed
+1134 -61

No files matched your search

@@ -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()
@@ -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.CognitoCustomDomainFix
import 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()));
}
}
@@ -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.
@@ -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(" "));
@@ -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\"}");
}
@Test
void 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);
}
@@ -6,12 +6,15 @@ import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.S
import 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)
@@ -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", "pipe@example.com"), "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
// =========================================================================