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:
Konda Balaji Rao authored and GitHub committed 2026-06-21 00:31:00 -05:00
1 parent 0bb6c6e76a
commit b377940cb6
15 files changed
+800 -23

No files matched your search

@@ -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) {
@@ -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(""hello":"world"")); // 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&b=2")); // JSON value XML-escaped
}
}
@@ -41,7 +41,7 @@ class BuildV2ProxyEventPathParametersTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null
null, null, null, null
);
}
@@ -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());
}
}
@@ -34,6 +34,7 @@ class CognitoJsonHandlerTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(), // revokedTokenStore
"http://localhost:4566",
regionResolver,
null
@@ -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);
}
@@ -37,6 +37,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
groupStore,
new InMemoryStorage<>(), // revokedTokenStore
"http://localhost:4566",
regionResolver,
null
@@ -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
@@ -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()
);
}