Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Brian Taylor2a4ca61baf4c
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index 780ae329f0..52a6a8e0f0 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -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. |
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.java
index adcffeaed4..c529fe2b96 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
@@ -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) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java
index 2f510b7ef1..ccdf41394b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDeleteUserPoolCascadeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDeleteUserPoolCascadeIntegrationTest.java
new file mode 100644
index 0000000000..b0d00fc504
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDeleteUserPoolCascadeIntegrationTest.java
@@ -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);
+ }
+}
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.java
index acb871ec61..3ae4faa6a3 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
@@ -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,11 +1529,13 @@ 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());
- service.deleteUserPool(pool.getId());
+ // 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"));
@@ -1540,6 +1544,20 @@ class CognitoServiceTest {
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());
+ service.deleteUserPool(pool.getId());
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.confirmSignUp(client.getClientId(), "carol", "123456"));
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ assertEquals("Client not found", ex.getMessage());
+ assertEquals(400, ex.getHttpStatus());
+ }
+
@ParameterizedTest
@CsvSource({"email_verified", "phone_number_verified"})
@SuppressWarnings("unchecked")
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java
index 39e8c1e7d5..44d98766b6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java
@@ -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; }