fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH (#2132)

* fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH

InitiateAuth with AuthFlow=REFRESH_TOKEN_AUTH silently fell back to
minting fresh tokens for a fake "unknown" user whenever the supplied
REFRESH_TOKEN failed to parse or didn't resolve to a real user,
instead of failing like GetTokensFromRefreshToken already does.

Fixes #2113

* test(cognito): add regression tests for invalid refresh token rejection

Cover InitiateAuth REFRESH_TOKEN_AUTH with a garbage token and with a
well-formed token encoding a nonexistent user; both must fail with
NotAuthorizedException rather than returning an AuthenticationResult.

* test(cognito): add regression test for non-numeric refresh token issued-at

Covers a well-formed refresh token whose issued-at field is not a
number; must fail with 400 NotAuthorizedException rather than the
500 NumberFormatException that surfaced before the parse was guarded.

* fix(ec2): make network interface pagination tests order-independent

describeNetworkInterfacesWithMaxResultsNoNextToken and
describeNetworkInterfacesMultipagePagination assumed a fixed/low ENI
count, but other tests in this class are not isolated and can leave
ENIs behind depending on JUnit's tie-breaking order among tests
sharing @Order(92). Use MaxResults=1000 for the single-page case and
measure the actual ENI baseline before asserting page counts for the
multipage case.
This commit is contained in:
Feyikemi Ogunsanya authored and GitHub committed 2026-08-10 19:01:47 -05:00
1 parent 50fe67dde6
commit 3ce5041c71
3 files changed
+142 -34

No files matched your search

@@ -246,7 +246,17 @@ final class CognitoAuthFlowHandler {
// Check revocation before issuing new tokens
service.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);
CognitoUser user = service.adminGetUser(pool.getId(), username);
CognitoUser user;
try {
user = service.adminGetUser(pool.getId(), username);
} catch (AwsException ae) {
// Real Cognito never reveals whether the encoded username exists; any
// refresh token that doesn't resolve to a real user is simply invalid.
if ("UserNotFoundException".equals(ae.getErrorCode())) {
throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);
}
throw ae;
}
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
clientMetadata, "TokenGeneration_RefreshTokens");
Map<String, Object> auth = new HashMap<>();
@@ -2351,6 +2351,65 @@ class CognitoIntegrationTest {
assertFalse(identity.path("primary").asBoolean());
}
// ── Issue #2113: InitiateAuth REFRESH_TOKEN_AUTH rejects garbage tokens ─
@Test
@Order(101)
void initiateAuthRefreshTokenAuthRejectsInvalidRefreshToken() {
cognitoAction("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "REFRESH_TOKEN_AUTH",
"AuthParameters": { "REFRESH_TOKEN": "invalid-refresh-token" }
}
""".formatted(clientId))
.then()
.statusCode(400)
.body("__type", org.hamcrest.Matchers.equalTo("NotAuthorizedException"));
}
@Test
@Order(102)
void initiateAuthRefreshTokenAuthRejectsUnknownWellFormedRefreshToken() {
// Well-formed shape (poolId|username|clientId|iat|nonce) but for a user that
// does not exist in this pool — must still be rejected, not silently accepted.
String bogusToken = java.util.Base64.getEncoder().withoutPadding().encodeToString(
(poolId + "|nonexistent-user|" + clientId + "|" + System.currentTimeMillis() + "|"
+ UUID.randomUUID()).getBytes(StandardCharsets.UTF_8));
cognitoAction("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "REFRESH_TOKEN_AUTH",
"AuthParameters": { "REFRESH_TOKEN": "%s" }
}
""".formatted(clientId, bogusToken))
.then()
.statusCode(400)
.body("__type", org.hamcrest.Matchers.equalTo("NotAuthorizedException"));
}
@Test
@Order(102)
void initiateAuthRefreshTokenAuthRejectsTokenWithNonNumericIssuedAt() {
// Well-formed shape (5 base64 parts), but the issued-at field is not a number.
// Must fail with NotAuthorizedException, not a 500 from an unguarded parseLong.
String bogusToken = java.util.Base64.getEncoder().withoutPadding().encodeToString(
(poolId + "|" + USERNAME + "|" + clientId + "|not-a-number|"
+ UUID.randomUUID()).getBytes(StandardCharsets.UTF_8));
cognitoAction("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "REFRESH_TOKEN_AUTH",
"AuthParameters": { "REFRESH_TOKEN": "%s" }
}
""".formatted(clientId, bogusToken))
.then()
.statusCode(400)
.body("__type", org.hamcrest.Matchers.equalTo("NotAuthorizedException"));
}
private static JsonNode decodeJwtPayload(String token) throws Exception {
return decodeJwtPart(token, 1);
}
@@ -2278,11 +2278,12 @@ class Ec2IntegrationTest {
void describeNetworkInterfacesWithMaxResultsNoNextToken() {
// When MaxResults exceeds the number of available ENIs,
// all results are returned and nextToken is omitted.
// This test works regardless of how many instances exist
// (including zero, e.g. when run in isolation).
// Other tests in this class are not isolated and may leave ENIs
// behind, so this uses the maximum allowed MaxResults (1000) to
// guarantee a single page regardless of test execution order.
String body = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("MaxResults", "5")
.formParam("MaxResults", "1000")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -2336,7 +2337,12 @@ class Ec2IntegrationTest {
@Test
@Order(92)
void describeNetworkInterfacesMultipagePagination() {
// ── Launch 5 additional instances to have 6 total ENIs ──
// Other tests in this class are not isolated and may leave ENIs
// behind, so the baseline is measured immediately before adding
// ours rather than assumed to be zero.
int baselineCount = countAllNetworkInterfaces();
// ── Launch 5 additional instances ──
List<String> batchIds = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890")
@@ -2355,38 +2361,43 @@ class Ec2IntegrationTest {
assert batchIds.size() == 5 : "Expected 5 new instances, got " + batchIds.size();
// ── Page 1: MaxResults=5, expect 5 ENIs + nextToken ──
String nextToken = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("MaxResults", "5")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(5))
.body("DescribeNetworkInterfacesResponse.nextToken", notNullValue())
.extract().path("DescribeNetworkInterfacesResponse.nextToken");
int expectedTotal = baselineCount + 5;
assert nextToken != null && !nextToken.isEmpty() : "Expected non-empty nextToken on truncated page";
// ── Walk every page with MaxResults=5, tracking whether a
// nextToken was seen on each page along the way ──
int collected = 0;
int pageCount = 0;
String nextToken = null;
do {
io.restassured.specification.RequestSpecification req = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("MaxResults", "5")
.header("Authorization", AUTH_HEADER);
if (nextToken != null) {
req = req.formParam("NextToken", nextToken);
}
io.restassured.response.Response resp = req.when().post("/");
resp.then().statusCode(200);
pageCount++;
// ── Page 2: use NextToken, expect remaining ENIs, no nextToken ──
String body = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("MaxResults", "5")
.formParam("NextToken", nextToken)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()",
org.hamcrest.Matchers.greaterThanOrEqualTo(1))
.extract().body().asString();
List<String> ids = resp.xmlPath().getList(
"DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId",
String.class);
collected += ids == null ? 0 : ids.size();
nextToken = resp.xmlPath().getString("DescribeNetworkInterfacesResponse.nextToken");
// Final page must NOT contain a nextToken element
org.hamcrest.MatcherAssert.assertThat(body,
not(containsString("<nextToken>")));
// Every page but the last must be a full page of 5.
if (nextToken != null && !nextToken.isEmpty()) {
org.hamcrest.MatcherAssert.assertThat(ids.size(), equalTo(5));
}
} while (nextToken != null && !nextToken.isEmpty());
org.hamcrest.MatcherAssert.assertThat(
"Expected " + expectedTotal + " ENIs across " + pageCount + " page(s)",
collected, equalTo(expectedTotal));
// With 5 new ENIs and MaxResults=5, at least one truncated page
// must have occurred (i.e. more than a single page was fetched).
org.hamcrest.MatcherAssert.assertThat(pageCount, greaterThanOrEqualTo(2));
// ── Cleanup: terminate the 5 extra instances ──
for (String id : batchIds) {
@@ -2401,6 +2412,34 @@ class Ec2IntegrationTest {
}
}
/**
* Counts all ENIs currently visible via DescribeNetworkInterfaces by
* walking every page. Used so pagination tests can compute an accurate
* baseline instead of assuming a fixed starting count.
*/
private static int countAllNetworkInterfaces() {
int total = 0;
String nextToken = null;
do {
io.restassured.specification.RequestSpecification req = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("MaxResults", "1000")
.header("Authorization", AUTH_HEADER);
if (nextToken != null) {
req = req.formParam("NextToken", nextToken);
}
io.restassured.response.Response resp = req.when().post("/");
resp.then().statusCode(200);
List<String> ids = resp.xmlPath().getList(
"DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId",
String.class);
total += ids == null ? 0 : ids.size();
nextToken = resp.xmlPath().getString("DescribeNetworkInterfacesResponse.nextToken");
} while (nextToken != null && !nextToken.isEmpty());
return total;
}
// =========================================================================
// Volumes
// =========================================================================