mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(cognito): implement token revocation for AdminUserGlobalSignOut (#1407)
* fix: return XML error for missing action and add volume action fallbacks * fix(eventbridge): sync EventBridge tags to ResourceGroupsTaggingService EventBridge stored tags on rules, buses, and archives in its own stores but never propagated them to the central ResourceGroupsTaggingService. This caused GetResources with --resource-type-filters events:rule to return an empty list. Inject ResourceGroupsTaggingService into EventBridgeService (following the existing GlueService pattern) and sync tags during putRule, tagResource, untagResource, and deleteRule operations. Closes #1343 * fix(apigateway): add support for SQS path-style integration URIs - Enhanced AwsServiceRouter to parse both action/ and path/ style integration URIs - Updated ApiGatewayExecuteController to handle form-urlencoded SQS requests - Added comprehensive integration tests covering end-to-end functionality - Maintains backward compatibility with existing action/ style integrations Fixes issue with API Gateway AWS integrations failing when using path-style SQS ARNs like arn:aws:apigateway:region:sqs:path/account/queue instead of action-style URIs. * fix(cognito): implement token revocation for AdminUserGlobalSignOut Previously AdminUserGlobalSignOut was a stub that only logged a message and did not invalidate any tokens, allowing previously issued refresh and access tokens to remain fully usable after a global sign-out. Changes: - Add RevokedTokenInfo model to track revoked token state - Add revokedTokenStore (StorageBackend) to CognitoService - Add jti and origin_jti claims to all generated JWT tokens - Implement revokeAllUserTokens() using a global revocation record keyed by pool + username, checked at every token validation point - Add validateRefreshTokenNotRevoked() accessible from the auth flow handler - Add validateUserNotGloballySignedOut() checked in getUser, changePassword, updateUserAttributes, deleteUserAttributes, and getTokensFromRefreshToken - Fix CognitoAuthFlowHandler.handleRefreshToken() to call the revocation check before issuing new tokens from REFRESH_TOKEN_AUTH flow - Update package-private constructor (used in tests) to accept the new store - Add AdminUserGlobalSignOutIntegrationTest covering the full sign-in → sign-out → token-reuse scenario (9 test cases) Closes #1395 * fix(cognito): only revoke tokens issued before global sign out instant * fix(cognito): correct time precision for global sign-out token invalidation
This commit is contained in:
1 parent
0bb6c6e76a
commit
b377940cb6
15 files changed
+800
-23
No files matched your search
+28
-3
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -72,6 +73,7 @@ public class ApiGatewayExecuteController {
|
||||
private final AwsServiceRouter serviceRouter;
|
||||
private final WebSocketConnectionManager webSocketConnectionManager;
|
||||
private final ElbV2Service elbV2Service;
|
||||
private final SqsQueryHandler sqsQueryHandler;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
|
||||
@@ -79,7 +81,8 @@ public class ApiGatewayExecuteController {
|
||||
ObjectMapper objectMapper, VtlTemplateEngine vtlEngine,
|
||||
AwsServiceRouter serviceRouter,
|
||||
WebSocketConnectionManager webSocketConnectionManager,
|
||||
ElbV2Service elbV2Service) {
|
||||
ElbV2Service elbV2Service,
|
||||
SqsQueryHandler sqsQueryHandler) {
|
||||
this.apiGatewayService = apiGatewayService;
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -89,6 +92,7 @@ public class ApiGatewayExecuteController {
|
||||
this.serviceRouter = serviceRouter;
|
||||
this.webSocketConnectionManager = webSocketConnectionManager;
|
||||
this.elbV2Service = elbV2Service;
|
||||
this.sqsQueryHandler = sqsQueryHandler;
|
||||
}
|
||||
|
||||
/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */
|
||||
@@ -782,6 +786,26 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
// ──────────────────────────── AWS (non-proxy) ────────────────────────────
|
||||
|
||||
private MultivaluedMap<String, String> parseFormEncodedBody(String body) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
if (body == null || body.isEmpty()) {
|
||||
return params;
|
||||
}
|
||||
String[] pairs = body.split("&");
|
||||
for (String pair : pairs) {
|
||||
int idx = pair.indexOf("=");
|
||||
if (idx > 0) {
|
||||
String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8);
|
||||
String value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8);
|
||||
params.add(key, value);
|
||||
} else if (idx == -1 && !pair.isEmpty()) {
|
||||
String key = URLDecoder.decode(pair, StandardCharsets.UTF_8);
|
||||
params.add(key, "");
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
private Response invokeAwsIntegration(String region, String httpMethod, String path, String proxy,
|
||||
String stageName, ApiGatewayResource resource,
|
||||
Integration integration, HttpHeaders headers,
|
||||
@@ -809,6 +833,9 @@ public class ApiGatewayExecuteController {
|
||||
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
|
||||
pathMap.putAll(extractPathParams(resource.getPath(), path));
|
||||
|
||||
String incomingContentType = headerMap.getOrDefault("Content-Type",
|
||||
headerMap.getOrDefault("content-type", "application/json"));
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null);
|
||||
@@ -817,8 +844,6 @@ public class ApiGatewayExecuteController {
|
||||
// before parameter mapping runs, since an integration.request.header.Content-Type
|
||||
// override (common for SQS query-protocol integrations) would otherwise clobber it and
|
||||
// misdirect template selection.
|
||||
String incomingContentType = headerMap.getOrDefault("Content-Type",
|
||||
headerMap.getOrDefault("content-type", "application/json"));
|
||||
|
||||
// Apply request parameter mapping (method.request.* → integration.request.*)
|
||||
Map<String, String> integrationReqParams = integration.getRequestParameters();
|
||||
|
||||
@@ -21,6 +21,8 @@ import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Routes API Gateway AWS integration requests to the correct internal service handler.
|
||||
@@ -80,10 +82,21 @@ public class AwsServiceRouter {
|
||||
this.acmHandler = acmHandler;
|
||||
}
|
||||
|
||||
private static final Pattern ACTION_URI_PATTERN = Pattern.compile(
|
||||
"^arn:aws:apigateway:([^:]+):([^:]+):action/(.+)$"
|
||||
);
|
||||
private static final Pattern PATH_URI_PATTERN = Pattern.compile(
|
||||
"^arn:aws:apigateway:([^:]+):([^:]+):path/(.+)$"
|
||||
);
|
||||
|
||||
/**
|
||||
* Parsed components of an API Gateway AWS integration URI.
|
||||
*/
|
||||
public record IntegrationTarget(String region, String service, String action) {}
|
||||
public record IntegrationTarget(String region, String service, String action, String path) {
|
||||
public IntegrationTarget(String region, String service, String action) {
|
||||
this(region, service, action, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an integration URI in either of the two forms AWS accepts:
|
||||
|
||||
+8
-2
@@ -234,13 +234,19 @@ final class CognitoAuthFlowHandler {
|
||||
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));
|
||||
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override));
|
||||
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<>();
|
||||
|
||||
@@ -60,6 +60,7 @@ public class CognitoService {
|
||||
private final StorageBackend<String, ResourceServer> resourceServerStore;
|
||||
private final StorageBackend<String, CognitoUser> userStore;
|
||||
private final StorageBackend<String, CognitoGroup> groupStore;
|
||||
private final StorageBackend<String, RevokedTokenInfo> revokedTokenStore;
|
||||
private final String baseUrl;
|
||||
private final RegionResolver regionResolver;
|
||||
private final LambdaService lambdaService;
|
||||
@@ -83,6 +84,8 @@ public class CognitoService {
|
||||
new TypeReference<Map<String, CognitoUser>>() {});
|
||||
this.groupStore = storageFactory.create("cognito", "cognito-groups.json",
|
||||
new TypeReference<Map<String, CognitoGroup>>() {});
|
||||
this.revokedTokenStore = storageFactory.create("cognito", "cognito-revoked-tokens.json",
|
||||
new TypeReference<Map<String, RevokedTokenInfo>>() {});
|
||||
this.baseUrl = trimTrailingSlash(emulatorConfig.baseUrl());
|
||||
this.regionResolver = regionResolver;
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -96,6 +99,7 @@ public class CognitoService {
|
||||
StorageBackend<String, ResourceServer> resourceServerStore,
|
||||
StorageBackend<String, CognitoUser> userStore,
|
||||
StorageBackend<String, CognitoGroup> groupStore,
|
||||
StorageBackend<String, RevokedTokenInfo> revokedTokenStore,
|
||||
String baseUrl,
|
||||
RegionResolver regionResolver,
|
||||
LambdaService lambdaService) {
|
||||
@@ -104,6 +108,7 @@ public class CognitoService {
|
||||
this.resourceServerStore = resourceServerStore;
|
||||
this.userStore = userStore;
|
||||
this.groupStore = groupStore;
|
||||
this.revokedTokenStore = revokedTokenStore;
|
||||
this.baseUrl = baseUrl;
|
||||
this.regionResolver = regionResolver;
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -788,8 +793,13 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
public void adminUserGlobalSignOut(String userPoolId, String username) {
|
||||
adminGetUser(userPoolId, username);
|
||||
LOG.infov("AdminUserGlobalSignOut stub: user {0} in pool {1} signed out globally", username, userPoolId);
|
||||
// Validate user exists
|
||||
CognitoUser user = adminGetUser(userPoolId, username);
|
||||
|
||||
// Revoke all tokens for this user
|
||||
revokeAllUserTokens(userPoolId, username);
|
||||
|
||||
LOG.infov("AdminUserGlobalSignOut: revoked all tokens for user {0} in pool {1}", username, userPoolId);
|
||||
}
|
||||
|
||||
public CognitoUser adminGetUser(String userPoolId, String username) {
|
||||
@@ -1143,9 +1153,16 @@ public class CognitoService {
|
||||
public void changePassword(String accessToken, String previousPassword, String proposedPassword) {
|
||||
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");
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
if (user.getPasswordHash() != null && !user.getPasswordHash().equals(hashPassword(previousPassword))) {
|
||||
@@ -1200,9 +1217,17 @@ public class CognitoService {
|
||||
public Map<String, Object> getUser(String accessToken) {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
if (username == null || poolId == null) {
|
||||
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");
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("Username", user.getUsername());
|
||||
@@ -1215,18 +1240,34 @@ public class CognitoService {
|
||||
public void updateUserAttributes(String accessToken, Map<String, String> attributes) {
|
||||
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");
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
adminUpdateUserAttributes(poolId, username, attributes);
|
||||
}
|
||||
|
||||
public void deleteUserAttributes(String accessToken, List<String> attributeNames) {
|
||||
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");
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
adminDeleteUserAttributes(poolId, username, attributeNames);
|
||||
}
|
||||
|
||||
@@ -1306,18 +1347,31 @@ public class CognitoService {
|
||||
}
|
||||
String poolId = parts[0];
|
||||
String username = parts[1];
|
||||
String refreshTokenUuid = parts[4]; // UUID from refresh token
|
||||
|
||||
if (!client.getUserPoolId().equals(poolId)) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400);
|
||||
}
|
||||
if (isRefreshTokenExpired(client, parts)) {
|
||||
throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400);
|
||||
}
|
||||
|
||||
// Check if refresh token has been revoked
|
||||
validateTokenNotRevoked(refreshTokenUuid, poolId, "refresh");
|
||||
long issuedAt = 0L;
|
||||
try {
|
||||
issuedAt = Long.parseLong(parts[3]);
|
||||
} catch (NumberFormatException ignored) {}
|
||||
validateUserNotGloballySignedOut(username, poolId, "refresh", issuedAt);
|
||||
|
||||
UserPool pool = describeUserPool(poolId);
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user);
|
||||
|
||||
// Use refresh token UUID as origin_jti for derived tokens
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override));
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override));
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
@@ -1326,9 +1380,13 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override) {
|
||||
return generateAuthResult(user, pool, client, override, null);
|
||||
}
|
||||
|
||||
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));
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override));
|
||||
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("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
@@ -1336,6 +1394,10 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override) {
|
||||
return generateSignedJwt(user, pool, type, client, override, null);
|
||||
}
|
||||
|
||||
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
String header = encodeJwtHeader(pool);
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type);
|
||||
@@ -1353,6 +1415,16 @@ public class CognitoService {
|
||||
claims.put("username", user.getUsername());
|
||||
claims.put("email", email);
|
||||
claims.put("cognito:username", user.getUsername());
|
||||
|
||||
// Add JWT ID (jti) claim for token revocation support
|
||||
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) {
|
||||
claims.put("origin_jti", originJti);
|
||||
}
|
||||
|
||||
String clientId = client != null ? client.getClientId() : null;
|
||||
if (clientId != null && !clientId.isBlank()) {
|
||||
if ("access".equals(type)) claims.put("client_id", clientId);
|
||||
@@ -1907,7 +1979,7 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
String buildRefreshToken(String poolId, String username, String clientId) {
|
||||
long issuedAt = System.currentTimeMillis() / 1000L;
|
||||
long issuedAt = System.currentTimeMillis();
|
||||
String raw = poolId + "|" + username + "|" + clientId + "|" + issuedAt + "|" + UUID.randomUUID();
|
||||
return Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
@@ -2005,6 +2077,163 @@ public class CognitoService {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract JWT ID (jti) claim from a JWT token.
|
||||
*/
|
||||
private String extractJtiFromToken(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, "jti");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractIatFromToken(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);
|
||||
String iatStr = extractJsonField(payloadJson, "iat");
|
||||
if (iatStr != null) {
|
||||
return Long.parseLong(iatStr);
|
||||
}
|
||||
// In case the simple extractor doesn't work for numbers (it extracts strings between quotes usually)
|
||||
// let's use MAPPER for this specific field
|
||||
Map<String, Object> payload = MAPPER.readValue(payloadJson, new TypeReference<>() {});
|
||||
Object iat = payload.get("iat");
|
||||
if (iat instanceof Number n) {
|
||||
return n.longValue();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a refresh token has not been revoked, including global user sign-out.
|
||||
* Called from CognitoAuthFlowHandler for the REFRESH_TOKEN_AUTH flow.
|
||||
*/
|
||||
void validateRefreshTokenNotRevoked(String jti, String poolId, String username, long iat) {
|
||||
validateTokenNotRevoked(jti, poolId, "refresh");
|
||||
validateUserNotGloballySignedOut(username, poolId, "refresh", iat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a token has not been revoked.
|
||||
* @param jti The JWT ID to check
|
||||
* @param poolId The user pool ID
|
||||
* @param tokenType The type of token (access, id, refresh)
|
||||
* @throws AwsException if the token has been revoked
|
||||
*/
|
||||
private void validateTokenNotRevoked(String jti, String poolId, String tokenType) {
|
||||
if (jti == null) {
|
||||
return; // Skip validation for tokens without jti (legacy tokens)
|
||||
}
|
||||
|
||||
// Check for specific token revocation
|
||||
String revokedKey = revokedTokenKey(poolId, jti);
|
||||
Optional<RevokedTokenInfo> revoked = revokedTokenStore.get(revokedKey);
|
||||
|
||||
if (revoked.isPresent()) {
|
||||
RevokedTokenInfo revokedInfo = revoked.get();
|
||||
|
||||
// Clean up expired revocation records
|
||||
if (revokedInfo.isExpired()) {
|
||||
revokedTokenStore.delete(revokedKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// Token has been revoked
|
||||
String errorMessage = switch (tokenType) {
|
||||
case "access" -> "Access Token has been revoked";
|
||||
case "id" -> "ID Token has been revoked";
|
||||
case "refresh" -> "Refresh Token has been revoked";
|
||||
default -> "Token has been revoked";
|
||||
};
|
||||
throw new AwsException("NotAuthorizedException", errorMessage, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user has been globally signed out (affects all their tokens).
|
||||
* This method should be called in addition to validateTokenNotRevoked.
|
||||
*/
|
||||
private void validateUserNotGloballySignedOut(String username, String poolId, String tokenType, long iat) {
|
||||
String globalRevokeKey = revokedTokenKey(poolId, "global:" + username);
|
||||
Optional<RevokedTokenInfo> globalRevoked = revokedTokenStore.get(globalRevokeKey);
|
||||
|
||||
if (globalRevoked.isPresent()) {
|
||||
RevokedTokenInfo globalInfo = globalRevoked.get();
|
||||
if (!globalInfo.isExpired()) {
|
||||
long revokedAtMs = globalInfo.getRevokedAt();
|
||||
boolean revoked = false;
|
||||
|
||||
if (iat > 1000000000000L) {
|
||||
// iat is in milliseconds (refresh token)
|
||||
revoked = iat <= revokedAtMs;
|
||||
} else if (iat > 0) {
|
||||
// iat is in seconds (access or id token)
|
||||
// If iat_seconds * 1000 <= revokedAt_ms, then the token was issued at or before the revocation second
|
||||
revoked = (iat * 1000L) <= revokedAtMs;
|
||||
}
|
||||
|
||||
if (revoked) {
|
||||
String errorMessage = switch (tokenType) {
|
||||
case "access" -> "Access Token has been revoked";
|
||||
case "id" -> "ID Token has been revoked";
|
||||
case "refresh" -> "Refresh Token has been revoked";
|
||||
default -> "Token has been revoked";
|
||||
};
|
||||
throw new AwsException("NotAuthorizedException", errorMessage, 400);
|
||||
}
|
||||
} else {
|
||||
revokedTokenStore.delete(globalRevokeKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke all tokens (refresh, access, ID) for a specific user.
|
||||
* This implements the core logic for AdminUserGlobalSignOut.
|
||||
*/
|
||||
private void revokeAllUserTokens(String userPoolId, String username) {
|
||||
long nowMs = System.currentTimeMillis();
|
||||
|
||||
// Note: In a real implementation, we would need to track all active tokens for a user.
|
||||
// Since Floci doesn't currently maintain a token registry, we implement a simpler
|
||||
// approach that marks the user as globally signed out with a future expiration.
|
||||
// This covers the most common use case where tokens are checked at validation time.
|
||||
|
||||
// Create a revocation record for the user with a future expiration
|
||||
// This will catch any existing tokens when they're next validated
|
||||
String globalRevokeKey = revokedTokenKey(userPoolId, "global:" + username);
|
||||
long globalExpiration = nowMs + (365L * 24L * 60L * 60L * 1000L); // 1 year from now in ms
|
||||
|
||||
RevokedTokenInfo globalRevocation = new RevokedTokenInfo(
|
||||
"global:" + username,
|
||||
"global",
|
||||
username,
|
||||
userPoolId,
|
||||
nowMs,
|
||||
globalExpiration
|
||||
);
|
||||
|
||||
revokedTokenStore.put(globalRevokeKey, globalRevocation);
|
||||
|
||||
LOG.debugv("Created global revocation record for user {0} in pool {1}", username, userPoolId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a storage key for revoked token information.
|
||||
*/
|
||||
private String revokedTokenKey(String poolId, String jti) {
|
||||
return "revoked:" + poolId + ":" + jti;
|
||||
}
|
||||
|
||||
private void ensureVerificationWiring() {
|
||||
if (verificationCodeService == null || messageDispatcher == null) {
|
||||
throw new IllegalStateException("Verification services are not configured");
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
/**
|
||||
* Information about a revoked token for tracking and validation purposes.
|
||||
* Used to implement AWS Cognito AdminUserGlobalSignOut token revocation behavior.
|
||||
*/
|
||||
public class RevokedTokenInfo {
|
||||
|
||||
private final String jti;
|
||||
private final String tokenType;
|
||||
private final String username;
|
||||
private final String userPoolId;
|
||||
private final long revokedAt;
|
||||
private final long expiresAt;
|
||||
|
||||
@JsonCreator
|
||||
public RevokedTokenInfo(
|
||||
@JsonProperty("jti") String jti,
|
||||
@JsonProperty("tokenType") String tokenType,
|
||||
@JsonProperty("username") String username,
|
||||
@JsonProperty("userPoolId") String userPoolId,
|
||||
@JsonProperty("revokedAt") long revokedAt,
|
||||
@JsonProperty("expiresAt") long expiresAt) {
|
||||
this.jti = jti;
|
||||
this.tokenType = tokenType;
|
||||
this.username = username;
|
||||
this.userPoolId = userPoolId;
|
||||
this.revokedAt = revokedAt;
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public String getJti() {
|
||||
return jti;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public String getUserPoolId() {
|
||||
return userPoolId;
|
||||
}
|
||||
|
||||
public long getRevokedAt() {
|
||||
return revokedAt;
|
||||
}
|
||||
|
||||
public long getExpiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this revocation record has expired and can be cleaned up.
|
||||
*/
|
||||
public boolean isExpired() {
|
||||
return System.currentTimeMillis() / 1000L > expiresAt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RevokedTokenInfo{" +
|
||||
"jti='" + jti + '\'' +
|
||||
", tokenType='" + tokenType + '\'' +
|
||||
", username='" + username + '\'' +
|
||||
", userPoolId='" + userPoolId + '\'' +
|
||||
", revokedAt=" + revokedAt +
|
||||
", expiresAt=" + expiresAt +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+25
-5
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.ReplayState;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -48,6 +49,7 @@ public class EventBridgeService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RuleScheduler ruleScheduler;
|
||||
private final EventBridgeInvoker invoker;
|
||||
private final ResourceGroupsTaggingService resourceGroupsTaggingService;
|
||||
private final ReplayDispatcher replayDispatcher;
|
||||
|
||||
@Inject
|
||||
@@ -57,7 +59,8 @@ public class EventBridgeService {
|
||||
ObjectMapper objectMapper,
|
||||
RuleScheduler ruleScheduler,
|
||||
EventBridgeInvoker invoker,
|
||||
ReplayDispatcher replayDispatcher) {
|
||||
ReplayDispatcher replayDispatcher,
|
||||
ResourceGroupsTaggingService resourceGroupsTaggingService) {
|
||||
this(
|
||||
storageFactory.create("eventbridge", "eventbridge-buses.json",
|
||||
new TypeReference<Map<String, EventBus>>() {}),
|
||||
@@ -71,7 +74,8 @@ public class EventBridgeService {
|
||||
new TypeReference<Map<String, List<ArchivedEvent>>>() {}),
|
||||
storageFactory.create("eventbridge", "eventbridge-replays.json",
|
||||
new TypeReference<Map<String, Replay>>() {}),
|
||||
regionResolver, objectMapper, ruleScheduler, invoker, replayDispatcher
|
||||
regionResolver, objectMapper, ruleScheduler, invoker, replayDispatcher,
|
||||
resourceGroupsTaggingService
|
||||
);
|
||||
}
|
||||
|
||||
@@ -85,7 +89,8 @@ public class EventBridgeService {
|
||||
ObjectMapper objectMapper,
|
||||
RuleScheduler ruleScheduler,
|
||||
EventBridgeInvoker invoker,
|
||||
ReplayDispatcher replayDispatcher) {
|
||||
ReplayDispatcher replayDispatcher,
|
||||
ResourceGroupsTaggingService resourceGroupsTaggingService) {
|
||||
this.busStore = busStore;
|
||||
this.ruleStore = ruleStore;
|
||||
this.targetStore = targetStore;
|
||||
@@ -97,6 +102,7 @@ public class EventBridgeService {
|
||||
this.ruleScheduler = ruleScheduler;
|
||||
this.invoker = invoker;
|
||||
this.replayDispatcher = replayDispatcher;
|
||||
this.resourceGroupsTaggingService = resourceGroupsTaggingService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -144,6 +150,7 @@ public class EventBridgeService {
|
||||
);
|
||||
if (tags != null) {
|
||||
bus.getTags().putAll(tags);
|
||||
resourceGroupsTaggingService.tagResources(List.of(bus.getArn()), tags, region);
|
||||
}
|
||||
busStore.put(key, bus);
|
||||
LOG.infov("Created event bus: {0} in region {1}", name, region);
|
||||
@@ -160,7 +167,7 @@ public class EventBridgeService {
|
||||
throw new AwsException("ValidationException", "Cannot delete the default event bus.", 400);
|
||||
}
|
||||
String key = busKey(region, effectiveName);
|
||||
busStore.get(key)
|
||||
EventBus bus = busStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"EventBus not found: " + effectiveName, 404));
|
||||
String rulePrefix = ruleKeyPrefix(region, effectiveName);
|
||||
@@ -170,6 +177,7 @@ public class EventBridgeService {
|
||||
"Cannot delete event bus with existing rules: " + name, 400);
|
||||
}
|
||||
busStore.delete(key);
|
||||
resourceGroupsTaggingService.deleteResources(List.of(bus.getArn()), region);
|
||||
LOG.infov("Deleted event bus: {0}", name);
|
||||
}
|
||||
|
||||
@@ -269,6 +277,10 @@ public class EventBridgeService {
|
||||
}
|
||||
ruleStore.put(key, rule);
|
||||
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
resourceGroupsTaggingService.tagResources(List.of(rule.getArn()), tags, region);
|
||||
}
|
||||
|
||||
if (ruleScheduler != null) {
|
||||
ruleScheduler.stopScheduler(rule.getArn());
|
||||
startSchedulerIfNeeded(rule);
|
||||
@@ -295,6 +307,7 @@ public class EventBridgeService {
|
||||
}
|
||||
|
||||
ruleStore.delete(key);
|
||||
resourceGroupsTaggingService.deleteResources(List.of(rule.getArn()), region);
|
||||
LOG.infov("Deleted rule: {0}", name);
|
||||
}
|
||||
|
||||
@@ -437,6 +450,7 @@ public class EventBridgeService {
|
||||
"Archive not found: " + archiveName, 404));
|
||||
archive.getTags().putAll(tags);
|
||||
archiveStore.put(key, archive);
|
||||
resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region);
|
||||
return;
|
||||
}
|
||||
if (resource.startsWith("event-bus/")) {
|
||||
@@ -447,6 +461,7 @@ public class EventBridgeService {
|
||||
"Resource not found: " + resourceArn, 404));
|
||||
bus.getTags().putAll(tags);
|
||||
busStore.put(key, bus);
|
||||
resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region);
|
||||
return;
|
||||
}
|
||||
if (resource.startsWith("rule/")) {
|
||||
@@ -457,6 +472,7 @@ public class EventBridgeService {
|
||||
"Resource not found: " + resourceArn, 404));
|
||||
rule.getTags().putAll(tags);
|
||||
ruleStore.put(key, rule);
|
||||
resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region);
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 404);
|
||||
@@ -472,6 +488,7 @@ public class EventBridgeService {
|
||||
"Archive not found: " + archiveName, 404));
|
||||
tagKeys.forEach(archive.getTags()::remove);
|
||||
archiveStore.put(key, archive);
|
||||
resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region);
|
||||
return;
|
||||
}
|
||||
if (resource.startsWith("event-bus/")) {
|
||||
@@ -482,6 +499,7 @@ public class EventBridgeService {
|
||||
"Resource not found: " + resourceArn, 404));
|
||||
tagKeys.forEach(bus.getTags()::remove);
|
||||
busStore.put(key, bus);
|
||||
resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region);
|
||||
return;
|
||||
}
|
||||
if (resource.startsWith("rule/")) {
|
||||
@@ -492,6 +510,7 @@ public class EventBridgeService {
|
||||
"Resource not found: " + resourceArn, 404));
|
||||
tagKeys.forEach(rule.getTags()::remove);
|
||||
ruleStore.put(key, rule);
|
||||
resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region);
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 404);
|
||||
@@ -1075,11 +1094,12 @@ public class EventBridgeService {
|
||||
|
||||
public void deleteArchive(String archiveName, String region) {
|
||||
String key = archiveKey(region, archiveName);
|
||||
archiveStore.get(key)
|
||||
Archive archive = archiveStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Archive not found: " + archiveName, 404));
|
||||
archiveStore.delete(key);
|
||||
archivedEventStore.delete(archivedEventKey(region, archiveName));
|
||||
resourceGroupsTaggingService.deleteResources(List.of(archive.getArchiveArn()), region);
|
||||
LOG.infov("Deleted archive: {0}", archiveName);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user