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

+2 -2
View File
@@ -6,7 +6,7 @@
Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys.
`CreateUserPool` supports overiding several values using user-pool tags **only** at creation time:
* `floci:override-id`, to pin the resulting `UserPool.Id`.
* `floci:override-id`, to pin the resulting `UserPool.Id`. Because a pinned id is caller-chosen it can be reused, which AWS never does. `DeleteUserPool` therefore deletes everything the pool owns (users, groups, app clients, resource servers, revoked token records and outstanding verification codes) so a pool recreated on the same id starts empty rather than inheriting the deleted pool's password hashes and client secrets.
* `floci:override-cognito-client-id`
* set to `use-name` to use the client name as client ID.
* set to `append-to-name:-somestring` to append a string to the client name to be used as client ID.
@@ -29,7 +29,7 @@ An action given a user pool ID that does not resolve returns `ResourceNotFoundEx
| DescribeUserPool | Returns the stored user pool configuration. |
| ListUserPools | Lists local user pools visible in the request region. |
| UpdateUserPool | Updates mutable user pool settings and persisted user-pool tags. |
| DeleteUserPool | Deletes a local user pool and its related state. |
| 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 a domain is still configured. |
| GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token setting. |
| 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. |
@@ -540,18 +540,37 @@ public class CognitoService implements ResourceProvider {
throw new AwsException("InvalidParameterException",
"User pool cannot be deleted. It has a domain configured that should be deleted first.", 400);
}
// github.com/floci-io/floci/issues/2864: every record the pool owns goes with it. On AWS
// a pool id is never reused, so the question does not arise; here floci:override-id makes
// ids caller-chosen and therefore reusable, and anything left behind is inherited by the
// next pool pinned to the same id. Orphaned users keep their password hashes and orphaned
// clients keep their secrets.
String prefix = id + "::";
groupStore.scan(k -> k.startsWith(prefix))
.forEach(g -> groupStore.delete(groupKey(id, g.getGroupName())));
// github.com/floci-io/floci/issues/2864: a pool id can be pinned with the
// floci:override-id tag, so it can be reused after delete - unlike real AWS, where a
// pool id is never reused and this situation can't arise. Without this, a pool
// recreated on the same id inherited the deleted pool's users (password hashes and
// all) and resource servers.
userStore.scan(k -> k.startsWith(prefix))
.forEach(u -> userStore.delete(userKey(id, u.getUsername())));
resourceServerStore.scan(k -> k.startsWith(prefix))
.forEach(r -> resourceServerStore.delete(resourceServerKey(id, r.getIdentifier())));
// Clients are keyed by client id alone, so they are found by their userPoolId field.
listUserPoolClients(id).forEach(c -> clientStore.delete(c.getClientId()));
// Revoked tokens are keyed revoked:{poolId}:{jti}, and a jti may itself contain a colon
// (global revocations use global:{username}), so the prefix cannot be bounded by the
// separator alone. Pool ids are caller-chosen and may also contain a colon, which would
// let this prefix match a live pool whose id extends this one and reinstate its revoked
// tokens. The record's own userPoolId settles ownership. Keys are collected before
// deleting so the backing key set is not modified while it is being iterated.
String revokedPrefix = "revoked:" + id + ":";
revokedTokenStore.keys().stream()
.filter(k -> k.startsWith(revokedPrefix))
.filter(k -> revokedTokenStore.get(k)
.map(t -> id.equals(t.getUserPoolId()))
.orElse(false))
.toList()
.forEach(revokedTokenStore::delete);
if (verificationCodeService != null) {
verificationCodeService.invalidateForPool(id);
}
// Same lock as the provider mutations: a create or update that interleaves with
// this cascade would otherwise reinstate a provider for a pool that is going away.
synchronized (identityProviderLock) {
@@ -145,6 +145,21 @@ public final class VerificationCodeService {
store.delete(VerificationCode.storageKey(userPoolId, username, purpose));
}
/**
* Removes every code issued for a pool, for DeleteUserPool. Pool ids are caller-chosen via
* floci:override-id and may contain a colon, so the key prefix alone also matches a distinct
* pool whose id extends this one. The stored record's own userPoolId settles the boundary.
* Keys are collected before deleting so the backing key set is not modified while iterated.
*/
public void invalidateForPool(String userPoolId) {
String prefix = userPoolId + ":";
store.keys().stream()
.filter(k -> k.startsWith(prefix))
.filter(k -> store.get(k).map(c -> userPoolId.equals(c.getUserPoolId())).orElse(false))
.toList()
.forEach(store::delete);
}
private byte[] randomBytes(int n) {
byte[] b = new byte[n];
random.nextBytes(b);
@@ -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; }