Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(cognito): HMAC-sign refresh tokens to prevent forgery (#2139)

Priamo Germosenc4f4181c3d75
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 7d4c5fa748..ee2e413281 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
@@ -231,32 +231,27 @@ final class CognitoAuthFlowHandler {
String refreshToken = params.get("REFRESH_TOKEN");
if (refreshToken == null) throw new AwsException("InvalidParameterException", "REFRESH_TOKEN is required", 400);
String[] parts = service.parseRefreshToken(refreshToken);
- if (parts != null) {
- String username = parts[1];
- String tokenClientId = parts[2];
- long iat = parts.length > 3 && !parts[3].isEmpty() ? Long.parseLong(parts[3]) : 0L;
- String refreshTokenUuid = parts.length > 4 ? parts[4] : null;
-
- // Check revocation before issuing new tokens
- service.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);
-
- try {
- CognitoUser user = service.adminGetUser(pool.getId(), username);
- CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
- clientMetadata, "TokenGeneration_RefreshTokens");
- Map<String, Object> auth = new HashMap<>();
- auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
- auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
- auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
- auth.put("TokenType", "Bearer");
- Map<String, Object> result = new HashMap<>();
- result.put("AuthenticationResult", auth);
- return result;
- } catch (AwsException ignored) { }
+ if (parts == null) {
+ throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);
+ }
+ String username = parts[1];
+ long iat;
+ try {
+ iat = parts.length > 3 && !parts[3].isEmpty() ? Long.parseLong(parts[3]) : 0L;
+ } catch (NumberFormatException e) {
+ throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);
}
+ String refreshTokenUuid = parts.length > 4 ? parts[4] : null;
+
+ // Check revocation before issuing new tokens
+ service.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);
+
+ CognitoUser user = service.adminGetUser(pool.getId(), username);
+ CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
+ clientMetadata, "TokenGeneration_RefreshTokens");
Map<String, Object> auth = new HashMap<>();
- auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client));
- auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client));
+ auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
+ auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
auth.put("TokenType", "Bearer");
Map<String, Object> result = new HashMap<>();
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.java
index 3f80a5b346..147f81eabe 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
@@ -25,6 +25,8 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import org.jspecify.annotations.Nullable;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
@@ -166,6 +168,7 @@ public class CognitoService {
populateUserPool(pool, request);
ensureJwtSigningKeys(pool);
+ ensureRefreshTokenSecret(pool);
poolStore.put(id, pool);
LOG.infov("Created User Pool: {0}", id);
return pool;
@@ -271,7 +274,9 @@ public class CognitoService {
public UserPool describeUserPool(String id) {
UserPool pool = poolStore.get(id)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404));
- if (ensureJwtSigningKeys(pool)) {
+ boolean generatedKeys = ensureJwtSigningKeys(pool);
+ boolean generatedSecret = ensureRefreshTokenSecret(pool);
+ if (generatedKeys || generatedSecret) {
poolStore.put(id, pool);
}
return pool;
@@ -1703,7 +1708,7 @@ public class CognitoService {
Map<String, Object> auth = new HashMap<>();
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti));
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti));
- auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), client.getClientId(), originJti));
+ auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), originJti));
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
auth.put("TokenType", "Bearer");
return auth;
@@ -2192,6 +2197,32 @@ public class CognitoService {
}
}
+ private boolean ensureRefreshTokenSecret(UserPool pool) {
+ synchronized (pool) {
+ if (pool.getSigningSecret() != null && !pool.getSigningSecret().isBlank()) {
+ return false;
+ }
+ byte[] secretBytes = new byte[32];
+ new SecureRandom().nextBytes(secretBytes);
+ pool.setSigningSecret(Base64.getEncoder().encodeToString(secretBytes));
+ if (pool.getId() != null) {
+ pool.setLastModifiedDate(System.currentTimeMillis() / 1000L);
+ }
+ return true;
+ }
+ }
+
+ static String hmacSha256(byte[] key, String data) {
+ try {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(key, "HmacSHA256"));
+ return Base64.getEncoder().withoutPadding()
+ .encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to compute refresh token HMAC", e);
+ }
+ }
+
String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
@@ -2293,11 +2324,20 @@ public class CognitoService {
}
}
- String buildRefreshToken(String poolId, String username, String clientId, String originJti) {
+ String buildRefreshToken(UserPool pool, String username, String clientId, String originJti) {
+ if (ensureRefreshTokenSecret(pool)) {
+ poolStore.put(pool.getId(), pool);
+ }
long issuedAt = System.currentTimeMillis();
String familyId = originJti != null ? originJti : UUID.randomUUID().toString();
- String raw = poolId + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId;
- return Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ String raw = pool.getId() + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId;
+ String signature = hmacSha256(refreshTokenSecretBytes(pool), raw);
+ return Base64.getEncoder().withoutPadding()
+ .encodeToString((raw + "|" + signature).getBytes(StandardCharsets.UTF_8));
+ }
+
+ static byte[] refreshTokenSecretBytes(UserPool pool) {
+ return Base64.getDecoder().decode(pool.getSigningSecret());
}
private boolean isTokenRevocationEnabled(UserPoolClient client) {
@@ -2309,13 +2349,21 @@ public class CognitoService {
try {
byte[] decoded = Base64.getDecoder().decode(refreshToken);
String raw = new String(decoded, StandardCharsets.UTF_8);
- String[] parts = raw.split("\\|", 5);
- if (parts.length == 5) {
- return parts; // [poolId, username, clientId, issuedAt, nonce]
+ String[] parts = raw.split("\\|", 6);
+ if (parts.length != 6) {
+ return null;
+ }
+ UserPool pool = poolStore.get(parts[0]).orElse(null);
+ if (pool == null || pool.getSigningSecret() == null || pool.getSigningSecret().isBlank()) {
+ return null;
}
- if (parts.length == 4) {
- return new String[] { parts[0], parts[1], parts[2], "", parts[3] };
+ String payload = String.join("|", Arrays.copyOf(parts, 5));
+ byte[] expectedSignature = Base64.getDecoder().decode(hmacSha256(refreshTokenSecretBytes(pool), payload));
+ byte[] actualSignature = Base64.getDecoder().decode(parts[5]);
+ if (!MessageDigest.isEqual(expectedSignature, actualSignature)) {
+ return null;
}
+ return Arrays.copyOf(parts, 5); // [poolId, username, clientId, issuedAt, nonce]
} catch (Exception ignored) { }
return null;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
index a142101551..5c3316084d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
@@ -53,7 +53,6 @@ public class UserPool {
long now = System.currentTimeMillis() / 1000L;
this.creationDate = now;
this.lastModifiedDate = now;
- this.signingSecret = java.util.UUID.randomUUID().toString().replace("-", "");
}
public String getId() { return id; }
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.java
index 0b2935513e..125a626c43 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
@@ -1739,6 +1739,13 @@ class CognitoServiceTest {
assertTrue(result.isEmpty());
}
+ /** Signs a hand-crafted {@code poolId|username|clientId|issuedAt|nonce} payload the same way buildRefreshToken does. */
+ private static String signRawRefreshToken(UserPool pool, String raw) {
+ String signature = CognitoService.hmacSha256(CognitoService.refreshTokenSecretBytes(pool), raw);
+ return Base64.getEncoder().withoutPadding()
+ .encodeToString((raw + "|" + signature).getBytes(StandardCharsets.UTF_8));
+ }
+
// =========================================================================
// Issue #234 — GetTokensFromRefreshToken
// =========================================================================
@@ -1756,14 +1763,15 @@ class CognitoServiceTest {
String refreshToken = (String) auth.get("RefreshToken");
assertNotNull(refreshToken);
- // Should be parseable as base64 structured token
+ // Should be parseable as base64 structured token: 5 payload fields + trailing HMAC signature
String decoded = new String(Base64.getDecoder().decode(refreshToken), StandardCharsets.UTF_8);
- String[] parts = decoded.split("\\|", 5);
- assertEquals(5, parts.length, "Refresh token should encode 5 pipe-separated fields");
+ String[] parts = decoded.split("\\|", 6);
+ assertEquals(6, parts.length, "Refresh token should encode 5 pipe-separated fields plus a signature");
assertEquals(pool.getId(), parts[0]);
assertEquals("alice", parts[1]);
assertEquals(client.getClientId(), parts[2]);
assertFalse(parts[3].isBlank(), "Refresh token should encode its issued-at timestamp");
+ assertFalse(parts[5].isBlank(), "Refresh token should encode a signature");
}
@Test
@@ -1827,7 +1835,7 @@ class CognitoServiceTest {
long issuedAt = (System.currentTimeMillis() / 1000L) - 5;
String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAt + "|" + java.util.UUID.randomUUID();
- String expiredRefreshToken = Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ String expiredRefreshToken = signRawRefreshToken(pool, raw);
AwsException exception = assertThrows(AwsException.class, () ->
service.getTokensFromRefreshToken(client.getClientId(), expiredRefreshToken));
@@ -1854,6 +1862,99 @@ class CognitoServiceTest {
assertNotNull(refreshed.get("IdToken"));
}
+ // =========================================================================
+ // Issue #2137 — Refresh tokens must be unforgeable (HMAC-signed)
+ // =========================================================================
+
+ @Test
+ void getTokensFromRefreshTokenRejectsUnsignedForgedToken() {
+ UserPool pool = createPoolAndUser();
+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
+
+ // Attacker who knows the pool id, client id, and a valid username, but not the pool's secret.
+ String raw = pool.getId() + "|alice|" + client.getClientId() + "|"
+ + System.currentTimeMillis() + "|" + java.util.UUID.randomUUID();
+ String forgedToken = Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.getTokensFromRefreshToken(client.getClientId(), forgedToken));
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void getTokensFromRefreshTokenRejectsTamperedUsername() {
+ UserPool pool = createPoolAndUser();
+ service.adminCreateUser(pool.getId(), "mallory", Map.of("email", "[email protected]"), "TempPass1!");
+ service.adminSetUserPassword(pool.getId(), "mallory", "Perm1234!", true);
+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
+
+ Map<String, Object> authResult = service.initiateAuth(
+ client.getClientId(), "USER_PASSWORD_AUTH",
+ Map.of("USERNAME", "mallory", "PASSWORD", "Perm1234!"));
+ String refreshToken = (String) ((Map<String, Object>) authResult.get("AuthenticationResult")).get("RefreshToken");
+
+ // Swap the username in the decoded payload post-signing; the HMAC no longer matches.
+ String decoded = new String(Base64.getDecoder().decode(refreshToken), StandardCharsets.UTF_8);
+ String tampered = decoded.replaceFirst("\\|mallory\\|", "|alice|");
+ String tamperedToken = Base64.getEncoder().withoutPadding().encodeToString(tampered.getBytes(StandardCharsets.UTF_8));
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.getTokensFromRefreshToken(client.getClientId(), tamperedToken));
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void getTokensFromRefreshTokenRejectsSwappedPoolId() {
+ UserPool poolA = createPoolAndUser();
+ UserPool poolB = service.createUserPool(Map.of("PoolName", "OtherPool"), "us-east-1");
+ UserPoolClient client = service.createUserPoolClient(poolA.getId(), "c", false, false, List.of(), List.of());
+
+ Map<String, Object> authResult = service.initiateAuth(
+ client.getClientId(), "USER_PASSWORD_AUTH",
+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
+ String refreshToken = (String) ((Map<String, Object>) authResult.get("AuthenticationResult")).get("RefreshToken");
+
+ // Swap the embedded pool id for a different real pool; the signature was computed over poolA's id.
+ String decoded = new String(Base64.getDecoder().decode(refreshToken), StandardCharsets.UTF_8);
+ String tampered = decoded.replaceFirst("^" + poolA.getId() + "\\|", poolB.getId() + "|");
+ String tamperedToken = Base64.getEncoder().withoutPadding().encodeToString(tampered.getBytes(StandardCharsets.UTF_8));
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.getTokensFromRefreshToken(client.getClientId(), tamperedToken));
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ }
+
+ @Test
+ void refreshTokenAuthRejectsForgedTokenInsteadOfIssuingUnknownUserTokens() {
+ UserPool pool = createPoolAndUser();
+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
+
+ // A garbage/forged REFRESH_TOKEN must not fall through to minting real, signed
+ // tokens for a hardcoded "unknown" user via InitiateAuth REFRESH_TOKEN_AUTH.
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",
+ Map.of("REFRESH_TOKEN", "not-a-valid-refresh-token")));
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ }
+
+ @Test
+ void refreshTokenAuthRejectsNonNumericIssuedAt() {
+ UserPool pool = createPoolAndUser();
+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
+
+ // Validly signed, but with a non-numeric issued-at field, must not throw an
+ // uncaught NumberFormatException — it should be rejected as an invalid token.
+ String raw = pool.getId() + "|alice|" + client.getClientId() + "|not-a-number|" + java.util.UUID.randomUUID();
+ String malformedToken = signRawRefreshToken(pool, raw);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.initiateAuth(client.getClientId(), "REFRESH_TOKEN_AUTH",
+ Map.of("REFRESH_TOKEN", malformedToken)));
+ assertEquals("NotAuthorizedException", exception.getErrorCode());
+ }
+
// =========================================================================
// deleteUserPool cascades groups
// =========================================================================