feat(cognito): implement identity provider configuration CRUD (#2858)

* feat(cognito): implement identity provider configuration CRUD

CreateIdentityProvider, DescribeIdentityProvider, ListIdentityProviders,
UpdateIdentityProvider and DeleteIdentityProvider were unsupported, so
infrastructure tooling could not manage a user pool's federated providers.

Stores provider configuration alongside the other user pool sub-resources and
matches the response and update semantics measured against the live API:

- IdpIdentifiers is echoed by create and update only when the request supplied
  the member, whatever the stored value; describe always returns it
- AttributeMapping defaults to username -> sub when the member is absent at
  create, while an explicitly empty map is stored as given
- members a request omits are preserved rather than cleared
- a duplicate provider name raises DuplicateProviderException
- ListIdentityProviders returns name/type/date summaries, never ProviderDetails

Federated sign-in itself is out of scope: Floci has no /oauth2/authorize or
/oauth2/idpresponse endpoint, so providers are stored configuration only.

* test(cognito): match identity provider exceptions on the SDK error name

`rejects.toThrow(/re/)` matches the error message, but the JS SDK maps the wire
`__type` onto `error.name` and puts the AWS text in `message`, so the duplicate
provider assertion never matched. Assert the name, and pin the enum text with
an explicit message matcher.

* fix(cognito): delete a pool's identity providers with the pool, and update a copy

Two review findings, both reproduced first.

DeleteUserPool left provider records behind. A pool recreated on a pinned id
(`floci:override-id`) then inherited the dead pool's providers, ProviderDetails
client_secret included. Pool deletion now removes them the way it already
removes groups.

UpdateIdentityProvider mutated the instance the store handed back, so two
concurrent updates could interleave into a state matching neither request. It
now writes a copy, which makes the losing update simply lose — what AWS does.

* fix(cognito): serialise identity provider mutations

UpdateIdentityProvider is a read-modify-write: it copies the stored provider,
applies only the members the request supplied and writes the whole record back.
Two overlapping updates copied the same base, so the later write restored the
other's omitted members to their stale values and silently dropped an update.

Live Cognito merges omitted members rather than clearing them, and applies that
merge atomically, so both updates survive there. One lock now guards every
mutating path, since create (check-then-put) and delete (check-then-act) carry
the same race, matching the existing identityLinkLock idiom.

The regression test runs two writers touching different optional members across
25 rounds; it fails on the first round with the lock reverted.

* fix(cognito): guard the pool deletion provider cascade with the same lock

DeleteUserPool clears a pool's identity providers outside identityProviderLock,
so a create or update interleaving with the cascade could reinstate a provider
for a pool that is going away. It now takes the same lock as the mutations it
races, closing the last unguarded path in that set.

* fix(cognito): recheck the pool under the lock when creating a provider

CreateIdentityProvider validated the pool before taking identityProviderLock and
never rechecked it, so a DeleteUserPool whose cascade ran in between left the
create writing a provider for a pool that no longer exists. It now reasserts the
pool inside the lock, immediately before the duplicate check and the write.

UpdateIdentityProvider needs no equivalent: the cascade deletes the provider, so
its own lookup throws ResourceNotFoundException. The outer validation stays where
it is to keep error ordering unchanged for ordinary single-request calls.
This commit is contained in:
Brian Taylor authored and GitHub committed 2026-09-02 12:00:26 -04:00
1 parent 1e4e8b9ee8
commit 0a3bc030f6
8 files changed
+1145 -2

No files matched your search

@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
import io.github.hectorvent.floci.services.cognito.model.ResourceServer;
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
@@ -61,6 +62,11 @@ public class CognitoJsonHandler {
case "ListResourceServers" -> handleListResourceServers(request);
case "UpdateResourceServer" -> handleUpdateResourceServer(request);
case "DeleteResourceServer" -> handleDeleteResourceServer(request);
case "CreateIdentityProvider" -> handleCreateIdentityProvider(request);
case "DescribeIdentityProvider" -> handleDescribeIdentityProvider(request);
case "ListIdentityProviders" -> handleListIdentityProviders(request);
case "UpdateIdentityProvider" -> handleUpdateIdentityProvider(request);
case "DeleteIdentityProvider" -> handleDeleteIdentityProvider(request);
case "CreateUserPoolDomain" -> handleCreateUserPoolDomain(request);
case "DescribeUserPoolDomain" -> handleDescribeUserPoolDomain(request);
case "DeleteUserPoolDomain" -> handleDeleteUserPoolDomain(request);
@@ -355,6 +361,59 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleCreateIdentityProvider(JsonNode request) {
IdentityProvider provider = service.createIdentityProvider(
request.path("UserPoolId").asText(),
request.path("ProviderName").asText(),
request.path("ProviderType").asText(null),
readStringMap(request, "ProviderDetails"),
readStringMap(request, "AttributeMapping"),
readStringList(request, "IdpIdentifiers")
);
ObjectNode response = objectMapper.createObjectNode();
response.set("IdentityProvider", identityProviderToNode(provider, request.has("IdpIdentifiers")));
return Response.ok(response).build();
}
private Response handleDescribeIdentityProvider(JsonNode request) {
IdentityProvider provider = service.describeIdentityProvider(
request.path("UserPoolId").asText(),
request.path("ProviderName").asText()
);
ObjectNode response = objectMapper.createObjectNode();
response.set("IdentityProvider", identityProviderToNode(provider, true));
return Response.ok(response).build();
}
private Response handleListIdentityProviders(JsonNode request) {
List<IdentityProvider> providers = service.listIdentityProviders(request.path("UserPoolId").asText());
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("Providers");
providers.forEach(provider -> items.add(providerDescriptionToNode(provider)));
return Response.ok(response).build();
}
private Response handleUpdateIdentityProvider(JsonNode request) {
IdentityProvider provider = service.updateIdentityProvider(
request.path("UserPoolId").asText(),
request.path("ProviderName").asText(),
readStringMap(request, "ProviderDetails"),
readStringMap(request, "AttributeMapping"),
readStringList(request, "IdpIdentifiers")
);
ObjectNode response = objectMapper.createObjectNode();
response.set("IdentityProvider", identityProviderToNode(provider, request.has("IdpIdentifiers")));
return Response.ok(response).build();
}
private Response handleDeleteIdentityProvider(JsonNode request) {
service.deleteIdentityProvider(
request.path("UserPoolId").asText(),
request.path("ProviderName").asText()
);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleCreateUserPoolDomain(JsonNode request) {
JsonNode customDomainConfigNode = request.path("CustomDomainConfig");
Map<String, Object> customDomainConfig = customDomainConfigNode.isObject()
@@ -1074,6 +1133,58 @@ public class CognitoJsonHandler {
return node;
}
/**
* {@code IdpIdentifiers} is echoed only when the caller supplied the member: AWS omits it
* from CreateIdentityProvider and UpdateIdentityProvider responses otherwise, whatever the
* stored value, while DescribeIdentityProvider always returns it.
*/
private ObjectNode identityProviderToNode(IdentityProvider provider, boolean includeIdpIdentifiers) {
ObjectNode node = objectMapper.createObjectNode();
node.put("UserPoolId", provider.getUserPoolId());
node.put("ProviderName", provider.getProviderName());
node.put("ProviderType", provider.getProviderType());
ObjectNode details = node.putObject("ProviderDetails");
provider.getProviderDetails().forEach(details::put);
ObjectNode mapping = node.putObject("AttributeMapping");
provider.getAttributeMapping().forEach(mapping::put);
if (includeIdpIdentifiers) {
ArrayNode identifiers = node.putArray("IdpIdentifiers");
provider.getIdpIdentifiers().forEach(identifiers::add);
}
node.put("CreationDate", provider.getCreationDate());
node.put("LastModifiedDate", provider.getLastModifiedDate());
return node;
}
private ObjectNode providerDescriptionToNode(IdentityProvider provider) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ProviderName", provider.getProviderName());
node.put("ProviderType", provider.getProviderType());
node.put("LastModifiedDate", provider.getLastModifiedDate());
node.put("CreationDate", provider.getCreationDate());
return node;
}
private Map<String, String> readStringMap(JsonNode request, String member) {
JsonNode node = request.get(member);
if (node == null || !node.isObject()) {
return null;
}
Map<String, String> values = new LinkedHashMap<>();
node.fields().forEachRemaining(entry -> values.put(entry.getKey(), entry.getValue().asText()));
return values;
}
private List<String> readStringList(JsonNode request, String member) {
JsonNode node = request.get(member);
if (node == null || !node.isArray()) {
return null;
}
List<String> values = new ArrayList<>();
node.forEach(item -> values.add(item.asText()));
return values;
}
private List<ResourceServerScope> parseScopes(JsonNode scopesNode) {
if (scopesNode == null || !scopesNode.isArray()) {
return List.of();
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
import io.github.hectorvent.floci.services.cognito.model.ResourceServer;
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo;
@@ -112,6 +113,7 @@ public class CognitoService implements ResourceProvider {
private final StorageBackend<String, UserPoolClient> clientStore;
private final StorageBackend<String, ResourceServer> resourceServerStore;
private final StorageBackend<String, UserPoolDomain> domainStore;
private final StorageBackend<String, IdentityProvider> identityProviderStore;
private final StorageBackend<String, CognitoUser> userStore;
private final StorageBackend<String, CognitoGroup> groupStore;
private final StorageBackend<String, RevokedTokenInfo> revokedTokenStore;
@@ -137,6 +139,8 @@ public class CognitoService implements ResourceProvider {
new TypeReference<Map<String, ResourceServer>>() {}),
storageFactory.create("cognito", "cognito-domains.json",
new TypeReference<Map<String, UserPoolDomain>>() {}),
storageFactory.create("cognito", "cognito-identity-providers.json",
new TypeReference<Map<String, IdentityProvider>>() {}),
storageFactory.create("cognito", "cognito-users.json",
new TypeReference<Map<String, CognitoUser>>() {}),
storageFactory.create("cognito", "cognito-groups.json",
@@ -161,7 +165,7 @@ public class CognitoService implements ResourceProvider {
RegionResolver regionResolver,
LambdaService lambdaService) {
this(poolStore, clientStore, resourceServerStore, new InMemoryStorage<>(),
userStore, groupStore, revokedTokenStore, baseUrl,
new InMemoryStorage<>(), userStore, groupStore, revokedTokenStore, baseUrl,
regionResolver, lambdaService, null, null);
}
@@ -169,6 +173,7 @@ public class CognitoService implements ResourceProvider {
StorageBackend<String, UserPoolClient> clientStore,
StorageBackend<String, ResourceServer> resourceServerStore,
StorageBackend<String, UserPoolDomain> domainStore,
StorageBackend<String, IdentityProvider> identityProviderStore,
StorageBackend<String, CognitoUser> userStore,
StorageBackend<String, CognitoGroup> groupStore,
StorageBackend<String, RevokedTokenInfo> revokedTokenStore,
@@ -180,6 +185,7 @@ public class CognitoService implements ResourceProvider {
this.clientStore = clientStore;
this.resourceServerStore = resourceServerStore;
this.domainStore = domainStore;
this.identityProviderStore = identityProviderStore;
this.userStore = userStore;
this.groupStore = groupStore;
this.revokedTokenStore = revokedTokenStore;
@@ -460,7 +466,13 @@ public class CognitoService implements ResourceProvider {
String prefix = id + "::";
groupStore.scan(k -> k.startsWith(prefix))
.forEach(g -> groupStore.delete(groupKey(id, g.getGroupName())));
poolStore.delete(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) {
identityProviderStore.scan(k -> k.startsWith(prefix))
.forEach(p -> identityProviderStore.delete(identityProviderKey(id, p.getProviderName())));
poolStore.delete(id);
}
}
// ──────────────────────────── User Pool Clients ────────────────────────────
@@ -877,6 +889,129 @@ public class CognitoService implements ResourceProvider {
resourceServerStore.delete(resourceServerKey(userPoolId, identifier));
}
// ──────────────────────────── Identity Providers ────────────────────────────
private static final Set<String> PROVIDER_TYPES =
Set.of("Facebook", "SAML", "SignInWithApple", "LoginWithAmazon", "OIDC", "Google");
public IdentityProvider createIdentityProvider(String userPoolId, String providerName, String providerType,
Map<String, String> providerDetails,
Map<String, String> attributeMapping,
List<String> idpIdentifiers) {
describeUserPool(userPoolId);
if (providerName == null || providerName.isBlank()) {
throw new AwsException("InvalidParameterException", "ProviderName is required", 400);
}
validateProviderType(providerType);
String key = identityProviderKey(userPoolId, providerName);
synchronized (identityProviderLock) {
// The pool was checked before the lock, so a DeleteUserPool that ran its
// cascade in between would leave this create writing a provider for a pool
// that no longer exists. Update needs no equivalent recheck: the cascade
// removes the provider, so its own lookup throws.
describeUserPool(userPoolId);
if (identityProviderStore.get(key).isPresent()) {
throw new AwsException("DuplicateProviderException",
providerName + " already exists for tenant " + userPoolId + ".", 400);
}
IdentityProvider provider = new IdentityProvider();
provider.setUserPoolId(userPoolId);
provider.setProviderName(providerName);
provider.setProviderType(providerType);
provider.setProviderDetails(copyOrEmpty(providerDetails));
// AWS supplies a default mapping only when the member is absent; an explicitly
// empty map is stored as given.
provider.setAttributeMapping(attributeMapping == null
? new LinkedHashMap<>(Map.of("username", "sub"))
: new LinkedHashMap<>(attributeMapping));
provider.setIdpIdentifiers(idpIdentifiers == null
? new ArrayList<>() : new ArrayList<>(idpIdentifiers));
identityProviderStore.put(key, provider);
return provider;
}
}
public IdentityProvider describeIdentityProvider(String userPoolId, String providerName) {
describeUserPool(userPoolId);
return identityProviderStore.get(identityProviderKey(userPoolId, providerName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Identity provider " + providerName + " for tenantId " + userPoolId
+ " does not exist.", 400));
}
public List<IdentityProvider> listIdentityProviders(String userPoolId) {
describeUserPool(userPoolId);
String prefix = userPoolId + "::";
return identityProviderStore.scan(k -> k.startsWith(prefix));
}
/**
* Members the request omits are left as they were: AWS preserves the stored
* {@code AttributeMapping} and {@code IdpIdentifiers} rather than clearing them, and an
* explicitly empty map or list is what clears them.
*/
public IdentityProvider updateIdentityProvider(String userPoolId, String providerName,
Map<String, String> providerDetails,
Map<String, String> attributeMapping,
List<String> idpIdentifiers) {
describeUserPool(userPoolId);
String key = identityProviderKey(userPoolId, providerName);
synchronized (identityProviderLock) {
IdentityProvider provider = copyOf(identityProviderStore.get(key)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Identity provider " + providerName + " in User Pool " + userPoolId
+ " does not exist.", 400)));
if (providerDetails != null) {
provider.setProviderDetails(new LinkedHashMap<>(providerDetails));
}
if (attributeMapping != null) {
provider.setAttributeMapping(new LinkedHashMap<>(attributeMapping));
}
if (idpIdentifiers != null) {
provider.setIdpIdentifiers(new ArrayList<>(idpIdentifiers));
}
provider.setLastModifiedDate(System.currentTimeMillis() / 1000L);
identityProviderStore.put(key, provider);
return provider;
}
}
public void deleteIdentityProvider(String userPoolId, String providerName) {
synchronized (identityProviderLock) {
describeIdentityProvider(userPoolId, providerName);
identityProviderStore.delete(identityProviderKey(userPoolId, providerName));
}
}
private void validateProviderType(String providerType) {
if (providerType == null || !PROVIDER_TYPES.contains(providerType)) {
throw new AwsException("InvalidParameterException",
"1 validation error detected: Value '" + providerType + "' at 'providerType' failed to "
+ "satisfy constraint: Member must satisfy enum value set: "
+ "[Facebook, SAML, SignInWithApple, LoginWithAmazon, OIDC, Google]", 400);
}
}
private Map<String, String> copyOrEmpty(Map<String, String> source) {
return source == null ? new LinkedHashMap<>() : new LinkedHashMap<>(source);
}
private IdentityProvider copyOf(IdentityProvider source) {
IdentityProvider copy = new IdentityProvider();
copy.setUserPoolId(source.getUserPoolId());
copy.setProviderName(source.getProviderName());
copy.setProviderType(source.getProviderType());
copy.setProviderDetails(new LinkedHashMap<>(source.getProviderDetails()));
copy.setAttributeMapping(new LinkedHashMap<>(source.getAttributeMapping()));
copy.setIdpIdentifiers(new ArrayList<>(source.getIdpIdentifiers()));
copy.setCreationDate(source.getCreationDate());
copy.setLastModifiedDate(source.getLastModifiedDate());
return copy;
}
// ──────────────────────────── User Pool Domains ────────────────────────────
/**
@@ -1388,6 +1523,12 @@ public class CognitoService implements ResourceProvider {
// Serializes adminLinkProviderForUser's check-then-write.
private final Object identityLinkLock = new Object();
// Identity provider mutations are read-modify-write (update) and check-then-act
// (create, delete). AWS applies each of those atomically, so two overlapping
// updates that touch different optional members both survive there. Guarding
// every mutating path with one lock reproduces that.
private final Object identityProviderLock = new Object();
public void adminLinkProviderForUser(String userPoolId, String destinationUsername,
String sourceProviderName, String sourceUserId) {
if (destinationUsername == null || destinationUsername.isEmpty()) {
@@ -3210,6 +3351,10 @@ public class CognitoService implements ResourceProvider {
return userPoolId + "::" + identifier;
}
private String identityProviderKey(String userPoolId, String providerName) {
return userPoolId + "::" + providerName;
}
private String escapeJson(String value) {
return value
.replace("\\", "\\\\")
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.cognito.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class IdentityProvider {
private String userPoolId;
private String providerName;
private String providerType;
private Map<String, String> providerDetails = new LinkedHashMap<>();
private Map<String, String> attributeMapping = new LinkedHashMap<>();
private List<String> idpIdentifiers = new ArrayList<>();
private long creationDate;
private long lastModifiedDate;
public IdentityProvider() {
long now = System.currentTimeMillis() / 1000L;
this.creationDate = now;
this.lastModifiedDate = now;
}
public String getUserPoolId() { return userPoolId; }
public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; }
public String getProviderName() { return providerName; }
public void setProviderName(String providerName) { this.providerName = providerName; }
public String getProviderType() { return providerType; }
public void setProviderType(String providerType) { this.providerType = providerType; }
public Map<String, String> getProviderDetails() { return providerDetails; }
public void setProviderDetails(Map<String, String> providerDetails) { this.providerDetails = providerDetails; }
public Map<String, String> getAttributeMapping() { return attributeMapping; }
public void setAttributeMapping(Map<String, String> attributeMapping) { this.attributeMapping = attributeMapping; }
public List<String> getIdpIdentifiers() { return idpIdentifiers; }
public void setIdpIdentifiers(List<String> idpIdentifiers) { this.idpIdentifiers = idpIdentifiers; }
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
public long getLastModifiedDate() { return lastModifiedDate; }
public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
}