Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(cognito): implement token revocation for AdminUserGlobalSignOut (#1407)

Konda Balaji Raob377940cb6cb
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
index e5a1d7e453..3988022a7d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
@@ -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();
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java
index d3570d9f5f..343f316f10 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java
@@ -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:
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 e91da7ffd3..c796c65ab6 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,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<>();
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 ec91c1fdc2..07c28ba803 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
@@ -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");
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/RevokedTokenInfo.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/RevokedTokenInfo.java
new file mode 100644
index 0000000000..097673c6d6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/RevokedTokenInfo.java
@@ -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 +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
index 522571b8e4..757f0c9b4e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
@@ -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);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
index ee63729a10..0411f19b64 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java
@@ -35,7 +35,7 @@ class ApiGatewayProxyMatchTest {
void setUp() {
ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService,
new RegionResolver("us-east-1", "000000000000"),
- new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service);
+ new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null);
}
private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewaySqsPathIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewaySqsPathIntegrationTest.java
new file mode 100644
index 0000000000..aaa3be0bcf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewaySqsPathIntegrationTest.java
@@ -0,0 +1,178 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.*;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.*;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewaySqsPathIntegrationTest {
+
+ private static final ObjectMapper mapper = new ObjectMapper();
+ private static String apiId;
+ private static String rootId;
+ private static String sqsResourceId;
+ private static String deploymentId;
+ private static final String QUEUE_NAME = "apigw-sqs-proxy-test-queue";
+ private static final String ACCOUNT_ID = "000000000000";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test @Order(1)
+ void setup_createSqsQueue() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", QUEUE_NAME)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ @Test @Order(2)
+ void setup_createRestApi() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"aws-sqs-integration-test","description":"Test AWS SQS path integration"}
+ """)
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .extract().path("id");
+ assertNotNull(apiId);
+ }
+
+ @Test @Order(3)
+ void setup_getRootResource() {
+ rootId = given()
+ .when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200)
+ .extract().path("item[0].id");
+ assertNotNull(rootId);
+ }
+
+ @Test @Order(4)
+ void setup_createSqsResource() {
+ sqsResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"send\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+ }
+
+ @Test @Order(5)
+ void setup_configureSqsMethod() throws Exception {
+ // PUT method
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + sqsResourceId + "/methods/POST")
+ .then().statusCode(201);
+
+ // PUT integration
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:eu-west-1:sqs:path/" + ACCOUNT_ID + "/" + QUEUE_NAME);
+
+ var requestParameters = mapper.createObjectNode();
+ requestParameters.put("integration.request.header.Content-Type", "'application/x-www-form-urlencoded'");
+ integrationNode.set("requestParameters", requestParameters);
+
+ var reqTemplates = mapper.createObjectNode();
+ String vtl = "Action=SendMessage&QueueUrl=$util.urlEncode(\"http://localhost:4566/" + ACCOUNT_ID + "/" + QUEUE_NAME + "\")&MessageBody=$util.urlEncode($input.body)";
+ reqTemplates.put("application/json", vtl);
+ integrationNode.set("requestTemplates", reqTemplates);
+
+ String integrationBody = mapper.writeValueAsString(integrationNode);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(integrationBody)
+ .when().put("/restapis/" + apiId + "/resources/" + sqsResourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ // PUT integration response (200 default)
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + sqsResourceId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+ }
+
+ @Test @Order(6)
+ void setup_deployAndCreateStage() {
+ deploymentId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"test\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}")
+ .when().post("/restapis/" + apiId + "/stages")
+ .then().statusCode(201);
+ }
+
+ @Test @Order(10)
+ void pathStyleSqsIntegration_proxiesMessageToQueue() throws Exception {
+ String messageBody = "{\"hello\":\"world\"}";
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(messageBody)
+ .when().post("/execute-api/" + apiId + "/test/send")
+ .then()
+ .statusCode(200);
+
+ // Verify message is in queue
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", "http://localhost:4566/" + ACCOUNT_ID + "/" + QUEUE_NAME)
+ .formParam("MaxNumberOfMessages", "1")
+ .formParam("VisibilityTimeout", "10")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("&quot;hello&quot;:&quot;world&quot;")); // JSON quotes are XML-escaped
+ }
+
+ @Test @Order(11)
+ void pathStyleSqsIntegration_handlesAmpersandAndEqualsInBody() throws Exception {
+ String messageBody = "{\"query\":\"a=1&b=2\",\"note\":\"contains & and = chars\"}";
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(messageBody)
+ .when().post("/execute-api/" + apiId + "/test/send")
+ .then()
+ .statusCode(200);
+
+ // Verify message is in queue
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", "http://localhost:4566/" + ACCOUNT_ID + "/" + QUEUE_NAME)
+ .formParam("MaxNumberOfMessages", "1")
+ .formParam("VisibilityTimeout", "10")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("a=1&amp;b=2")); // JSON value XML-escaped
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
index a127992bc9..dcc0b36a1b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java
@@ -41,7 +41,7 @@ class BuildV2ProxyEventPathParametersTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, new ObjectMapper(), null,
- null, null, null
+ null, null, null, null
);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java
new file mode 100644
index 0000000000..b116b84803
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/AdminUserGlobalSignOutIntegrationTest.java
@@ -0,0 +1,222 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Integration tests for the AdminUserGlobalSignOut API.
+ *
+ * Reproduces issue #1395: previously issued tokens must be invalidated
+ * after calling AdminUserGlobalSignOut, matching AWS Cognito behavior.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class AdminUserGlobalSignOutIntegrationTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static String poolId;
+ private static String clientId;
+ private static String refreshToken;
+ private static String accessToken;
+
+ private static final String USERNAME = "alice";
+ private static final String PASSWORD = "Password123!";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ // ─── helpers ────────────────────────────────────────────────────────────
+
+ private static Response cognitoAction(String action, String body) {
+ return given()
+ .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action)
+ .contentType(CONTENT_TYPE)
+ .body(body)
+ .when()
+ .post("/");
+ }
+
+ private static JsonNode cognitoJson(String action, String body) throws Exception {
+ return MAPPER.readTree(
+ cognitoAction(action, body).then().statusCode(200).extract().asString());
+ }
+
+ /** POST without asserting 200 — lets tests inspect the error response. */
+ private static JsonNode cognitoJsonAny(String action, String body) throws Exception {
+ return MAPPER.readTree(cognitoAction(action, body).then().extract().asString());
+ }
+
+ // ─── setup ──────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ void setupPoolAndUser() throws Exception {
+ JsonNode pool = cognitoJson("CreateUserPool", """
+ {"PoolName":"SignOutTestPool"}
+ """);
+ poolId = pool.path("UserPool").path("Id").asText();
+ assertFalse(poolId.isBlank(), "Pool ID must not be blank");
+
+ JsonNode client = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "test-client",
+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]
+ }
+ """.formatted(poolId));
+ clientId = client.path("UserPoolClient").path("ClientId").asText();
+ assertFalse(clientId.isBlank(), "Client ID must not be blank");
+
+ cognitoAction("AdminCreateUser", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, USERNAME)).then().statusCode(200);
+
+ cognitoAction("AdminSetUserPassword", """
+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
+ """.formatted(poolId, USERNAME, PASSWORD)).then().statusCode(200);
+ }
+
+ @Test
+ @Order(2)
+ void authenticateAndCaptureTokens() throws Exception {
+ JsonNode auth = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "USER_PASSWORD_AUTH",
+ "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}
+ }
+ """.formatted(clientId, USERNAME, PASSWORD));
+
+ refreshToken = auth.path("AuthenticationResult").path("RefreshToken").asText();
+ accessToken = auth.path("AuthenticationResult").path("AccessToken").asText();
+
+ assertFalse(refreshToken.isBlank(), "RefreshToken must be present after sign-in");
+ assertFalse(accessToken.isBlank(), "AccessToken must be present after sign-in");
+ }
+
+ @Test
+ @Order(3)
+ void refreshTokenWorksBeforeSignOut() throws Exception {
+ // Verify refresh token is functional before global sign-out
+ JsonNode refreshed = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "REFRESH_TOKEN_AUTH",
+ "AuthParameters": {"REFRESH_TOKEN": "%s"}
+ }
+ """.formatted(clientId, refreshToken));
+
+ String newAccess = refreshed.path("AuthenticationResult").path("AccessToken").asText();
+ assertFalse(newAccess.isBlank(), "Refresh should succeed before global sign-out");
+ }
+
+ @Test
+ @Order(4)
+ void adminUserGlobalSignOutSucceeds() {
+ // AdminUserGlobalSignOut must return HTTP 200 with an empty body
+ cognitoAction("AdminUserGlobalSignOut", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, USERNAME))
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(5)
+ void refreshTokenIsRejectedAfterSignOut() throws Exception {
+ // Core bug reproduction: refresh token must be rejected after global sign-out
+ JsonNode body = cognitoJsonAny("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "REFRESH_TOKEN_AUTH",
+ "AuthParameters": {"REFRESH_TOKEN": "%s"}
+ }
+ """.formatted(clientId, refreshToken));
+
+ assertEquals("NotAuthorizedException", body.path("__type").asText(),
+ "Expected NotAuthorizedException after global sign-out, body was: " + body);
+ }
+
+ @Test
+ @Order(6)
+ void getTokensFromRefreshTokenIsRejectedAfterSignOut() throws Exception {
+ // GetTokensFromRefreshToken path must also honour revocation
+ JsonNode body = cognitoJsonAny("GetTokensFromRefreshToken", """
+ {"ClientId":"%s","RefreshToken":"%s"}
+ """.formatted(clientId, refreshToken));
+
+ assertEquals("NotAuthorizedException", body.path("__type").asText(),
+ "Expected NotAuthorizedException for GetTokensFromRefreshToken after sign-out");
+ }
+
+ @Test
+ @Order(7)
+ void newLoginSucceedsAfterSignOut() throws Exception {
+ // A fresh password-auth login must still succeed — sign-out does not lock the account
+ JsonNode auth = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "USER_PASSWORD_AUTH",
+ "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}
+ }
+ """.formatted(clientId, USERNAME, PASSWORD));
+
+ String newRefresh = auth.path("AuthenticationResult").path("RefreshToken").asText();
+ assertFalse(newRefresh.isBlank(), "Fresh login must succeed after global sign-out");
+ assertNotEquals(refreshToken, newRefresh, "New session must issue a new RefreshToken");
+
+ // Verify the new refresh token works
+ JsonNode refreshed = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "REFRESH_TOKEN_AUTH",
+ "AuthParameters": {"REFRESH_TOKEN": "%s"}
+ }
+ """.formatted(clientId, newRefresh));
+
+ String newAccess = refreshed.path("AuthenticationResult").path("AccessToken").asText();
+ assertFalse(newAccess.isBlank(), "Refresh should succeed for new tokens issued after global sign-out");
+ }
+
+ @Test
+ @Order(8)
+ void oldRefreshTokenStillRejectedAfterNewLogin() throws Exception {
+ // Even after a new login, the old revoked refresh token remains invalid
+ JsonNode body = cognitoJsonAny("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "REFRESH_TOKEN_AUTH",
+ "AuthParameters": {"REFRESH_TOKEN": "%s"}
+ }
+ """.formatted(clientId, refreshToken));
+
+ assertEquals("NotAuthorizedException", body.path("__type").asText(),
+ "Old revoked token must still be rejected after a new login");
+ }
+
+ @Test
+ @Order(9)
+ void adminUserGlobalSignOutFailsForUnknownUser() throws Exception {
+ // Calling sign-out for a non-existent user must return UserNotFoundException
+ JsonNode body = cognitoJsonAny("AdminUserGlobalSignOut", """
+ {"UserPoolId":"%s","Username":"ghost"}
+ """.formatted(poolId));
+
+ assertEquals("UserNotFoundException", body.path("__type").asText());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java
index eb4807c308..a13a792b69 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java
@@ -34,6 +34,7 @@ class CognitoJsonHandlerTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
+ new InMemoryStorage<>(), // revokedTokenStore
"http://localhost:4566",
regionResolver,
null
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java
index 782cbe593a..315d3526dd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java
@@ -52,6 +52,7 @@ class CognitoLambdaTriggersTest {
service = new CognitoService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), // revokedTokenStore
"http://localhost:4566", regionResolver, lambdaService);
}
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 18cf57412b..3efcdcf353 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
@@ -37,6 +37,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
groupStore,
+ new InMemoryStorage<>(), // revokedTokenStore
"http://localhost:4566",
regionResolver,
null
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
index e47f38ded7..75bfd2a5d4 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.Replay;
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 io.vertx.core.Vertx;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -48,7 +49,8 @@ class EventBridgeSchedulerIntegrationTest {
busStore, ruleStore, targetStore,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT),
- new ObjectMapper(), scheduler, invoker, replayDispatcher);
+ new ObjectMapper(), scheduler, invoker, replayDispatcher,
+ new ResourceGroupsTaggingService());
}
@AfterEach
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
index c057a9f3b0..e706c05560 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -42,7 +43,8 @@ class EventBridgeServiceTest {
new ObjectMapper(),
null,
invokerMock,
- null
+ null,
+ new ResourceGroupsTaggingService()
);
}