feat(cognito): add AdminLinkProviderForUser (#2166)

* feat(cognito): add AdminLinkProviderForUser

Linking a federated identity to an existing user pool user returned
400 UnsupportedOperation, because the action had no arm in the
CognitoJsonHandler switch and fell through to the default case.

Add the action to the handler and service. The link is recorded as an
entry in the destination user's `identities` attribute, matching the
JSON array AWS documents: userId, providerName, providerType, issuer,
primary and dateCreated. CognitoUser.attributes is already a free-form
map and AdminGetUser emits every attribute as a UserAttribute, so the
linked identity surfaces without a model change.

dateCreated is stored in epoch milliseconds. That differs from the
seconds this service uses for its own user timestamps, but it is what
AWS emits in the identities attribute and the ID token claim.

providerType is only set when the source provider name is one of the
provider types AWS also uses as a name (Facebook, Google,
LoginWithAmazon, SignInWithApple). SAML and OIDC types, and issuer, are
properties of a registered IdP, which the emulator does not model, so
they stay null rather than being guessed.

A source identity may be linked to at most one user per pool; a
conflicting link throws AliasExistsException, a documented error of
this operation.

Source provider names are not validated against a configured IdP, and
the five-identity cap is not enforced. Both are noted as deliberate
divergences in the pull request.

Closes #1563

* fix(cognito): validate link fields and serialize the uniqueness check

AdminLinkProviderForUser accepted requests with a missing SourceUser
ProviderName or ProviderAttributeValue: path().asText() turns absent
fields into empty strings, so a bad request returned 200 and persisted
an identity with an empty providerName or userId. Require the three
fields up front and answer InvalidParameterException, matching how
this service already reports missing required input.

The uniqueness check and the write could also interleave: two
concurrent links of the same source identity to different users could
both pass the scan before either wrote. Wrap the check and the write
in synchronized (pool), the pattern the tag operations already use.

* fix(cognito): serialize identity links on a stable monitor

The uniqueness check locked the UserPool object, but updateUserPool
replaces the stored instance (convertValue copy + poolStore.put), so
two links racing an update could hold different monitors and both pass
the scan. Serialize on a dedicated lock instead, declared beside the
one method it guards.

Dropping the describeUserPool lookup also changes the unknown-pool
error source: adminGetUser reports it as ResourceNotFoundException 400,
which is how every sibling admin user mutator already reports it.

Verified with an 8-thread probe linking the same source identity to
eight users: one winner and seven AliasExistsException with the lock,
eight winners without it.
This commit is contained in:
soreavis authored and GitHub committed 2026-08-07 17:30:11 -05:00
1 parent 7d9b9aedd2
commit 0203bc7f7e
6 files changed
+353

No files matched your search

+1
View File
@@ -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
@@ -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);
@@ -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));
@@ -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);
@@ -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)
@@ -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", "bob@example.com"), "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
// =========================================================================