fix(cognito): expire refresh tokens and scope them to their own pool in REFRESH_TOKEN_AUTH (#2135)

Rebased onto current main and trimmed to the parts still missing after
#2132 (unparsable/unresolvable-token rejection) and #2139 (HMAC signing)
merged. What #2132 already covers — null-parse, non-numeric issued-at,
and UserNotFound rejection — is dropped; two independent defects remain:

- Expiry never fired. buildRefreshToken writes issued-at in epoch
  milliseconds, but isRefreshTokenExpired compared it as seconds against
  a seconds clock, so real tokens looked ~1000x fresher than they were
  and never expired. Fixed the millis->seconds conversion, and called
  the check on the InitiateAuth REFRESH_TOKEN_AUTH path, which never
  invoked it at all (GetTokensFromRefreshToken already did).

- Cross-pool replay. HMAC verification proves a token was signed by the
  pool in parts[0], not that parts[0] is the pool serving the request. A
  token legitimately minted for pool A was accepted against pool B's
  client whenever the username existed in both. Added the embedded
  pool-id check, mirroring getTokensFromRefreshToken's existing guard.

Tests live in CognitoServiceTest (alongside #2139's refresh-token
security tests) because HMAC signing means a valid token can only be
built with the pool's secret. Both fail on main for the right reason:
the expired token and the foreign-pool token are each accepted and mint
tokens without the fix. Full Cognito suite: 336 tests, 0 failures on
JDK 25.

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
AbhigyaandPriamo authored and GitHub committed 2026-08-17 23:54:05 -04:00
1 parent 6962e91020
commit 7d8acede18
3 files changed
+82 -4

No files matched your search

@@ -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 tokens
service.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);
@@ -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;
}
@@ -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)
// =========================================================================