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

@@ -0,0 +1,185 @@
/**
* Cognito identity provider configuration compatibility tests.
*
* The response shapes asserted here were measured against the live Cognito API:
* `IdpIdentifiers` is echoed by CreateIdentityProvider and UpdateIdentityProvider
* only when the request supplied the member, whatever the stored value, while
* DescribeIdentityProvider always returns it. Members a request omits are
* preserved rather than cleared.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import {
CognitoIdentityProviderClient,
CreateUserPoolCommand,
DeleteUserPoolCommand,
CreateIdentityProviderCommand,
DescribeIdentityProviderCommand,
ListIdentityProvidersCommand,
UpdateIdentityProviderCommand,
DeleteIdentityProviderCommand,
IdentityProviderTypeType,
} from '@aws-sdk/client-cognito-identity-provider';
import { makeClient, uniqueName } from './setup';
const OIDC_DETAILS = {
client_id: 'node-compat-client',
client_secret: 'node-compat-secret',
attributes_request_method: 'GET',
oidc_issuer: 'https://issuer.example.com',
authorize_scopes: 'openid',
};
describe('Cognito identity providers', () => {
let cognito: CognitoIdentityProviderClient;
let poolId: string;
beforeAll(async () => {
cognito = makeClient(CognitoIdentityProviderClient);
const pool = await cognito.send(
new CreateUserPoolCommand({ PoolName: uniqueName('idp-pool') })
);
poolId = pool.UserPool!.Id!;
});
afterAll(async () => {
if (poolId) {
await cognito.send(new DeleteUserPoolCommand({ UserPoolId: poolId }));
}
});
it('defaults AttributeMapping and omits IdpIdentifiers on create', async () => {
const created = await cognito.send(
new CreateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidc',
ProviderType: IdentityProviderTypeType.OIDC,
ProviderDetails: { ...OIDC_DETAILS },
})
);
expect(created.IdentityProvider!.AttributeMapping).toEqual({ username: 'sub' });
expect(created.IdentityProvider!.IdpIdentifiers).toBeUndefined();
const described = await cognito.send(
new DescribeIdentityProviderCommand({ UserPoolId: poolId, ProviderName: 'NodeOidc' })
);
expect(described.IdentityProvider!.IdpIdentifiers).toEqual([]);
expect(described.IdentityProvider!.ProviderDetails!.client_id).toBe('node-compat-client');
await cognito.send(
new DeleteIdentityProviderCommand({ UserPoolId: poolId, ProviderName: 'NodeOidc' })
);
});
it('preserves members the update request omits', async () => {
await cognito.send(
new CreateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcAliased',
ProviderType: IdentityProviderTypeType.OIDC,
ProviderDetails: { ...OIDC_DETAILS },
AttributeMapping: { email: 'email', username: 'sub' },
IdpIdentifiers: ['node-alias'],
})
);
const updated = await cognito.send(
new UpdateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcAliased',
ProviderDetails: { ...OIDC_DETAILS },
})
);
expect(updated.IdentityProvider!.IdpIdentifiers).toBeUndefined();
const described = await cognito.send(
new DescribeIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcAliased',
})
);
expect(described.IdentityProvider!.IdpIdentifiers).toEqual(['node-alias']);
expect(described.IdentityProvider!.AttributeMapping).toEqual({
email: 'email',
username: 'sub',
});
await cognito.send(
new DeleteIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcAliased',
})
);
});
it('lists providers as summaries without provider details', async () => {
await cognito.send(
new CreateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcListed',
ProviderType: IdentityProviderTypeType.OIDC,
ProviderDetails: { ...OIDC_DETAILS },
})
);
const listed = await cognito.send(new ListIdentityProvidersCommand({ UserPoolId: poolId }));
expect(listed.Providers).toHaveLength(1);
expect(listed.Providers![0].ProviderName).toBe('NodeOidcListed');
expect(listed.Providers![0].ProviderType).toBe('OIDC');
expect(listed.Providers![0].CreationDate).toBeInstanceOf(Date);
expect(listed.Providers![0]).not.toHaveProperty('ProviderDetails');
await cognito.send(
new DeleteIdentityProviderCommand({ UserPoolId: poolId, ProviderName: 'NodeOidcListed' })
);
const empty = await cognito.send(new ListIdentityProvidersCommand({ UserPoolId: poolId }));
expect(empty.Providers).toEqual([]);
});
it('rejects a duplicate provider name and an unknown provider type', async () => {
await cognito.send(
new CreateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcDuplicate',
ProviderType: IdentityProviderTypeType.OIDC,
ProviderDetails: { ...OIDC_DETAILS },
})
);
// The SDK maps the wire `__type` onto `error.name` and puts the AWS text in
// `message`, so the exception has to be matched on the name.
await expect(
cognito.send(
new CreateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcDuplicate',
ProviderType: IdentityProviderTypeType.OIDC,
ProviderDetails: { ...OIDC_DETAILS },
})
)
).rejects.toMatchObject({ name: 'DuplicateProviderException' });
await expect(
cognito.send(
new CreateIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeBogus',
ProviderType: 'NotARealType' as IdentityProviderTypeType,
ProviderDetails: { client_id: 'x' },
})
)
).rejects.toMatchObject({
name: 'InvalidParameterException',
message: expect.stringContaining('Member must satisfy enum value set'),
});
await cognito.send(
new DeleteIdentityProviderCommand({
UserPoolId: poolId,
ProviderName: 'NodeOidcDuplicate',
})
);
});
});
@@ -360,3 +360,132 @@ class TestCognitoDescribeUserPoolStandardAttributes:
assert sub["Mutable"] is False
finally:
cognito_client.delete_user_pool(UserPoolId=pool_id)
class TestCognitoIdentityProvider:
"""Test Cognito identity provider configuration operations.
The response shapes asserted here were measured against the live Cognito API.
``IdpIdentifiers`` is echoed by CreateIdentityProvider only when the request
supplied it, while DescribeIdentityProvider always returns it.
"""
OIDC_DETAILS = {
"client_id": "pytest-client",
"client_secret": "pytest-secret",
"attributes_request_method": "GET",
"oidc_issuer": "https://issuer.example.com",
"authorize_scopes": "openid",
}
@pytest.fixture
def pool_id(self, cognito_client, unique_name):
response = cognito_client.create_user_pool(PoolName=f"pytest-idp-pool-{unique_name}")
pool_id = response["UserPool"]["Id"]
yield pool_id
cognito_client.delete_user_pool(UserPoolId=pool_id)
def test_create_defaults_attribute_mapping_and_omits_idp_identifiers(
self, cognito_client, pool_id
):
"""Create defaults AttributeMapping and omits IdpIdentifiers when not supplied."""
provider = cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
)["IdentityProvider"]
assert provider["ProviderType"] == "OIDC"
assert provider["AttributeMapping"] == {"username": "sub"}
assert "IdpIdentifiers" not in provider
def test_describe_always_returns_idp_identifiers(self, cognito_client, pool_id):
"""Describe returns IdpIdentifiers even when the stored list is empty."""
cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
)
provider = cognito_client.describe_identity_provider(
UserPoolId=pool_id, ProviderName="PytestOidc"
)["IdentityProvider"]
assert provider["IdpIdentifiers"] == []
assert provider["ProviderDetails"]["client_id"] == "pytest-client"
def test_update_preserves_members_the_request_omits(self, cognito_client, pool_id):
"""Omitting AttributeMapping/IdpIdentifiers on update leaves them unchanged."""
cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
AttributeMapping={"email": "email", "username": "sub"},
IdpIdentifiers=["pytest-alias"],
)
cognito_client.update_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderDetails=dict(self.OIDC_DETAILS),
)
provider = cognito_client.describe_identity_provider(
UserPoolId=pool_id, ProviderName="PytestOidc"
)["IdentityProvider"]
assert provider["IdpIdentifiers"] == ["pytest-alias"]
assert provider["AttributeMapping"] == {"email": "email", "username": "sub"}
def test_list_returns_summaries_without_provider_details(self, cognito_client, pool_id):
"""ListIdentityProviders returns summaries, never provider credentials."""
cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
)
providers = cognito_client.list_identity_providers(UserPoolId=pool_id)["Providers"]
assert len(providers) == 1
assert providers[0]["ProviderName"] == "PytestOidc"
assert providers[0]["ProviderType"] == "OIDC"
assert "ProviderDetails" not in providers[0]
def test_create_rejects_duplicate_provider_name(self, cognito_client, pool_id):
"""A second provider with the same name raises DuplicateProviderException."""
cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
)
with pytest.raises(cognito_client.exceptions.DuplicateProviderException):
cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
)
def test_delete_removes_the_provider(self, cognito_client, pool_id):
"""Delete removes the provider and a second delete raises."""
cognito_client.create_identity_provider(
UserPoolId=pool_id,
ProviderName="PytestOidc",
ProviderType="OIDC",
ProviderDetails=dict(self.OIDC_DETAILS),
)
cognito_client.delete_identity_provider(UserPoolId=pool_id, ProviderName="PytestOidc")
assert cognito_client.list_identity_providers(UserPoolId=pool_id)["Providers"] == []
with pytest.raises(cognito_client.exceptions.ResourceNotFoundException):
cognito_client.delete_identity_provider(
UserPoolId=pool_id, ProviderName="PytestOidc"
)
+32
View File
@@ -56,6 +56,38 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource`
| UpdateResourceServer | Updates a resource server's name and scopes. |
| DeleteResourceServer | Deletes a resource server from a user pool. |
### Identity Providers
| Action | Description |
|--------|-------------|
| CreateIdentityProvider | Registers a federated identity provider on a user pool. |
| DescribeIdentityProvider | Returns a registered identity provider. |
| ListIdentityProviders | Lists a user pool's providers as name/type/date summaries. |
| UpdateIdentityProvider | Updates a provider's details, attribute mapping or identifiers. |
| DeleteIdentityProvider | Deletes an identity provider from a user pool. |
Providers are stored configuration only. Floci does not perform the federated sign-in
flow: there is no `/oauth2/authorize` or `/oauth2/idpresponse` endpoint, so a registered
provider cannot be used to authenticate. This covers infrastructure tooling that creates
and reads provider configuration, not federated login.
Two deliberate divergences from AWS, both consequences of not calling out to a third
party:
- **No create-time validation of `ProviderDetails`.** AWS resolves an OIDC provider's
`oidc_issuer` discovery document while handling `CreateIdentityProvider`, and rejects
the call when it is unreachable. Floci stores `ProviderDetails` opaquely and makes no
outbound request, so it also does not enforce the per-provider-type required keys.
- **No injected provider defaults.** AWS adds keys such as
`attributes_url_add_attributes` to an OIDC provider's stored details; Floci returns
only what was supplied.
`AttributeMapping` and `IdpIdentifiers` follow AWS's update semantics: a member the
request omits is left unchanged, and an explicitly empty map or list is what clears it.
`IdpIdentifiers` is echoed by `CreateIdentityProvider` and `UpdateIdentityProvider` only
when the request supplied it, whatever the stored value, while `DescribeIdentityProvider`
always returns it.
### User Pool Domains
| Action | Description |
@@ -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; }
}
@@ -0,0 +1,462 @@
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 java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Covers CreateIdentityProvider/DescribeIdentityProvider/ListIdentityProviders/
* UpdateIdentityProvider/DeleteIdentityProvider.
*
* <p>The response and update semantics asserted here were measured against the live
* Cognito API; they are not derivable from the API reference. In particular
* {@code IdpIdentifiers} is echoed by create and update only when the request supplied
* the member, and members a request omits are preserved rather than cleared.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CognitoIdentityProviderIntegrationTest {
private static String poolId;
private static final String OIDC_DETAILS = """
{
"client_id": "idp-test-client",
"client_secret": "idp-test-secret",
"attributes_request_method": "GET",
"oidc_issuer": "https://issuer.example.com",
"authorize_scopes": "openid"
}
""";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createPool() throws Exception {
JsonNode response = cognitoJson("CreateUserPool", """
{
"PoolName": "IdentityProviderTestPool"
}
""");
poolId = response.path("UserPool").path("Id").asText();
}
@Test
@Order(2)
void createRejectsUnknownProviderType() {
cognitoAction("CreateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "Bogus",
"ProviderType": "NotARealType",
"ProviderDetails": {"client_id": "x"}
}
""".formatted(poolId))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", equalTo(
"1 validation error detected: Value 'NotARealType' at 'providerType' failed to "
+ "satisfy constraint: Member must satisfy enum value set: "
+ "[Facebook, SAML, SignInWithApple, LoginWithAmazon, OIDC, Google]"));
}
@Test
@Order(3)
void createDefaultsAttributeMappingAndOmitsIdpIdentifiers() throws Exception {
JsonNode provider = cognitoJson("CreateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidc",
"ProviderType": "OIDC",
"ProviderDetails": %s
}
""".formatted(poolId, OIDC_DETAILS)).path("IdentityProvider");
assertEquals("TestOidc", provider.path("ProviderName").asText());
assertEquals("OIDC", provider.path("ProviderType").asText());
assertEquals("idp-test-client", provider.path("ProviderDetails").path("client_id").asText());
assertEquals("sub", provider.path("AttributeMapping").path("username").asText());
assertEquals(1, provider.path("AttributeMapping").size());
assertTrue(provider.path("IdpIdentifiers").isMissingNode(),
"AWS omits IdpIdentifiers from a create response that did not supply it");
}
@Test
@Order(4)
void describeAlwaysReturnsIdpIdentifiers() throws Exception {
JsonNode provider = cognitoJson("DescribeIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidc"
}
""".formatted(poolId)).path("IdentityProvider");
assertTrue(provider.path("IdpIdentifiers").isArray(),
"Describe returns IdpIdentifiers even when it is empty");
assertEquals(0, provider.path("IdpIdentifiers").size());
assertEquals(poolId, provider.path("UserPoolId").asText());
}
@Test
@Order(5)
void createRejectsDuplicateProviderName() {
cognitoAction("CreateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidc",
"ProviderType": "OIDC",
"ProviderDetails": %s
}
""".formatted(poolId, OIDC_DETAILS))
.then()
.statusCode(400)
.body("__type", equalTo("DuplicateProviderException"))
.body("message", equalTo("TestOidc already exists for tenant " + poolId + "."));
}
@Test
@Order(6)
void createEchoesIdpIdentifiersWhenSupplied() throws Exception {
JsonNode provider = cognitoJson("CreateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased",
"ProviderType": "OIDC",
"ProviderDetails": %s,
"AttributeMapping": {"email": "email", "username": "sub"},
"IdpIdentifiers": ["alias-keep"]
}
""".formatted(poolId, OIDC_DETAILS)).path("IdentityProvider");
assertEquals(1, provider.path("IdpIdentifiers").size());
assertEquals("alias-keep", provider.path("IdpIdentifiers").get(0).asText());
assertEquals("email", provider.path("AttributeMapping").path("email").asText());
}
@Test
@Order(7)
void updateOmittingMembersPreservesThem() throws Exception {
JsonNode updated = cognitoJson("UpdateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased",
"ProviderDetails": %s
}
""".formatted(poolId, OIDC_DETAILS)).path("IdentityProvider");
assertTrue(updated.path("IdpIdentifiers").isMissingNode(),
"the update response omits IdpIdentifiers regardless of the stored value");
JsonNode described = cognitoJson("DescribeIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased"
}
""".formatted(poolId)).path("IdentityProvider");
assertEquals(1, described.path("IdpIdentifiers").size(),
"omitting IdpIdentifiers preserves the stored value");
assertEquals("alias-keep", described.path("IdpIdentifiers").get(0).asText());
assertEquals("email", described.path("AttributeMapping").path("email").asText());
}
@Test
@Order(8)
void updateWithEmptyCollectionsClearsThem() throws Exception {
JsonNode updated = cognitoJson("UpdateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased",
"ProviderDetails": %s,
"AttributeMapping": {},
"IdpIdentifiers": []
}
""".formatted(poolId, OIDC_DETAILS)).path("IdentityProvider");
assertTrue(updated.path("IdpIdentifiers").isArray(),
"a supplied IdpIdentifiers member is echoed even when empty");
assertEquals(0, updated.path("IdpIdentifiers").size());
assertEquals(0, updated.path("AttributeMapping").size());
JsonNode described = cognitoJson("DescribeIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased"
}
""".formatted(poolId)).path("IdentityProvider");
assertEquals(0, described.path("AttributeMapping").size());
assertEquals(0, described.path("IdpIdentifiers").size());
}
@Test
@Order(9)
void listReturnsSummariesWithoutProviderDetails() throws Exception {
JsonNode providers = cognitoJson("ListIdentityProviders", """
{
"UserPoolId": "%s"
}
""".formatted(poolId)).path("Providers");
assertEquals(2, providers.size());
for (JsonNode provider : providers) {
assertTrue(provider.hasNonNull("ProviderName"));
assertTrue(provider.hasNonNull("ProviderType"));
assertTrue(provider.hasNonNull("CreationDate"));
assertTrue(provider.hasNonNull("LastModifiedDate"));
assertFalse(provider.has("ProviderDetails"),
"ListIdentityProviders returns summaries only, never provider credentials");
assertFalse(provider.has("AttributeMapping"));
}
}
@Test
@Order(10)
void describeAndUpdateReportMissingProvidersDifferently() {
cognitoAction("DescribeIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "NoSuchProvider"
}
""".formatted(poolId))
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("message", equalTo(
"Identity provider NoSuchProvider for tenantId " + poolId + " does not exist."));
cognitoAction("UpdateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "NoSuchProvider",
"ProviderDetails": %s
}
""".formatted(poolId, OIDC_DETAILS))
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("message", equalTo(
"Identity provider NoSuchProvider in User Pool " + poolId + " does not exist."));
}
@Test
@Order(11)
void deleteRemovesProviderAndIsNotIdempotent() throws Exception {
cognitoAction("DeleteIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased"
}
""".formatted(poolId))
.then()
.statusCode(200);
cognitoAction("DeleteIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidcAliased"
}
""".formatted(poolId))
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
cognitoAction("DeleteIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "TestOidc"
}
""".formatted(poolId))
.then()
.statusCode(200);
assertEquals(0, cognitoJson("ListIdentityProviders", """
{
"UserPoolId": "%s"
}
""".formatted(poolId)).path("Providers").size());
}
/**
* A pool recreated on a pinned id must not inherit the dead pool's providers: their
* ProviderDetails carry the client_secret.
*/
@Test
@Order(12)
void deletingAPoolRemovesItsIdentityProviders() throws Exception {
String pinnedId = "us-east-1_idporph1";
cognitoAction("CreateUserPool", """
{
"PoolName": "IdpOrphanPool",
"UserPoolTags": {"floci:override-id": "%s"}
}
""".formatted(pinnedId))
.then()
.statusCode(200);
cognitoAction("CreateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "OrphanOidc",
"ProviderType": "OIDC",
"ProviderDetails": %s
}
""".formatted(pinnedId, OIDC_DETAILS))
.then()
.statusCode(200);
cognitoAction("DeleteUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(pinnedId))
.then()
.statusCode(200);
cognitoAction("CreateUserPool", """
{
"PoolName": "IdpOrphanPoolAgain",
"UserPoolTags": {"floci:override-id": "%s"}
}
""".formatted(pinnedId))
.then()
.statusCode(200);
assertEquals(0, cognitoJson("ListIdentityProviders", """
{
"UserPoolId": "%s"
}
""".formatted(pinnedId)).path("Providers").size(),
"a recreated pool must not inherit the deleted pool's providers");
cognitoAction("DeleteUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(pinnedId))
.then()
.statusCode(200);
}
/**
* Two overlapping updates that touch different optional members must both survive.
*
* <p>Update is a read-modify-write: it copies the stored provider, applies only the
* members the request supplied and writes the whole record back. Without a lock both
* callers copy the same base, so the later write restores the other's omitted members
* to their stale values and silently drops an update.
*
* <p>Measured against live Cognito in ap-southeast-1: an update that omits
* {@code AttributeMapping} and {@code IdpIdentifiers} leaves both intact, so the
* service merges, and it does so atomically. Reverting the lock in
* {@code CognitoService.updateIdentityProvider} makes this test fail.
*/
@Test
@Order(13)
void concurrentUpdatesOfDifferentMembersBothSurvive() throws Exception {
String racePool = cognitoJson("CreateUserPool", """
{
"PoolName": "idp-concurrency-pool"
}
""").path("UserPool").path("Id").asText();
cognitoAction("CreateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "RaceOidc",
"ProviderType": "OIDC",
"ProviderDetails": %s,
"AttributeMapping": {"username": "sub"}
}
""".formatted(racePool, OIDC_DETAILS))
.then()
.statusCode(200);
ExecutorService threads = Executors.newFixedThreadPool(2);
try {
for (int round = 0; round < 25; round++) {
String attribute = "email" + round;
String identifier = "ident" + round;
CyclicBarrier start = new CyclicBarrier(2);
Future<?> mappingWriter = threads.submit(() -> {
start.await();
return cognitoAction("UpdateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "RaceOidc",
"AttributeMapping": {"username": "sub", "%s": "%s"}
}
""".formatted(racePool, attribute, attribute));
});
Future<?> identifierWriter = threads.submit(() -> {
start.await();
return cognitoAction("UpdateIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "RaceOidc",
"IdpIdentifiers": ["%s"]
}
""".formatted(racePool, identifier));
});
mappingWriter.get(30, TimeUnit.SECONDS);
identifierWriter.get(30, TimeUnit.SECONDS);
JsonNode described = cognitoJson("DescribeIdentityProvider", """
{
"UserPoolId": "%s",
"ProviderName": "RaceOidc"
}
""".formatted(racePool)).path("IdentityProvider");
assertTrue(described.path("AttributeMapping").has(attribute),
"round " + round + ": the concurrent IdpIdentifiers update discarded "
+ "the AttributeMapping write");
assertEquals(identifier, described.path("IdpIdentifiers").path(0).asText(),
"round " + round + ": the concurrent AttributeMapping update discarded "
+ "the IdpIdentifiers write");
}
} finally {
threads.shutdownNow();
cognitoAction("DeleteUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(racePool));
}
}
@Test
@Order(14)
void deletePool() {
cognitoAction("DeleteUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(poolId))
.then()
.statusCode(200);
}
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
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.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
@@ -1385,6 +1386,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
@@ -1423,6 +1425,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
@@ -2602,6 +2605,29 @@ class CognitoServiceTest {
}
@Test
void updateIdentityProviderDoesNotMutateAlreadyReturnedInstances() {
UserPool pool = service.createUserPool(Map.of("PoolName", "IdpCopyPool"), "us-east-1");
Map<String, String> details = Map.of(
"client_id", "before",
"client_secret", "secret",
"attributes_request_method", "GET",
"oidc_issuer", "https://issuer.example.com",
"authorize_scopes", "openid");
service.createIdentityProvider(pool.getId(), "CopyOidc", "OIDC", details, null, null);
IdentityProvider held = service.describeIdentityProvider(pool.getId(), "CopyOidc");
Map<String, String> updated = new java.util.LinkedHashMap<>(details);
updated.put("client_id", "after");
service.updateIdentityProvider(pool.getId(), "CopyOidc", updated, null, null);
assertEquals("before", held.getProviderDetails().get("client_id"),
"update must write a copy, not mutate the instance the store already handed out");
assertEquals("after",
service.describeIdentityProvider(pool.getId(), "CopyOidc").getProviderDetails().get("client_id"));
}
// Issue #1654: ConfirmSignUp updates verified attribute
@Nested
class ConfirmSignUpVerifiedAttributes {
@@ -2815,6 +2841,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,