fix(cognito): delete a user pool's records with the pool (#2949)

* fix(cognito): delete a user pool's app clients, revocations and codes

#3419 took users and resource servers out with the pool, closing the half of
#2864 that was reported. Three more record types are the same defect and were
left behind: app clients, revoked token records and outstanding verification
codes.

On AWS a pool id is never reused, so nothing can inherit an orphan. Here
floci:override-id makes ids caller-chosen and therefore reusable, and a pool
recreated on a pinned id picks up whatever the deleted pool left.

Reproduced by pinning us-east-1_orphanprobe1, populating it, deleting the pool
and recreating it on the same id. The client leak is the serious one: the
deleted pool's client id kept resolving against the new pool, carrying a secret
the new pool's caller never saw.

  clients: ["c1"]
  describe-user-pool-client --client-id c1a93e3fc698451d96ed406adb -> c1

Clients are keyed by client id alone, so they are found by their userPoolId
field rather than a key prefix. Revoked tokens and verification codes have
their keys collected before deleting so the backing key set is not modified
while it is being iterated.

confirmSignUpNamesDeletedUserPoolInResourceNotFoundMessage, added by #2936,
built its orphaned client by deleting the client's pool, which this cascade
now prevents. It is renamed and reaches the same defensive path by dropping the
pool record alone, and a second case pins the new behaviour: a client id from a
deleted pool is gone with it.

Refs #2864

* fix(cognito): bound the delete cascade by pool ownership, not key prefix

floci:override-id makes pool ids caller-chosen, and validateOverrideId
permits a colon. Two live pools can therefore be named so that one id
plus the key separator is a prefix of the other, and the revoked-token
and verification-code cascades deleted by the matched key, so deleting
the shorter pool erased the longer one's records. For revoked tokens
that reinstated tokens the surviving pool had revoked.

Both records carry their own userPoolId, so ownership is now settled by
that field rather than by the key prefix. The other cascades reconstruct
the key from the pool id being deleted and so never reached across a
boundary; they are left alone.

A jti can itself contain a colon (global revocations use
global:{username}), so bounding the prefix by the separator would not
have been sufficient either.
This commit is contained in:
Brian Taylor authored and GitHub committed 2026-09-12 23:39:32 -04:00
1 parent 17245081f1
commit 2a4ca61baf
6 files changed
+211 -10

No files matched your search

