Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Feyikemi Ogunsanya3ce5041c717c
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
index ee2e413281..b75a71254e 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
@@ -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<>();
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
index 615ca796dd..ec1ccfc9b2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
@@ -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);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
index dce3eb15c9..75e71afb04 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
@@ -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");
-
- assert nextToken != null && !nextToken.isEmpty() : "Expected non-empty nextToken on truncated page";
-
- // ── 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();
-
- // Final page must NOT contain a nextToken element
- org.hamcrest.MatcherAssert.assertThat(body,
- not(containsString("<nextToken>")));
+ int expectedTotal = baselineCount + 5;
+
+ // ── 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++;
+
+ List<String> ids = resp.xmlPath().getList(
+ "DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId",
+ String.class);
+ collected += ids == null ? 0 : ids.size();
+ nextToken = resp.xmlPath().getString("DescribeNetworkInterfacesResponse.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
// =========================================================================