mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 14:30:28 -05:00
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:
1 parent
7d9b9aedd2
commit
0203bc7f7e
6 files changed
+353
No files matched your search
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user