mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat: emit jti/origin_jti and support RevokeToken (#1705)
* feat: emit jti/origin_jti and support RevokeToken * fix(cognito): authenticate RevokeToken caller before revocation-config check Address PR review feedback on the jti/origin_jti + RevokeToken change: - RevokeToken now validates the client secret before the EnableTokenRevocation check, so a confidential client with revocation disabled returns NotAuthorizedException (not UnsupportedOperationException) for a wrong/missing secret, matching AWS's identity-first ordering and avoiding leaking revocation state to unauthenticated callers. - OriginJtiIntegrationTest guards the shared ordered-test state via requireSetup()/requireInitialAuthState() so a setup or initial-auth failure reports a clear cause instead of misleading downstream assertions, and adds a regression test for the auth-ordering fix. * fix(cognito): revoke access tokens by origin_jti and use UnauthorizedException Address review feedback on PR #1705: - Check origin_jti (not just jti) when validating access tokens against the revocation store, so RevokeToken actually kills issued access tokens for GetUser, ChangePassword, UpdateUserAttributes and DeleteUserAttributes. - Change RevokeToken error from NotAuthorizedException to UnauthorizedException to match the declared API model. - Remove unused three-arg buildRefreshToken overload. - Add Order(12) test proving GetUser fails after RevokeToken.
This commit is contained in:
1 parent
001e530aca
commit
28252763f5
3 files changed
+464
-18
No files matched your search
@@ -92,6 +92,7 @@ public class CognitoJsonHandler {
|
||||
case "AdminRemoveUserFromGroup" -> handleAdminRemoveUserFromGroup(request);
|
||||
case "AdminListGroupsForUser" -> handleAdminListGroupsForUser(request);
|
||||
case "GetTokensFromRefreshToken" -> handleGetTokensFromRefreshToken(request);
|
||||
case "RevokeToken" -> handleRevokeToken(request);
|
||||
case "ListUserPoolClientSecrets" -> handleListUserPoolClientSecrets(request);
|
||||
case "AddUserPoolClientSecret" -> handleAddUserPoolClientSecret(request);
|
||||
case "DeleteUserPoolClientSecret" -> handleDeleteUserPoolClientSecret(request);
|
||||
@@ -451,6 +452,15 @@ public class CognitoJsonHandler {
|
||||
return Response.ok(objectMapper.valueToTree(result)).build();
|
||||
}
|
||||
|
||||
private Response handleRevokeToken(JsonNode request) {
|
||||
service.revokeToken(
|
||||
request.path("ClientId").asText(null),
|
||||
request.path("Token").asText(null),
|
||||
request.path("ClientSecret").asText(null)
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleInitiateAuth(JsonNode request) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
request.path("AuthParameters").fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().asText()));
|
||||
|
||||
@@ -1309,13 +1309,13 @@ public class CognitoService {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
String jti = extractJtiFromToken(accessToken);
|
||||
|
||||
|
||||
if (username == null || poolId == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
|
||||
// Check if access token has been revoked
|
||||
|
||||
validateTokenNotRevoked(jti, poolId, "access");
|
||||
validateOriginJtiNotRevoked(accessToken, poolId);
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
@@ -1373,13 +1373,13 @@ public class CognitoService {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
String jti = extractJtiFromToken(accessToken);
|
||||
|
||||
|
||||
if (username == null || poolId == null || jti == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
|
||||
// Check if access token has been revoked
|
||||
|
||||
validateTokenNotRevoked(jti, poolId, "access");
|
||||
validateOriginJtiNotRevoked(accessToken, poolId);
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
@@ -1396,13 +1396,13 @@ public class CognitoService {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
String jti = extractJtiFromToken(accessToken);
|
||||
|
||||
|
||||
if (username == null || poolId == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
|
||||
// Check if access token has been revoked
|
||||
|
||||
validateTokenNotRevoked(jti, poolId, "access");
|
||||
validateOriginJtiNotRevoked(accessToken, poolId);
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
@@ -1413,13 +1413,13 @@ public class CognitoService {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
String jti = extractJtiFromToken(accessToken);
|
||||
|
||||
|
||||
if (username == null || poolId == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
|
||||
// Check if access token has been revoked
|
||||
|
||||
validateTokenNotRevoked(jti, poolId, "access");
|
||||
validateOriginJtiNotRevoked(accessToken, poolId);
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
@@ -1516,15 +1516,63 @@ public class CognitoService {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void revokeToken(String clientId, String token, String clientSecret) {
|
||||
if (token == null || token.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "Token is required", 400);
|
||||
}
|
||||
if (clientId == null || clientId.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "ClientId is required", 400);
|
||||
}
|
||||
|
||||
UserPoolClient client = findClientById(clientId);
|
||||
|
||||
// Authenticate the caller before disclosing configuration state: a confidential client must
|
||||
// present a valid secret first, matching AWS which validates identity ahead of feature checks.
|
||||
String secret = client.getClientSecret();
|
||||
if (secret != null && !secret.isBlank() && !secret.equals(clientSecret)) {
|
||||
throw new AwsException("UnauthorizedException", "Invalid client secret", 403);
|
||||
}
|
||||
|
||||
if (!isTokenRevocationEnabled(client)) {
|
||||
throw new AwsException("UnsupportedOperationException",
|
||||
"Please enable token revocation before revoking tokens for this client", 400);
|
||||
}
|
||||
|
||||
String[] parts = parseRefreshToken(token);
|
||||
if (parts == null) {
|
||||
throw new AwsException("UnsupportedTokenTypeException",
|
||||
"Only refresh tokens can be revoked", 400);
|
||||
}
|
||||
|
||||
String poolId = parts[0];
|
||||
String username = parts[1];
|
||||
String tokenClientId = parts[2];
|
||||
String familyId = parts.length > 4 && !parts[4].isEmpty() ? parts[4] : null;
|
||||
|
||||
if (!clientId.equals(tokenClientId)) {
|
||||
throw new AwsException("UnauthorizedException", "Refresh token was not issued to this client", 403);
|
||||
}
|
||||
if (familyId == null) {
|
||||
return; // Nothing keyed to revoke (legacy token); revocation is idempotent.
|
||||
}
|
||||
|
||||
long nowMs = System.currentTimeMillis();
|
||||
long expiresAtSeconds = nowMs / 1000L + (365L * 24L * 60L * 60L);
|
||||
RevokedTokenInfo info = new RevokedTokenInfo(familyId, "refresh", username, poolId, nowMs, expiresAtSeconds);
|
||||
revokedTokenStore.put(revokedTokenKey(poolId, familyId), info);
|
||||
LOG.infov("RevokeToken: revoked refresh token family {0} for user {1} in pool {2}", familyId, username, poolId);
|
||||
}
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override) {
|
||||
return generateAuthResult(user, pool, client, override, null);
|
||||
String originJti = UUID.randomUUID().toString();
|
||||
return generateAuthResult(user, pool, client, override, originJti);
|
||||
}
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
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()));
|
||||
auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), client.getClientId(), originJti));
|
||||
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
return auth;
|
||||
@@ -1557,8 +1605,7 @@ public class CognitoService {
|
||||
String jti = UUID.randomUUID().toString();
|
||||
claims.put("jti", jti);
|
||||
|
||||
// Add origin_jti for access and ID tokens derived from refresh tokens
|
||||
if (("access".equals(type) || "id".equals(type)) && originJti != null) {
|
||||
if (("access".equals(type) || "id".equals(type)) && originJti != null && isTokenRevocationEnabled(client)) {
|
||||
claims.put("origin_jti", originJti);
|
||||
}
|
||||
|
||||
@@ -2115,12 +2162,18 @@ public class CognitoService {
|
||||
}
|
||||
}
|
||||
|
||||
String buildRefreshToken(String poolId, String username, String clientId) {
|
||||
String buildRefreshToken(String poolId, String username, String clientId, String originJti) {
|
||||
long issuedAt = System.currentTimeMillis();
|
||||
String raw = poolId + "|" + username + "|" + clientId + "|" + issuedAt + "|" + UUID.randomUUID();
|
||||
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));
|
||||
}
|
||||
|
||||
private boolean isTokenRevocationEnabled(UserPoolClient client) {
|
||||
return client == null || client.getEnableTokenRevocation() == null
|
||||
|| Boolean.TRUE.equals(client.getEnableTokenRevocation());
|
||||
}
|
||||
|
||||
String[] parseRefreshToken(String refreshToken) {
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(refreshToken);
|
||||
@@ -2228,6 +2281,17 @@ public class CognitoService {
|
||||
}
|
||||
}
|
||||
|
||||
private String extractOriginJtiFromToken(String token) {
|
||||
try {
|
||||
String[] parts = token.split("\\.");
|
||||
if (parts.length < 2) return null;
|
||||
String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
return extractJsonField(payloadJson, "origin_jti");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractIatFromToken(String token) {
|
||||
try {
|
||||
String[] parts = token.split("\\.");
|
||||
@@ -2295,6 +2359,13 @@ public class CognitoService {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateOriginJtiNotRevoked(String accessToken, String poolId) {
|
||||
String originJti = extractOriginJtiFromToken(accessToken);
|
||||
if (originJti != null) {
|
||||
validateTokenNotRevoked(originJti, poolId, "access");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user has been globally signed out (affects all their tokens).
|
||||
* This method should be called in addition to validateTokenNotRevoked.
|
||||
|
||||
Reference in new issue
Block a user