Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): implement DeleteUser self-service API action (#4493)
iam-ssrivastav8ea033d9fdeb
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex dd92681f8e..adebb5e6c9 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -43,6 +43,7 @@ format. Validation runs before pool or client lookup.| UpdateUserPool | Updates mutable user pool settings and persisted user-pool tags. || DeleteUserPool | Deletes a local user pool and everything it owns: users, groups, app clients, resource servers, identity providers, revoked tokens and verification codes. Refused with `InvalidParameterException` while `DeletionProtection` is `ACTIVE` (switch it to `INACTIVE` with `UpdateUserPool` first, as on AWS) or while a domain is still configured. || GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token setting. |+| AddCustomAttributes | Adds 1 to 25 attributes to a user pool's schema, prefixing each name with `custom:`, or `dev:` for a `DeveloperOnlyAttribute`, and rejecting a name the schema already has. || SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS. SMS, email and WebAuthn configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have. |### User Pool Tags@@ -60,7 +61,11 @@ format. Validation runs before pool or client lookup.| CreateUserPoolClient | Creates an app client for a user pool, including optional generated secret handling. || DescribeUserPoolClient | Returns the stored app client configuration. || ListUserPoolClients | Lists app clients for a user pool. |+| UpdateUserPoolClient | Updates an app client's settings. A field the request omits keeps its stored value, where AWS resets it to its default. || DeleteUserPoolClient | Deletes an app client from a user pool. |+| AddUserPoolClientSecret | Adds a client secret to an app client, up to 2. A supplied `ClientSecret` must be 24 to 64 word characters; without one Floci generates the secret and returns its value. |+| ListUserPoolClientSecrets | Lists an app client's client secrets, without their values. |+| DeleteUserPoolClientSecret | Deletes one of an app client's client secrets. The client's only secret cannot be deleted. |### Resource Servers@@ -178,9 +183,16 @@ further divergences, both deliberate:|--------|-------------|| AdminCreateUser | Creates or resends setup for a user in a user pool. || AdminGetUser | Returns a user's stored attributes and status. |-| AdminDeleteUser | Deletes a user from a user pool. |+| AdminDeleteUser | Deletes a user from a user pool. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. || AdminSetUserPassword | Sets a user's password and permanent-password status. || AdminUpdateUserAttributes | Updates attributes for a user in a user pool. |+| AdminDeleteUserAttributes | Deletes the named attributes from a user, along with any pending verification of them. |+| AdminConfirmSignUp | Confirms a user's sign-up without a confirmation code. |+| AdminDisableUser | Disables a user, who can no longer sign in. Tokens already issued keep working, where AWS revokes the user's access tokens. |+| AdminEnableUser | Re-enables a disabled user. |+| AdminResetUserPassword | Clears a user's password and sets the status to `RESET_REQUIRED`, so sign-in fails with `PasswordResetRequiredException`. Floci sends no reset code: finish with `ForgotPassword` and `ConfirmForgotPassword`, or `AdminSetUserPassword`. Refused when the pool's account recovery is `admin_only`. |+| AdminSetUserMFAPreference | Sets a user's email MFA preference from `EmailMfaSettings`. SMS and software-token settings are accepted but not stored. |+| AdminUserGlobalSignOut | Revokes the access, ID and refresh tokens issued to a user. || AdminLinkProviderForUser | Links an external IdP identity to an existing user's `identities` attribute. |### User Operations@@ -189,19 +201,25 @@ further divergences, both deliberate:|--------|-------------|| SignUp | Creates a self-service user for an app client. || ConfirmSignUp | Confirms a pending self-service signup. |+| ResendConfirmationCode | Issues a new sign-up confirmation code to an unconfirmed user, replacing the previous one, and returns where it was sent. || GetUser | Returns attributes for the authenticated access-token user. || GetUserAuthFactors | Returns the authenticated access-token user's sign-in factors: `PASSWORD` when the user has a password, `EMAIL_OTP` and `SMS_OTP` when the email or phone number is verified, whatever the pool's `AllowedFirstAuthFactors` allows, as on AWS, and `SOFTWARE_TOKEN` once `VerifySoftwareToken` has confirmed an authenticator. The access token must carry the `aws.cognito.signin.user.admin` scope. `UserMFASettingList` and `PreferredMfaSetting` report the email MFA preference set with `SetUserMFAPreference`. `WEB_AUTHN` and SMS or software-token MFA settings are not reported. || GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. || VerifyUserAttribute | Verifies an email or phone_number attribute with its issued verification code. || UpdateUserAttributes | Updates attributes for the authenticated access-token user. |+| DeleteUserAttributes | Deletes the named attributes from the authenticated access-token user. |+| DeleteUser | Deletes the authenticated access-token user and removes them from their groups. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. || ChangePassword | Changes the authenticated user's password. |+| SetUserMFAPreference | Sets the authenticated access-token user's email MFA preference from `EmailMfaSettings`. SMS and software-token settings are accepted but not stored. |+| GlobalSignOut | Revokes the access, ID and refresh tokens issued to the authenticated access-token user. || ForgotPassword | Starts the local forgot-password flow for a user. || ConfirmForgotPassword | Completes the forgot-password flow by setting a replacement password. |As on AWS, every operation authorized by the user's access token (`GetUser`,-`GetUserAuthFactors`, `UpdateUserAttributes`, `DeleteUserAttributes`, `ChangePassword`,-`GetUserAttributeVerificationCode`, `VerifyUserAttribute`, `SetUserMFAPreference`,-`GlobalSignOut`, and `AssociateSoftwareToken` and `VerifySoftwareToken` with an `AccessToken`)+`GetUserAuthFactors`, `UpdateUserAttributes`, `DeleteUserAttributes`, `DeleteUser`,+`ChangePassword`, `GetUserAttributeVerificationCode`, `VerifyUserAttribute`,+`SetUserMFAPreference`, `GlobalSignOut`, and `AssociateSoftwareToken` and+`VerifySoftwareToken` with an `AccessToken`)requires the token's `scope` to include `aws.cognito.signin.user.admin`. Tokens from`InitiateAuth` and the other API sign-in flows always carry it; a token from the OAuth tokenendpoint carries it only when the authorization request asked for it, or asked for no scope and@@ -216,6 +234,9 @@ which a pre token generation trigger leaves when it suppresses every scope.| InitiateAuth | Authenticates app-client users through supported user-password and SRP-style flows. || AdminInitiateAuth | Starts an admin authentication flow for a user pool user. || RespondToAuthChallenge | Responds to supported Cognito auth challenges, including TOTP setup and software-token MFA. |+| AdminRespondToAuthChallenge | Responds to a challenge from `AdminInitiateAuth`, with the same challenges `RespondToAuthChallenge` supports. |+| GetTokensFromRefreshToken | Issues new access and ID tokens from a refresh token. A client's `RefreshTokenRotation` setting is stored but not applied, so no new refresh token is issued. |+| RevokeToken | Revokes a refresh token. The client must have token revocation enabled and, when it has a secret, present it. Only refresh tokens can be revoked. || AssociateSoftwareToken | Creates a TOTP secret for a user identified by an MFA setup session or access token. || VerifySoftwareToken | Verifies the TOTP code and enables the user's software token. |@@ -554,6 +575,9 @@ Floci mirrors AWS's access-token / ID-token split:`email_verified`, `phone_number`, `custom:*`, ...). Attribute claims are filtered by the app client's`ReadAttributes` (an unset/empty list means all attributes are readable).+As on AWS, a pre token generation trigger cannot suppress or override `sub`, the access token's+`username` or the ID token's `cognito:username`; Floci ignores those entries in its response.+Not-found errors (`ResourceNotFoundException`, `UserNotFoundException`) return HTTP `400`, matching theCognito JSON protocol.diff --git a/docs/services/index.md b/docs/services/index.mdindex 6aea30cf70..91561711b0 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -26,7 +26,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 || [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 || [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |-| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 43 |+| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 86 || [Cognito Identity](cognitoidentity.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityService.*` | JSON 1.1 | 12 || [Global Accelerator](globalaccelerator.md) | `POST /` + `X-Amz-Target: GlobalAccelerator_V20180706.*` | JSON 1.1 | 22 || [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 42 |diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.javaindex a011ae93bc..59cf77898e 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java@@ -111,6 +111,7 @@ public class CognitoJsonHandler {case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);case "GlobalSignOut" -> handleGlobalSignOut(request);+ case "DeleteUser" -> handleDeleteUser(request);case "CreateGroup" -> handleCreateGroup(request);case "GetGroup" -> handleGetGroup(request);case "ListGroups" -> handleListGroups(request);@@ -1069,7 +1070,12 @@ public class CognitoJsonHandler {}private Response handleGlobalSignOut(JsonNode request) {- service.globalSignOut(request.path("AccessToken").asText());+ service.globalSignOut(request.path("AccessToken").asText(null));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleDeleteUser(JsonNode request) {+ service.deleteUser(request.path("AccessToken").asText(null));return Response.ok(objectMapper.createObjectNode()).build();}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.javaindex be70bafa31..9f15a1757a 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@@ -2146,6 +2146,34 @@ public class CognitoService implements ResourceProvider {LOG.infov("GlobalSignOut: revoked all tokens for user {0} in pool {1}", user.getUsername(), poolId);}+ /**+ * DeleteUser: the self-service counterpart to AdminDeleteUser, authenticated with the caller's+ * access token instead of admin credentials. Deletes the user profile and removes them from all+ * groups, matching AWS behavior.+ */+ public void deleteUser(String accessToken) {+ if (accessToken == null || accessToken.isEmpty()) {+ throw new AwsException("InvalidParameterException",+ "1 validation error detected: Value at 'accessToken' failed to satisfy constraint: Member must not be null", 400);+ }++ VerifiedAccessToken token = verifyAccessToken(accessToken);+ requireScope(accessToken, USER_ADMIN_SCOPE);+ String username = token.username();+ String poolId = token.poolId();+ try {+ adminDeleteUser(poolId, username);+ } catch (AwsException e) {+ if ("UserNotFoundException".equals(e.getErrorCode())+ || "ResourceNotFoundException".equals(e.getErrorCode())) {+ throw new AwsException("NotAuthorizedException", INVALID_ACCESS_TOKEN_MESSAGE, 400);+ }+ throw e;+ }++ LOG.infov("DeleteUser: deleted user {0} in pool {1}", username, poolId);+ }+public CognitoUser adminGetUser(String userPoolId, String username) {UserPool pool = poolStore.get(userPoolId).orElseThrow(() -> userPoolNotFound(userPoolId));@@ -3887,8 +3915,18 @@ public class CognitoService implements ResourceProvider {boolean isAccess = "access".equals(tokenType);List<String> suppress = isAccess ? override.accessClaimsToSuppress() : override.idClaimsToSuppress();Map<String, Object> addOrOverride = isAccess ? override.accessClaimsToAddOrOverride() : override.idClaimsToAddOrOverride();- if (suppress != null) suppress.forEach(claims::remove);- if (addOrOverride != null) claims.putAll(addOrOverride);+ if (suppress != null) {+ suppress.stream()+ .filter(claim -> !isTriggerProtectedIdentityClaim(claim, isAccess))+ .forEach(claims::remove);+ }+ if (addOrOverride != null) {+ addOrOverride.forEach((claim, value) -> {+ if (!isTriggerProtectedIdentityClaim(claim, isAccess)) {+ claims.put(claim, value);+ }+ });+ }if (override.groupsToOverride() != null) {claims.put("cognito:groups", override.groupsToOverride());}@@ -3917,6 +3955,15 @@ public class CognitoService implements ResourceProvider {}}+ /**+ * AWS lets no pre token generation trigger add, modify or suppress the claims that identify+ * the user: {@code sub} in either token, {@code username} in the access token and+ * {@code cognito:username} in the ID token.+ */+ private static boolean isTriggerProtectedIdentityClaim(String claim, boolean isAccess) {+ return "sub".equals(claim) || (isAccess ? "username" : "cognito:username").equals(claim);+ }+private String encodeJwtHeader(UserPool pool) {String headerJson = String.format("{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}",@@ -4652,6 +4699,10 @@ public class CognitoService implements ResourceProvider {validateUserNotGloballySignedOut(username, poolId, tokenUse,requiredNumericClaim(claims, "iat"));}+ boolean clientCredentialsToken = "access".equals(tokenUse) && subject.equals(clientId);+ if (!clientCredentialsToken) {+ requireTokenUserExists(poolId, username, subject);+ }Map<String, Object> mapped = MAPPER.convertValue(claims, new TypeReference<Map<String, Object>>() {});return new VerifiedApiGatewayToken(poolId, tokenUse, Map.copyOf(mapped));} catch (AwsException e) {@@ -4662,6 +4713,19 @@ public class CognitoService implements ResourceProvider {}}+ /**+ * A deleted user's tokens keep a valid signature until they expire, so the authorizer also+ * requires the user to still be in the pool. Every user token names its user, since no pre+ * token generation trigger can remove the username claim, and matching {@code sub} keeps a user+ * re-created under the same name from inheriting the deleted user's tokens.+ */+ private void requireTokenUserExists(String poolId, String username, String subject) {+ CognitoUser user = username == null ? null : userStore.get(userKey(poolId, username)).orElse(null);+ if (user == null || !subject.equals(user.getAttributes().getOrDefault("sub", user.getUsername()))) {+ throw new AwsException("NotAuthorizedException", INVALID_ACCESS_TOKEN_MESSAGE, 400);+ }+ }+/*** Verifies the Cognito access-token contract before any self-service operation uses its claims.* The pool's persisted public key is the trust anchor; claims are never trusted before thediff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCognitoAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCognitoAuthorizerIntegrationTest.javaindex 2c6ace9169..086a26ffe0 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCognitoAuthorizerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCognitoAuthorizerIntegrationTest.java@@ -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)diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDeleteUserIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDeleteUserIntegrationTest.javanew file mode 100644index 0000000000..12be3395be--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDeleteUserIntegrationTest.java@@ -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"));+ }+}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.javaindex 60e5095232..2923963aaf 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@@ -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", "[email protected]"), "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);diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.javaindex d4ca9639fb..5a226ccc93 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java@@ -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;