Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cognito): add AdminLinkProviderForUser (#2166)

soreavis0203bc7f7e71
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index 62ebad3ce6..4c24becffd 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -64,6 +64,7 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource`
| AdminDeleteUser | Deletes a user from a user pool. |
| AdminSetUserPassword | Sets a user's password and permanent-password status. |
| AdminUpdateUserAttributes | Updates attributes for a user in a user pool. |
+| AdminLinkProviderForUser | Links an external IdP identity to an existing user's `identities` attribute. |
### User Operations
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.java
index 9cdd5df0c7..4b9dea6812 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
@@ -67,6 +67,7 @@ public class CognitoJsonHandler {
case "AdminUserGlobalSignOut" -> handleAdminUserGlobalSignOut(request);
case "AdminEnableUser" -> handleAdminEnableUser(request);
case "AdminDisableUser" -> handleAdminDisableUser(request);
+ case "AdminLinkProviderForUser" -> handleAdminLinkProviderForUser(request);
case "ListUsers" -> handleListUsers(request);
case "InitiateAuth" -> handleInitiateAuth(request);
case "AdminInitiateAuth" -> handleAdminInitiateAuth(request);
@@ -436,6 +437,16 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
+ private Response handleAdminLinkProviderForUser(JsonNode request) {
+ JsonNode sourceUser = request.path("SourceUser");
+ service.adminLinkProviderForUser(
+ request.path("UserPoolId").asText(),
+ request.path("DestinationUser").path("ProviderAttributeValue").asText(),
+ sourceUser.path("ProviderName").asText(),
+ sourceUser.path("ProviderAttributeValue").asText());
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
private Response handleListUsers(JsonNode request) {
String filter = request.path("Filter").isMissingNode() ? null : request.path("Filter").asText(null);
List<CognitoUser> users = service.listUsers(request.path("UserPoolId").asText(), filter);
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 9433a0bbf4..3f80a5b346 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
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -41,6 +43,14 @@ public class CognitoService {
private static final Logger LOG = Logger.getLogger(CognitoService.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String IDENTITIES_ATTRIBUTE = "identities";
+
+ // AWS provider types that double as the provider name. SAML and OIDC types are only
+ // knowable from a registered IdP, which floci does not model, so they stay null.
+ private static final Set<String> NAMED_PROVIDER_TYPES =
+ Set.of("Facebook", "Google", "LoginWithAmazon", "SignInWithApple");
+
+
/**
* Claim overrides returned by a PreTokenGeneration Lambda trigger.
* <p>
@@ -981,6 +991,82 @@ public class CognitoService {
LOG.infov("Reset password for user {0} in pool {1}", user.getUsername(), userPoolId);
}
+ // Serializes adminLinkProviderForUser's check-then-write.
+ private final Object identityLinkLock = new Object();
+
+ public void adminLinkProviderForUser(String userPoolId, String destinationUsername,
+ String sourceProviderName, String sourceUserId) {
+ if (destinationUsername == null || destinationUsername.isEmpty()) {
+ throw new AwsException("InvalidParameterException",
+ "DestinationUser.ProviderAttributeValue is required.", 400);
+ }
+ if (sourceProviderName == null || sourceProviderName.isEmpty()) {
+ throw new AwsException("InvalidParameterException",
+ "SourceUser.ProviderName is required.", 400);
+ }
+ if (sourceUserId == null || sourceUserId.isEmpty()) {
+ throw new AwsException("InvalidParameterException",
+ "SourceUser.ProviderAttributeValue is required.", 400);
+ }
+
+ // The uniqueness check and the write must not interleave with another
+ // link of the same source identity. The UserPool object cannot serve as
+ // the monitor — updateUserPool replaces the stored instance — so links
+ // serialize on a dedicated lock.
+ synchronized (identityLinkLock) {
+ CognitoUser user = adminGetUser(userPoolId, destinationUsername);
+ String prefix = userPoolId + "::";
+ if (userStore.scan(k -> k.startsWith(prefix)).stream()
+ .anyMatch(u -> hasLinkedIdentity(u, sourceProviderName, sourceUserId))) {
+ throw new AwsException("AliasExistsException",
+ "Source identity is already linked to a user in this user pool", 400);
+ }
+
+ ArrayNode identities = readIdentities(user);
+ identities.addObject()
+ .put("userId", sourceUserId)
+ .put("providerName", sourceProviderName)
+ .put("providerType",
+ NAMED_PROVIDER_TYPES.contains(sourceProviderName) ? sourceProviderName : null)
+ .putNull("issuer")
+ .put("primary", false)
+ // AWS emits dateCreated in epoch milliseconds, unlike the seconds this
+ // service uses for its own user timestamps.
+ .put("dateCreated", System.currentTimeMillis());
+
+ user.getAttributes().put(IDENTITIES_ATTRIBUTE, identities.toString());
+ user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
+ userStore.put(userKey(userPoolId, user.getUsername()), user);
+ LOG.infov("Linked {0} identity {1} to user {2} in pool {3}",
+ sourceProviderName, sourceUserId, user.getUsername(), userPoolId);
+ }
+ }
+
+ private boolean hasLinkedIdentity(CognitoUser user, String providerName, String userId) {
+ for (JsonNode identity : readIdentities(user)) {
+ if (providerName.equals(identity.path("providerName").asText())
+ && userId.equals(identity.path("userId").asText())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private ArrayNode readIdentities(CognitoUser user) {
+ String raw = user.getAttributes().get(IDENTITIES_ATTRIBUTE);
+ if (raw != null && !raw.isBlank()) {
+ try {
+ if (MAPPER.readTree(raw) instanceof ArrayNode stored) {
+ return stored;
+ }
+ LOG.warnv("Discarding non-array identities attribute for user {0}", user.getUsername());
+ } catch (JsonProcessingException e) {
+ LOG.warnv(e, "Discarding malformed identities attribute for user {0}", user.getUsername());
+ }
+ }
+ return MAPPER.createArrayNode();
+ }
+
public List<CognitoUser> listUsers(String userPoolId, String filter) {
String prefix = userPoolId + "::";
List<CognitoUser> all = userStore.scan(k -> k.startsWith(prefix));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
index cdf68885c8..615ca796dd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
@@ -39,6 +39,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
@QuarkusTest
@@ -2290,7 +2291,65 @@ class CognitoIntegrationTest {
assertEquals(1200L, refreshedIdPayload.path("exp").asLong() - refreshedIdPayload.path("iat").asLong());
}
+ @Test
+ @Order(100)
+ void adminLinkProviderForUserSurfacesIdentityOnAdminGetUser() throws Exception {
+ JsonNode poolResponse = cognitoJson("CreateUserPool", """
+ {
+ "PoolName": "LinkProviderPool"
+ }
+ """);
+ String linkPoolId = poolResponse.path("UserPool").path("Id").asText();
+ String linkUsername = "linked+" + UUID.randomUUID() + "@example.com";
+
+ cognitoAction("AdminCreateUser", """
+ {
+ "UserPoolId": "%s",
+ "Username": "%s",
+ "MessageAction": "SUPPRESS"
+ }
+ """.formatted(linkPoolId, linkUsername))
+ .then()
+ .statusCode(200);
+
+ cognitoAction("AdminLinkProviderForUser", """
+ {
+ "UserPoolId": "%s",
+ "DestinationUser": {
+ "ProviderName": "Cognito",
+ "ProviderAttributeValue": "%s"
+ },
+ "SourceUser": {
+ "ProviderName": "Google",
+ "ProviderAttributeName": "Cognito_Subject",
+ "ProviderAttributeValue": "google-sub-1563"
+ }
+ }
+ """.formatted(linkPoolId, linkUsername))
+ .then()
+ .statusCode(200)
+ .body(equalTo("{}"));
+ JsonNode user = cognitoJson("AdminGetUser", """
+ {
+ "UserPoolId": "%s",
+ "Username": "%s"
+ }
+ """.formatted(linkPoolId, linkUsername));
+
+ String identities = StreamSupport.stream(Spliterators.spliteratorUnknownSize(
+ user.path("UserAttributes").elements(), 0), false)
+ .filter(n -> "identities".equals(n.path("Name").asText()))
+ .map(n -> n.path("Value").asText())
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("identities attribute missing: " + user));
+ JsonNode identity = OBJECT_MAPPER.readTree(identities).get(0);
+ assertEquals("google-sub-1563", identity.path("userId").asText());
+ assertEquals("Google", identity.path("providerName").asText());
+ assertEquals("Google", identity.path("providerType").asText());
+ assertTrue(identity.path("issuer").isNull());
+ assertFalse(identity.path("primary").asBoolean());
+ }
private static JsonNode decodeJwtPayload(String token) throws Exception {
return decodeJwtPart(token, 1);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java
index afa062d145..57532c2078 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java
@@ -385,6 +385,79 @@ class CognitoJsonHandlerTest {
"CreateUserPoolClient must not return RefreshTokenRotation when not set");
}
+ // Issue #1563 — AdminLinkProviderForUser
+
+ @Test
+ void adminLinkProviderForUserReturnsEmptyBody() {
+ String poolId = createPoolWithUser("link-pool", "alice");
+
+ Response response = handler.handle("AdminLinkProviderForUser",
+ linkRequest(poolId, "alice", "Google", "google-sub-123"), "us-east-1");
+
+ assertEquals(200, response.getStatus());
+ JsonNode body = (JsonNode) response.getEntity();
+ assertTrue(body.isObject());
+ assertTrue(body.isEmpty(), "AdminLinkProviderForUser returns an empty JSON object");
+ }
+
+ @Test
+ void adminLinkProviderForUserIdentitySurfacesInAdminGetUser() {
+ String poolId = createPoolWithUser("link-getuser-pool", "alice");
+ handler.handle("AdminLinkProviderForUser",
+ linkRequest(poolId, "alice", "Google", "google-sub-123"), "us-east-1");
+
+ ObjectNode getUser = mapper.createObjectNode();
+ getUser.put("UserPoolId", poolId);
+ getUser.put("Username", "alice");
+ JsonNode body = (JsonNode) handler.handle("AdminGetUser", getUser, "us-east-1").getEntity();
+
+ String identities = StreamSupport.stream(Spliterators.spliteratorUnknownSize(
+ body.get("UserAttributes").elements(), 0), false)
+ .filter(n -> "identities".equals(n.get("Name").asText()))
+ .map(n -> n.get("Value").asText())
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("identities attribute missing from AdminGetUser"));
+ assertTrue(identities.contains("\"userId\":\"google-sub-123\""), identities);
+ assertTrue(identities.contains("\"providerName\":\"Google\""), identities);
+ }
+
+ @Test
+ void adminLinkProviderForUserUnknownUserThrows() {
+ String poolId = createPoolWithUser("link-missing-pool", "alice");
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ handler.handle("AdminLinkProviderForUser",
+ linkRequest(poolId, "ghost", "Google", "google-sub-123"), "us-east-1"));
+ assertEquals("UserNotFoundException", exception.getErrorCode());
+ }
+
+ private String createPoolWithUser(String poolName, String username) {
+ ObjectNode poolReq = mapper.createObjectNode();
+ poolReq.put("PoolName", poolName);
+ JsonNode poolBody = (JsonNode) handler.handle("CreateUserPool", poolReq, "us-east-1").getEntity();
+ String poolId = poolBody.get("UserPool").get("Id").asText();
+
+ ObjectNode createUser = mapper.createObjectNode();
+ createUser.put("UserPoolId", poolId);
+ createUser.put("Username", username);
+ handler.handle("AdminCreateUser", createUser, "us-east-1");
+ return poolId;
+ }
+
+ private ObjectNode linkRequest(String poolId, String destinationUsername,
+ String sourceProviderName, String sourceUserId) {
+ ObjectNode request = mapper.createObjectNode();
+ request.put("UserPoolId", poolId);
+ request.putObject("DestinationUser")
+ .put("ProviderName", "Cognito")
+ .put("ProviderAttributeValue", destinationUsername);
+ request.putObject("SourceUser")
+ .put("ProviderName", sourceProviderName)
+ .put("ProviderAttributeName", "Cognito_Subject")
+ .put("ProviderAttributeValue", sourceUserId);
+ return request;
+ }
+
private Set<String> schemaNames(JsonNode pool) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(pool.get("SchemaAttributes").elements(), 0), false)
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 c5da58ccf6..0b2935513e 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
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.cognito;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
@@ -34,6 +37,8 @@ import static org.mockito.Mockito.when;
class CognitoServiceTest {
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
private CognitoService service;
private InMemoryStorage<String, CognitoUser> userStore;
private InMemoryStorage<String, CognitoGroup> groupStore;
@@ -941,6 +946,124 @@ class CognitoServiceTest {
service.adminAddUserToGroup(pool.getId(), "admins", "nonexistent"));
}
+ // =========================================================================
+ // Issue #1563 — AdminLinkProviderForUser
+ // =========================================================================
+
+ @Test
+ void adminLinkProviderForUserAppendsIdentity() {
+ UserPool pool = createPoolAndUser();
+
+ service.adminLinkProviderForUser(pool.getId(), "alice", "Google", "google-sub-123");
+
+ JsonNode identities = identitiesOf(pool, "alice");
+ assertEquals(1, identities.size());
+ JsonNode identity = identities.get(0);
+ assertEquals("google-sub-123", identity.get("userId").asText());
+ assertEquals("Google", identity.get("providerName").asText());
+ assertEquals("Google", identity.get("providerType").asText());
+ assertTrue(identity.get("issuer").isNull());
+ assertFalse(identity.get("primary").asBoolean());
+ assertTrue(identity.get("dateCreated").isNumber(),
+ "dateCreated must be a JSON number, not a string");
+ assertTrue(identity.get("dateCreated").asLong() > 1_600_000_000_000L,
+ "dateCreated must be epoch milliseconds, not seconds");
+ }
+
+ @Test
+ void adminLinkProviderForUserRejectsMissingSourceFields() {
+ UserPool pool = createPoolAndUser();
+
+ AwsException noProvider = assertThrows(AwsException.class,
+ () -> service.adminLinkProviderForUser(pool.getId(), "alice", "", "google-sub-123"));
+ assertEquals("InvalidParameterException", noProvider.getErrorCode());
+
+ AwsException noUserId = assertThrows(AwsException.class,
+ () -> service.adminLinkProviderForUser(pool.getId(), "alice", "Google", ""));
+ assertEquals("InvalidParameterException", noUserId.getErrorCode());
+
+ AwsException noDestination = assertThrows(AwsException.class,
+ () -> service.adminLinkProviderForUser(pool.getId(), "", "Google", "google-sub-123"));
+ assertEquals("InvalidParameterException", noDestination.getErrorCode());
+
+ assertNull(service.adminGetUser(pool.getId(), "alice").getAttributes().get("identities"));
+ }
+
+ @Test
+ void adminLinkProviderForUserReplacesMalformedIdentities() {
+ UserPool pool = createPoolAndUser();
+ service.adminUpdateUserAttributes(pool.getId(), "alice", Map.of("identities", "not-json-at-all"));
+
+ service.adminLinkProviderForUser(pool.getId(), "alice", "Google", "google-sub-123");
+
+ JsonNode identities = identitiesOf(pool, "alice");
+ assertEquals(1, identities.size());
+ assertEquals("google-sub-123", identities.get(0).get("userId").asText());
+ }
+
+ @Test
+ void adminLinkProviderForUserSecondProviderAppends() {
+ UserPool pool = createPoolAndUser();
+
+ service.adminLinkProviderForUser(pool.getId(), "alice", "Google", "google-sub-123");
+ service.adminLinkProviderForUser(pool.getId(), "alice", "MyOIDCProvider", "oidc-sub-456");
+
+ JsonNode identities = identitiesOf(pool, "alice");
+ assertEquals(2, identities.size());
+ assertEquals("Google", identities.get(0).get("providerName").asText());
+ assertEquals("MyOIDCProvider", identities.get(1).get("providerName").asText());
+ assertTrue(identities.get(1).get("providerType").isNull(),
+ "providerType is unknowable without a registered IdP");
+ }
+
+ @Test
+ void adminLinkProviderForUserDuplicateIdentityThrows() {
+ UserPool pool = createPoolAndUser();
+ service.adminLinkProviderForUser(pool.getId(), "alice", "Google", "google-sub-123");
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.adminLinkProviderForUser(pool.getId(), "alice", "Google", "google-sub-123"));
+ assertEquals("AliasExistsException", ex.getErrorCode());
+ }
+
+ @Test
+ void adminLinkProviderForUserRelinkToDifferentUserThrows() {
+ UserPool pool = createPoolAndUser();
+ service.adminCreateUser(pool.getId(), "bob", Map.of("email", "[email protected]"), "TempPass1!");
+ service.adminLinkProviderForUser(pool.getId(), "alice", "Google", "google-sub-123");
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.adminLinkProviderForUser(pool.getId(), "bob", "Google", "google-sub-123"));
+ assertEquals("AliasExistsException", ex.getErrorCode());
+ assertEquals(1, identitiesOf(pool, "alice").size(), "the existing link must survive");
+ }
+
+ @Test
+ void adminLinkProviderForUserUnknownUserThrows() {
+ UserPool pool = createPoolAndUser();
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.adminLinkProviderForUser(pool.getId(), "ghost", "Google", "google-sub-123"));
+ assertEquals("UserNotFoundException", ex.getErrorCode());
+ }
+
+ @Test
+ void adminLinkProviderForUserUnknownPoolThrows() {
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.adminLinkProviderForUser("us-east-1_missing", "alice", "Google", "google-sub-123"));
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ }
+
+ private JsonNode identitiesOf(UserPool pool, String username) {
+ String raw = service.adminGetUser(pool.getId(), username).getAttributes().get("identities");
+ assertNotNull(raw, "identities attribute should be set");
+ try {
+ return MAPPER.readTree(raw);
+ } catch (JsonProcessingException e) {
+ throw new AssertionError("identities is not valid JSON: " + raw, e);
+ }
+ }
+
// =========================================================================
// JWT groups claim
// =========================================================================