feat(cognito): implement DeleteUser self-service API action (#4493)

This commit is contained in:
iam-ssrivastav authored and GitHub committed 2026-10-04 20:09:58 -04:00
1 parent 6a3bc12769
commit 8ea033d9fd
8 files changed
+414 -8

No files matched your search

@@ -102,6 +102,38 @@ class ApiGatewayCognitoAuthorizerIntegrationTest {
}
}
@Test
void rejectsTokensOfDeletedUser() throws Exception {
UserPool pool = cognitoService.createUserPool(Map.of("PoolName", "deleted-user-pool"), "us-east-1");
Map<String, Object> tokens = issueTokens(pool);
String accessToken = (String) tokens.get("AccessToken");
String idToken = (String) tokens.get("IdToken");
String apiId = given().contentType(ContentType.JSON)
.body(Map.of("name", "cognito-deleted-user-test"))
.post("/restapis").then().statusCode(201).extract().path("id");
try {
String rootId = given().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String securedId = createResource(apiId, rootId, "secured");
String authorizerId = createAuthorizer(apiId, "Guard", pool.getArn());
configureMethod(apiId, securedId, authorizerId, "COGNITO_USER_POOLS", List.of());
given().contentType(ContentType.JSON).body(Map.of("stageName", "test"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
String securedPath = "/execute-api/" + apiId + "/test/secured";
given().header("X-Id-Token", "Bearer " + accessToken)
.get(securedPath).then().statusCode(200);
cognitoService.deleteUser(accessToken);
given().header("X-Id-Token", "Bearer " + accessToken)
.get(securedPath).then().statusCode(401);
given().header("X-Id-Token", "Bearer " + idToken)
.get(securedPath).then().statusCode(401);
} finally {
given().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@ParameterizedTest
@ValueSource(strings = {"", ", \"providerARNs\": null"})
void mergingPartialCognitoAuthorizerKeepsRetainedMethodAuthorized(String providerArnsField)
@@ -0,0 +1,145 @@
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 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 java.util.UUID;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CognitoDeleteUserIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String USERNAME = "deleteuser+" + UUID.randomUUID() + "@example.com";
private static final String PASSWORD = "DeleteUser1234!";
private static String poolId;
private static String clientId;
private static String accessToken;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void setUpPoolClientUserAndToken() throws Exception {
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "DeleteUserPool"
}
""");
poolId = poolResponse.path("UserPool").path("Id").asText();
JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "delete-user-client",
"ExplicitAuthFlows": ["ALLOW_ADMIN_USER_PASSWORD_AUTH"]
}
""".formatted(poolId));
clientId = clientResponse.path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{
"UserPoolId": "%s",
"Username": "%s",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(poolId, USERNAME, USERNAME))
.then()
.statusCode(200);
cognitoAction("AdminSetUserPassword", """
{
"UserPoolId": "%s",
"Username": "%s",
"Password": "%s",
"Permanent": true
}
""".formatted(poolId, USERNAME, PASSWORD))
.then()
.statusCode(200);
JsonNode authResponse = cognitoJson("AdminInitiateAuth", """
{
"UserPoolId": "%s",
"ClientId": "%s",
"AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
"AuthParameters": {
"USERNAME": "%s",
"PASSWORD": "%s"
}
}
""".formatted(poolId, clientId, USERNAME, PASSWORD));
accessToken = authResponse.path("AuthenticationResult").path("AccessToken").asText();
}
@Test
@Order(2)
void deleteUserWithMissingOrNullAccessTokenReturnsInvalidParameterException() {
cognitoAction("DeleteUser", "{}")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
cognitoAction("DeleteUser", """
{
"AccessToken": null
}
""")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
}
@Test
@Order(3)
void deleteUserWithValidAccessTokenDeletesUser() {
cognitoAction("DeleteUser", """
{
"AccessToken": "%s"
}
""".formatted(accessToken))
.then()
.statusCode(200);
// Verify AdminGetUser now returns UserNotFoundException
cognitoAction("AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(poolId, USERNAME))
.then()
.statusCode(400)
.body("__type", equalTo("UserNotFoundException"));
}
@Test
@Order(4)
void deleteUserWithAlreadyDeletedUserAccessTokenReturnsNotAuthorizedException() {
cognitoAction("DeleteUser", """
{
"AccessToken": "%s"
}
""".formatted(accessToken))
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"));
}
}
@@ -3976,6 +3976,112 @@ class CognitoServiceTest {
assertEquals(client.getClientId(), id.claims().get("aud"));
}
@Test
@SuppressWarnings("unchecked")
void verifyApiGatewayTokenRejectsTokensOfDeletedUser() {
UserPool pool = createPoolAndUser();
UserPoolClient client = openClient(service, pool.getId(), "c", false);
Map<String, Object> auth = (Map<String, Object>) service.initiateAuth(
client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")).get("AuthenticationResult");
String accessToken = (String) auth.get("AccessToken");
String idToken = (String) auth.get("IdToken");
service.deleteUser(accessToken);
AwsException access = assertThrows(AwsException.class, () -> service.verifyApiGatewayToken(accessToken));
AwsException id = assertThrows(AwsException.class, () -> service.verifyApiGatewayToken(idToken));
assertEquals("NotAuthorizedException", access.getErrorCode());
assertEquals("NotAuthorizedException", id.getErrorCode());
}
@Test
@SuppressWarnings("unchecked")
void verifyApiGatewayTokenRejectsOldTokenOfUserRecreatedUnderTheSameName() {
UserPool pool = createPoolAndUser();
UserPoolClient client = openClient(service, pool.getId(), "c", false);
Map<String, String> credentials = Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!");
Map<String, Object> before = (Map<String, Object>) service.initiateAuth(
client.getClientId(), "USER_PASSWORD_AUTH", credentials).get("AuthenticationResult");
service.adminDeleteUser(pool.getId(), "alice");
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "TempPass1!");
service.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
Map<String, Object> after = (Map<String, Object>) service.initiateAuth(
client.getClientId(), "USER_PASSWORD_AUTH", credentials).get("AuthenticationResult");
AwsException stale = assertThrows(AwsException.class,
() -> service.verifyApiGatewayToken((String) before.get("AccessToken")));
assertEquals("NotAuthorizedException", stale.getErrorCode());
assertEquals("access", service.verifyApiGatewayToken((String) after.get("AccessToken")).tokenUse());
}
@Test
void verifyApiGatewayTokenRejectsDeletedUserTokensWhoseTriggerSuppressedUsername() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "c", false, false, List.of(), List.of());
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
CognitoService.ClaimsOverride suppressUsername = new CognitoService.ClaimsOverride(
null, List.of("cognito:username"), null, List.of("username"), null, null, null, null, null);
String accessToken = service.generateSignedJwt(user, pool, "access", client, suppressUsername);
String idToken = service.generateSignedJwt(user, pool, "id", client, suppressUsername);
assertEquals("access", service.verifyApiGatewayToken(accessToken).tokenUse());
assertEquals("id", service.verifyApiGatewayToken(idToken).tokenUse());
service.adminDeleteUser(pool.getId(), "alice");
AwsException access = assertThrows(AwsException.class, () -> service.verifyApiGatewayToken(accessToken));
AwsException id = assertThrows(AwsException.class, () -> service.verifyApiGatewayToken(idToken));
assertEquals("NotAuthorizedException", access.getErrorCode());
assertEquals("NotAuthorizedException", id.getErrorCode());
}
@Test
void preTokenGenerationOverrideCannotSuppressOrReplaceIdentityClaims() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "c", false, false, List.of(), List.of());
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
String sub = user.getAttributes().get("sub");
CognitoService.ClaimsOverride suppress = new CognitoService.ClaimsOverride(
null, List.of("sub", "cognito:username"), null, List.of("sub", "username"),
null, null, null, null, null);
CognitoService.ClaimsOverride replace = new CognitoService.ClaimsOverride(
Map.<String, Object>of("sub", "other", "cognito:username", "bob"), null,
Map.<String, Object>of("sub", "other", "username", "bob"), null,
null, null, null, null, null);
for (CognitoService.ClaimsOverride override : List.of(suppress, replace)) {
Map<String, Object> access = service.verifyApiGatewayToken(
service.generateSignedJwt(user, pool, "access", client, override)).claims();
Map<String, Object> id = service.verifyApiGatewayToken(
service.generateSignedJwt(user, pool, "id", client, override)).claims();
assertEquals(sub, access.get("sub"));
assertEquals("alice", access.get("username"));
assertEquals(sub, id.get("sub"));
assertEquals("alice", id.get("cognito:username"));
}
}
@Test
void verifyApiGatewayTokenAcceptsClientCredentialsToken() {
String poolId = service.createUserPool(Map.of("PoolName", "m2m-pool"), "us-east-1").getId();
ResourceServerScope read = new ResourceServerScope();
read.setScopeName("read");
service.createResourceServer(poolId, "notes", "Notes", List.of(read));
UserPoolClient client = service.createUserPoolClient(poolId, "m2m", true, true,
List.of("client_credentials"), List.of("notes/read"));
String accessToken = (String) service.issueClientCredentialsToken(
client.getClientId(), client.getClientSecret(), null, null).get("access_token");
CognitoService.VerifiedApiGatewayToken verified = service.verifyApiGatewayToken(accessToken);
assertEquals("access", verified.tokenUse());
assertEquals(client.getClientId(), verified.claims().get("sub"));
}
// =========================================================================
// AdminGetUser resolves configured identifiers
// =========================================================================
@@ -5492,6 +5598,24 @@ class CognitoServiceTest {
assertEquals("Access Token does not have required scopes", ex.getMessage());
}
@Test
void deleteUser_accessTokenWithoutAdminScope_isRejectedAndKeepsTheUser() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "c", false, false, List.of(), List.of());
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
String accessToken = service.generateSignedJwt(user, pool, "access", client,
new CognitoService.ClaimsOverride(null, null, null, null,
List.of("openid", "email"), List.of("aws.cognito.signin.user.admin"),
null, null, null));
AwsException ex = assertThrows(AwsException.class, () -> service.deleteUser(accessToken));
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertEquals("Access Token does not have required scopes", ex.getMessage());
assertEquals("alice", service.adminGetUser(pool.getId(), "alice").getUsername());
}
private void assertInvalidAccessToken(String token, String reason) {
AwsException failure = assertThrows(AwsException.class, () -> service.getUser(token), reason);
assertEquals("NotAuthorizedException", failure.getErrorCode(), reason);
@@ -243,6 +243,17 @@ class GlobalSignOutIntegrationTest {
"GlobalSignOut with no AccessToken must fail with InvalidParameterException, body was: " + body);
}
@Test
@Order(13)
void globalSignOutRejectsExplicitNullAccessToken() throws Exception {
JsonNode body = cognitoJsonAny("GlobalSignOut", """
{"AccessToken":null}
""");
assertEquals("InvalidParameterException", body.path("__type").asText(),
"GlobalSignOut with a null AccessToken must fail with InvalidParameterException, body was: " + body);
}
/** Build an unsigned JWT-shaped access token — the emulator decodes the payload without verifying the signature. */
private static String forgeAccessToken(String poolId, String username) {
long nowSeconds = System.currentTimeMillis() / 1000L;