Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): expire refresh tokens and scope them to their own pool in REFRESH_TOKEN_AUTH (#2135)
Abhigya7d8acede18a4
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 b75a71254e..f9e1aa8925 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@@ -234,6 +234,13 @@ final class CognitoAuthFlowHandler {if (parts == null) {throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);}+ // Scope the token to the pool that minted it. HMAC verification only proves the token+ // was signed by parts[0]'s pool, not that parts[0] is the pool serving this request, so+ // a token legitimately issued for pool A must not be replayed against pool B's client.+ // Mirrors getTokensFromRefreshToken's pool-id check.+ if (!pool.getId().equals(parts[0])) {+ throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);+ }String username = parts[1];long iat;try {@@ -243,6 +250,10 @@ final class CognitoAuthFlowHandler {}String refreshTokenUuid = parts.length > 4 ? parts[4] : null;+ if (service.isRefreshTokenExpired(client, parts)) {+ throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400);+ }+// Check revocation before issuing new tokensservice.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);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 d9560c8f75..1271f818dd 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@@ -2399,14 +2399,17 @@ public class CognitoService {return configured == null || configured.isBlank() ? defaultUnit : configured.trim().toLowerCase(Locale.ROOT);}- private boolean isRefreshTokenExpired(UserPoolClient client, String[] parts) {+ boolean isRefreshTokenExpired(UserPoolClient client, String[] parts) {if (parts.length < 5) {return false;}try {- long issuedAt = Long.parseLong(parts[3]);- long expiresAt = issuedAt + resolveTokenLifetimeSeconds(client, "refresh");- return System.currentTimeMillis() / 1000L >= expiresAt;+ // buildRefreshToken writes issued-at as epoch milliseconds, but the lifetime and+ // the comparison clock below are in seconds — convert before comparing so the check+ // is not off by a factor of ~1000 (which made it never fire for real tokens).+ long issuedAtSeconds = Long.parseLong(parts[3]) / 1000L;+ long expiresAtSeconds = issuedAtSeconds + resolveTokenLifetimeSeconds(client, "refresh");+ return System.currentTimeMillis() / 1000L >= expiresAtSeconds;} catch (NumberFormatException ignored) {return false;}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 e576b88d7e..1ddb455358 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@@ -1860,6 +1860,70 @@ class CognitoServiceTest {assertNotNull(refreshed.get("IdToken"));}+ @Test+ void refreshTokenAuthFlowExpiredTokenThrows() {+ UserPool pool = createPoolAndUser();+ UserPoolClient client = service.createUserPoolClient(+ pool.getId(),+ "c",+ false,+ false,+ List.of(),+ List.of(),+ null,+ List.of(),+ null,+ List.of(),+ null,+ null,+ List.of(),+ null,+ List.of(),+ 1,+ List.of(),+ Map.of("RefreshToken", "seconds"),+ List.of(),+ null,+ null+ );++ // issued-at is epoch MILLISECONDS, exactly as buildRefreshToken writes it. A token+ // issued 10s ago against a 1s refresh lifetime is expired only if isRefreshTokenExpired+ // converts millis to seconds before comparing — before the fix the InitiateAuth+ // REFRESH_TOKEN_AUTH path never called the check at all, so this minted fresh tokens.+ long issuedAtMillis = System.currentTimeMillis() - 10_000L;+ String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAtMillis + "|"+ + java.util.UUID.randomUUID();+ String expiredRefreshToken = signRawRefreshToken(pool, raw);++ AwsException exception = assertThrows(AwsException.class, () ->+ service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",+ Map.of("REFRESH_TOKEN", expiredRefreshToken)));+ assertEquals("NotAuthorizedException", exception.getErrorCode());+ }++ @Test+ @SuppressWarnings("unchecked")+ void refreshTokenAuthFlowRejectsTokenFromAnotherPool() {+ // Two independent pools, each with an "alice". A refresh token minted for poolB is+ // validly HMAC-signed (by poolB) and its username resolves in poolA too, so the only+ // thing that can reject it against poolA's client is the embedded pool-id check.+ UserPool poolA = createPoolAndUser();+ UserPool poolB = createPoolAndUser();+ UserPoolClient clientA = service.createUserPoolClient(poolA.getId(), "ca", false, false, List.of(), List.of());+ UserPoolClient clientB = service.createUserPoolClient(poolB.getId(), "cb", false, false, List.of(), List.of());++ Map<String, Object> authB = (Map<String, Object>) service.initiateAuth(+ clientB.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")).get("AuthenticationResult");+ String foreignRefreshToken = (String) authB.get("RefreshToken");++ AwsException exception = assertThrows(AwsException.class, () ->+ service.initiateAuth(clientA.getClientId(), "REFRESH_TOKEN_AUTH",+ Map.of("REFRESH_TOKEN", foreignRefreshToken)));+ assertEquals("NotAuthorizedException", exception.getErrorCode());+ }+// =========================================================================// Issue #2137 — Refresh tokens must be unforgeable (HMAC-signed)// =========================================================================