@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* DeleteUserPool has to take the pool's records with it.
*
* <p>On AWS a pool id is never reused, so nothing can be inherited. Floci's
* {@code floci:override-id} reserved tag makes ids caller-chosen and therefore reusable, which
* turns any record left behind into one the next pool pinned to the same id picks up. Orphaned
* users keep their password hashes and orphaned clients keep their secrets, so the recreated
* pool has to come up empty.
*/
@QuarkusTest
class CognitoDeleteUserPoolCascadeIntegrationTest {
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static String createPinnedPool(String poolId, String poolName) throws Exception {
JsonNode pool = cognitoJson("CreateUserPool", """
{
"PoolName": "%s",
"UserPoolTags": { "floci:override-id": "%s" }
}
""".formatted(poolName, poolId));
return pool.path("UserPool").path("Id").asText();
}
@Test
void aPoolRecreatedOnAPinnedIdInheritsNothingFromTheDeletedOne() throws Exception {
String poolId = "us-east-1_cascadeprobe";
assertEquals(poolId, createPinnedPool(poolId, "cascade-probe"));
cognitoAction("AdminCreateUser", """
{
"UserPoolId": "%s",
"Username": "orphanuser",
"MessageAction": "SUPPRESS"
}
""".formatted(poolId)).then().statusCode(200);
cognitoAction("CreateResourceServer", """
{
"UserPoolId": "%s",
"Identifier": "https://api.example.com",
"Name": "API",
"Scopes": [ { "ScopeName": "read", "ScopeDescription": "r" } ]
}
""".formatted(poolId)).then().statusCode(200);
String clientId = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "orphanclient"
}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
assertTrue(clientId != null && !clientId.isEmpty(), "client id must be issued");
cognitoAction("CreateGroup", """
{
"UserPoolId": "%s",
"GroupName": "orphangroup"
}
""".formatted(poolId)).then().statusCode(200);
cognitoAction("DeleteUserPool", """
{ "UserPoolId": "%s" }
""".formatted(poolId)).then().statusCode(200);
assertEquals(poolId, createPinnedPool(poolId, "cascade-probe-2"));
assertEquals(0, cognitoJson("ListUsers", """
{ "UserPoolId": "%s" }
""".formatted(poolId)).path("Users").size(), "users must not be inherited");
assertEquals(0, cognitoJson("ListResourceServers", """
{ "UserPoolId": "%s", "MaxResults": 10 }
""".formatted(poolId)).path("ResourceServers").size(),
"resource servers must not be inherited");
assertEquals(0, cognitoJson("ListUserPoolClients", """
{ "UserPoolId": "%s" }
""".formatted(poolId)).path("UserPoolClients").size(),
"clients must not be inherited");
assertEquals(0, cognitoJson("ListGroups", """
{ "UserPoolId": "%s" }
""".formatted(poolId)).path("Groups").size(), "groups must not be inherited");
// The deleted pool's client id must not keep working against the new pool: it was issued
// with a secret the caller of the recreated pool never saw.
cognitoAction("DescribeUserPoolClient", """
{
"UserPoolId": "%s",
"ClientId": "%s"
}
""".formatted(poolId, clientId))
.then().statusCode(400)
.body("__type", org.hamcrest.Matchers.equalTo("ResourceNotFoundException"));
cognitoAction("DeleteUserPool", """
{ "UserPoolId": "%s" }
""".formatted(poolId)).then().statusCode(200);
}
}
@@ -54,6 +54,7 @@ class CognitoServiceTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private CognitoService service;
private InMemoryStorage<String, UserPool> poolStore;
private InMemoryStorage<String, CognitoUser> userStore;
private InMemoryStorage<String, CognitoGroup> groupStore;
private InMemoryStorage<String, RevokedTokenInfo> revokedTokenStore;
@@ -62,6 +63,7 @@ class CognitoServiceTest {
@BeforeEach
void setUp() {
poolStore = new InMemoryStorage<>();
userStore = new InMemoryStorage<>();
groupStore = new InMemoryStorage<>();
revokedTokenStore = new InMemoryStorage<>();
@@ -71,7 +73,7 @@ class CognitoServiceTest {
when(acmService.describeCertificate(anyString(), eq("us-east-1")))
.thenAnswer(inv -> issuedCertificate(inv.getArgument(0)));
service = new CognitoService(
new InMemoryStorage<>(),
poolStore,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
userStore,
@@ -1527,7 +1529,23 @@ class CognitoServiceTest {
}
@Test
void confirmSignUpNamesDeletedUserPoolInResourceNotFoundMessage() {
void confirmSignUpNamesMissingUserPoolInResourceNotFoundMessage() {
UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "test-client", false, false, List.of(), List.of());
// DeleteUserPool takes the pool's clients with it, so an orphaned client cannot be
// produced through the API. Drop the pool record alone to reach the defensive path.
poolStore.delete(pool.getId());
AwsException ex = assertThrows(AwsException.class, () ->
service.confirmSignUp(client.getClientId(), "carol", "123456"));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
assertEquals("User pool " + pool.getId() + " does not exist.", ex.getMessage());
assertEquals(400, ex.getHttpStatus());
}
@Test
void confirmSignUpRejectsAClientIdBelongingToADeletedUserPool() {
UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "test-client", false, false, List.of(), List.of());
@@ -1536,7 +1554,7 @@ class CognitoServiceTest {
AwsException ex = assertThrows(AwsException.class, () ->
service.confirmSignUp(client.getClientId(), "carol", "123456"));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
assertEquals("User pool " + pool.getId() + " does not exist.", ex.getMessage());
assertEquals("Client not found", ex.getMessage());
assertEquals(400, ex.getHttpStatus());
}
@@ -132,6 +132,37 @@ class VerificationCodeServiceTest {
VerificationCode.Purpose.PASSWORD_RESET, resetCode));
}
@Test
void invalidateForPool_removesOnlyThatPoolsCodes() {
service.issue("pool", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
String otherCode = service.issue("other", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
service.invalidateForPool("pool");
assertThrows(VerificationCodeException.class, () -> service.consume("pool", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, "000000"));
assertDoesNotThrow(() -> service.consume("other", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, otherCode));
}
@Test
void invalidateForPool_sparesPoolWhoseIdExtendsThisOne() {
// floci:override-id lets a caller pin an id containing a colon, so "pool:child" is a
// distinct live pool whose storage keys share the "pool:" prefix of the pool being deleted.
service.issue("pool", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
String childCode = service.issue("pool:child", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
service.invalidateForPool("pool");
assertDoesNotThrow(() -> service.consume("pool:child", "alice",
VerificationCode.Purpose.SIGNUP_CONFIRMATION, childCode),
"deleting pool must not invalidate a code issued by pool:child");
}
static final class MutableClock extends Clock {
private Instant now;
MutableClock(Instant start) { this.now = start; }