From dd9cdc12073eef64dbcb863034dad5949ebed872 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Fri, 4 Sep 2026 10:16:18 -0600 Subject: [PATCH] feat(cognitoidentity): identity pool management plane (CRUD, roles, principal-tag maps, tags) (#2977) * feat(cognitoidentity): identity pool management plane (CRUD, roles, principal-tag maps, tags) Emulates the Cognito Identity (federated identity pools) management API: CreateIdentityPool through DeleteIdentityPool, ListIdentityPools with pagination, SetIdentityPoolRoles/GetIdentityPoolRoles including role mappings, Set/GetPrincipalTagAttributeMap, and resource tagging. JSON 1.1 under the AWSCognitoIdentityService target prefix, signing name cognito-identity. * fix(cognitoidentity): require AllowUnauthenticatedIdentities and key tag writes by pool region An omitted AllowUnauthenticatedIdentities returned success with false persisted. It now fails with ValidationException. TagResource and UntagResource wrote the pool back under the signing region rather than the region in its ARN. * fix(cognitoidentity): reject a non-boolean AllowUnauthenticatedIdentities Jackson coerced strings and numbers to a boolean instead of failing the request. --- docs/services/cognitoidentity.md | 82 +++ docs/services/index.md | 1 + mkdocs.yml | 1 + .../floci/config/EmulatorConfig.java | 6 + .../core/common/AwsJson11Controller.java | 5 + .../core/common/ResolvedServiceCatalog.java | 5 + .../CognitoIdentityJsonHandler.java | 244 +++++++++ .../CognitoIdentityService.java | 309 ++++++++++++ .../model/CognitoIdentityProvider.java | 39 ++ .../cognitoidentity/model/IdentityPool.java | 169 +++++++ .../model/PrincipalTagAttributeMap.java | 41 ++ src/main/resources/application.yml | 2 + .../CognitoIdentityIntegrationTest.java | 467 ++++++++++++++++++ src/test/resources/application.yml | 2 + tools/docs/service_matrix.yaml | 1 + tools/docs/services.yaml | 4 + 16 files changed, 1378 insertions(+) create mode 100644 docs/services/cognitoidentity.md create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityJsonHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/CognitoIdentityProvider.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/IdentityPool.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/PrincipalTagAttributeMap.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityIntegrationTest.java diff --git a/docs/services/cognitoidentity.md b/docs/services/cognitoidentity.md new file mode 100644 index 0000000000..65a51ead1d --- /dev/null +++ b/docs/services/cognitoidentity.md @@ -0,0 +1,82 @@ +# Amazon Cognito Identity + +**Protocol:** JSON 1.1 (`X-Amz-Target: AWSCognitoIdentityService.`) +**Endpoint:** `http://localhost:4566/` (SigV4 service `cognito-identity`) + +Cognito Identity is the federated identity pool API, distinct from the Cognito user pool +API (`cognito-idp`, documented in [Cognito](cognito.md)). Floci emulates the identity pool +management plane; the identity and credential-vending data plane is not emulated. + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `CreateIdentityPool` | Create a pool; returns the whole pool including tags | +| `DescribeIdentityPool` | Read a pool by id | +| `UpdateIdentityPool` | Replace a pool's configuration wholesale | +| `DeleteIdentityPool` | Delete a pool | +| `ListIdentityPools` | Page through pools, ordered by pool id | +| `SetIdentityPoolRoles` | Set the authenticated/unauthenticated roles and role mappings | +| `GetIdentityPoolRoles` | Read the roles and role mappings | +| `TagResource` | Add tags to a pool by ARN | +| `UntagResource` | Remove tags from a pool by ARN | +| `ListTagsForResource` | List a pool's tags | +| `SetPrincipalTagAttributeMap` | Map principal tags to user attributes for one provider | +| `GetPrincipalTagAttributeMap` | Read a provider's principal tag attribute map | + + +Pool ids use the AWS `:` format (`us-east-1:0f4a...`), and pool ARNs the +documented `arn:aws:cognito-identity:::identitypool/` form, so +callers that parse either get the same structure they would from AWS. + +`UpdateIdentityPool` takes the full `IdentityPool` shape and replaces the stored pool with +it: a member the caller omits is reset to its default rather than carried over, matching +the AWS behaviour ("if you don't provide a value for a parameter, Amazon Cognito sets it to +its default value"). Roles, role mappings and principal tag attribute maps are set by their +own operations, are not part of the `IdentityPool` shape, and survive the replace. + +`TagResource` writes into the same store as `IdentityPoolTags`, so a tag added by ARN is +visible on the next `DescribeIdentityPool` and vice versa. + +`GetIdentityPoolRoles` returns `Roles` and `RoleMappings` as empty maps before +`SetIdentityPoolRoles` has run, never as null, so a provider read that dereferences them +does not crash. + +## Not implemented + +The identity and credential-vending operations are absent and return +`UnknownOperationException`: + +`GetId`, `GetCredentialsForIdentity`, `GetOpenIdToken`, `GetOpenIdTokenForDeveloperIdentity`, +`DescribeIdentity`, `ListIdentities`, `DeleteIdentities`, `UnlinkIdentity`, +`UnlinkDeveloperIdentity`, `LookupDeveloperIdentity`, `MergeDeveloperIdentities`. + +These mint real STS session credentials and signed OIDC tokens against a pool's configured +providers. An identity id handed out by `GetId` is only usable as input to +`GetCredentialsForIdentity` or `GetOpenIdToken`, so serving it alone would move the failure +one call later instead of removing it. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_COGNITOIDENTITY_ENABLED` | `true` | Enable or disable the service | + +## Examples + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 + +aws cognito-identity create-identity-pool \ + --identity-pool-name my-pool \ + --allow-unauthenticated-identities + +aws cognito-identity set-identity-pool-roles \ + --identity-pool-id us-east-1:... \ + --roles authenticated=arn:aws:iam::000000000000:role/authenticated + +aws cognito-identity describe-identity-pool --identity-pool-id us-east-1:... + +aws cognito-identity delete-identity-pool --identity-pool-id us-east-1:... +``` diff --git a/docs/services/index.md b/docs/services/index.md index cc60092b45..82e6c7d22d 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -27,6 +27,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 55 | | [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 43 | +| [Cognito Identity](cognitoidentity.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityService.*` | JSON 1.1 | 13 | | [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 34 | | [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 | | [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 24 | diff --git a/mkdocs.yml b/mkdocs.yml index 31d5e30c49..12a113a8b9 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -106,6 +106,7 @@ nav: - Lambda MicroVMs: services/lambda-microvms.md - API Gateway: services/api-gateway.md - Cognito: services/cognito.md + - Cognito Identity: services/cognitoidentity.md - KMS: services/kms.md - CloudHSM v2: services/cloudhsmv2.md - Kinesis: services/kinesis.md diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index e23c9cb5fe..252e4b0695 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -714,6 +714,7 @@ public interface EmulatorConfig { RamServiceConfig ram(); ControlTowerServiceConfig controltower(); ConnectServiceConfig connect(); + CognitoIdentityServiceConfig cognitoidentity(); ApsServiceConfig aps(); @@ -727,6 +728,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface CognitoIdentityServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface SsoAdminServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index 1426717082..1e065d3b49 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -45,6 +45,7 @@ import io.github.hectorvent.floci.services.kinesisanalytics.KinesisAnalyticsV2Js import io.github.hectorvent.floci.services.kms.KmsJsonHandler; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler; import io.github.hectorvent.floci.services.organizations.OrganizationsJsonHandler; +import io.github.hectorvent.floci.services.cognitoidentity.CognitoIdentityJsonHandler; import io.github.hectorvent.floci.services.route53resolver.Route53ResolverJsonHandler; import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler; import io.github.hectorvent.floci.services.servicecatalog.ServiceCatalogJsonHandler; @@ -115,6 +116,7 @@ public class AwsJson11Controller { private final CloudTrailJsonHandler cloudTrailJsonHandler; private final LightsailJsonHandler lightsailJsonHandler; private final Route53ResolverJsonHandler route53ResolverJsonHandler; + private final CognitoIdentityJsonHandler cognitoIdentityJsonHandler; private final NetworkFirewallJsonHandler networkFirewallJsonHandler; private final ServiceCatalogJsonHandler serviceCatalogJsonHandler; private final CloudControlJsonHandler cloudControlJsonHandler; @@ -161,6 +163,7 @@ public class AwsJson11Controller { CloudTrailJsonHandler cloudTrailJsonHandler, LightsailJsonHandler lightsailJsonHandler, Route53ResolverJsonHandler route53ResolverJsonHandler, + CognitoIdentityJsonHandler cognitoIdentityJsonHandler, NetworkFirewallJsonHandler networkFirewallJsonHandler, ServiceCatalogJsonHandler serviceCatalogJsonHandler, CloudControlJsonHandler cloudControlJsonHandler, @@ -211,6 +214,7 @@ public class AwsJson11Controller { this.cloudTrailJsonHandler = cloudTrailJsonHandler; this.lightsailJsonHandler = lightsailJsonHandler; this.route53ResolverJsonHandler = route53ResolverJsonHandler; + this.cognitoIdentityJsonHandler = cognitoIdentityJsonHandler; this.networkFirewallJsonHandler = networkFirewallJsonHandler; this.serviceCatalogJsonHandler = serviceCatalogJsonHandler; this.cloudControlJsonHandler = cloudControlJsonHandler; @@ -293,6 +297,7 @@ public class AwsJson11Controller { case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region); case "lightsail" -> lightsailJsonHandler.handle(action, request, region); case "route53resolver" -> route53ResolverJsonHandler.handle(action, request, region, regionResolver.getAccountId()); + case "cognito-identity" -> cognitoIdentityJsonHandler.handle(action, request, region); case "network-firewall" -> networkFirewallJsonHandler.handle( action, request, region, regionResolver.getAccountId()); case "servicecatalog" -> serviceCatalogJsonHandler.handle( diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 63f195d580..153bb3374b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -555,6 +555,11 @@ public class ResolvedServiceCatalog { protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("connect"), Set.of(), Set.of(io.github.hectorvent.floci.services.connect.ConnectController.class)), + descriptor("cognito-identity", "cognitoidentity", + config.services().cognitoidentity().enabled(), true, + "cognitoidentity", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("AWSCognitoIdentityService."), Set.of("cognito-identity"), Set.of(), Set.of()), descriptor("network-firewall", "networkfirewall", config.services().networkfirewall().enabled(), true, "networkfirewall", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityJsonHandler.java new file mode 100644 index 0000000000..ba3026332b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityJsonHandler.java @@ -0,0 +1,244 @@ +package io.github.hectorvent.floci.services.cognitoidentity; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cognitoidentity.model.CognitoIdentityProvider; +import io.github.hectorvent.floci.services.cognitoidentity.model.IdentityPool; +import io.github.hectorvent.floci.services.cognitoidentity.model.PrincipalTagAttributeMap; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Amazon Cognito Identity (federated identity pools) management plane. + * + *

Operations that are not implemented fall through to a clean + * {@code UnknownOperationException} rather than a stub success, so callers fail fast + * instead of stranding a waiter. The identity and credential-vending operations + * ({@code GetId}, {@code GetCredentialsForIdentity}, {@code GetOpenIdToken} and peers) are + * deliberately absent: they mint STS session credentials and signed OIDC tokens, which this + * management plane has no way to produce. + */ +@ApplicationScoped +public class CognitoIdentityJsonHandler { + + private final CognitoIdentityService cognitoIdentityService; + private final ObjectMapper objectMapper; + + @Inject + public CognitoIdentityJsonHandler(CognitoIdentityService cognitoIdentityService, ObjectMapper objectMapper) { + this.cognitoIdentityService = cognitoIdentityService; + this.objectMapper = objectMapper; + } + + public Response handle(String action, JsonNode request, String region) throws Exception { + return switch (action) { + case "CreateIdentityPool" -> Response.ok( + identityPoolNode(cognitoIdentityService.createIdentityPool(parsePool(request), region))).build(); + + case "DescribeIdentityPool" -> Response.ok(identityPoolNode( + cognitoIdentityService.describeIdentityPool(text(request, "IdentityPoolId"), region))).build(); + + case "UpdateIdentityPool" -> Response.ok( + identityPoolNode(cognitoIdentityService.updateIdentityPool(parsePool(request), region))).build(); + + case "DeleteIdentityPool" -> { + cognitoIdentityService.deleteIdentityPool(text(request, "IdentityPoolId"), region); + yield Response.ok(objectMapper.createObjectNode()).build(); + } + + case "ListIdentityPools" -> { + CognitoIdentityService.Page page = cognitoIdentityService.listIdentityPools( + integer(request, "MaxResults"), text(request, "NextToken"), region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode identityPools = response.putArray("IdentityPools"); + for (IdentityPool pool : page.identityPools()) { + ObjectNode summary = identityPools.addObject(); + summary.put("IdentityPoolId", pool.getIdentityPoolId()); + summary.put("IdentityPoolName", pool.getIdentityPoolName()); + } + if (page.nextToken() != null) { + response.put("NextToken", page.nextToken()); + } + yield Response.ok(response).build(); + } + + case "SetIdentityPoolRoles" -> { + cognitoIdentityService.setIdentityPoolRoles(text(request, "IdentityPoolId"), + stringMap(request.get("Roles")), request.get("RoleMappings"), region); + yield Response.ok(objectMapper.createObjectNode()).build(); + } + + case "GetIdentityPoolRoles" -> { + IdentityPool pool = cognitoIdentityService.getIdentityPoolRoles( + text(request, "IdentityPoolId"), region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("IdentityPoolId", pool.getIdentityPoolId()); + response.set("Roles", objectMapper.valueToTree(pool.getRoles())); + response.set("RoleMappings", pool.getRoleMappings() != null + ? pool.getRoleMappings() + : objectMapper.createObjectNode()); + yield Response.ok(response).build(); + } + + case "TagResource" -> { + cognitoIdentityService.tagResource(text(request, "ResourceArn"), + stringMap(request.get("Tags")), region); + yield Response.ok(objectMapper.createObjectNode()).build(); + } + + case "UntagResource" -> { + cognitoIdentityService.untagResource(text(request, "ResourceArn"), + stringList(request.get("TagKeys")), region); + yield Response.ok(objectMapper.createObjectNode()).build(); + } + + case "ListTagsForResource" -> { + Map tags = cognitoIdentityService.listTagsForResource( + text(request, "ResourceArn"), region); + ObjectNode response = objectMapper.createObjectNode(); + response.set("Tags", objectMapper.valueToTree(tags)); + yield Response.ok(response).build(); + } + + case "SetPrincipalTagAttributeMap" -> { + String identityPoolId = text(request, "IdentityPoolId"); + PrincipalTagAttributeMap attributeMap = cognitoIdentityService.setPrincipalTagAttributeMap( + identityPoolId, text(request, "IdentityProviderName"), + bool(request, "UseDefaults"), stringMap(request.get("PrincipalTags")), region); + yield Response.ok(principalTagAttributeMapNode(identityPoolId, attributeMap)).build(); + } + + case "GetPrincipalTagAttributeMap" -> { + String identityPoolId = text(request, "IdentityPoolId"); + PrincipalTagAttributeMap attributeMap = cognitoIdentityService.getPrincipalTagAttributeMap( + identityPoolId, text(request, "IdentityProviderName"), region); + yield Response.ok(principalTagAttributeMapNode(identityPoolId, attributeMap)).build(); + } + + default -> throw new AwsException("UnknownOperationException", + "Operation " + action + " is not supported by floci", 400); + }; + } + + private IdentityPool parsePool(JsonNode request) { + IdentityPool pool = new IdentityPool(); + pool.setIdentityPoolId(text(request, "IdentityPoolId")); + pool.setIdentityPoolName(text(request, "IdentityPoolName")); + pool.setAllowUnauthenticatedIdentities(requiredBool(request, "AllowUnauthenticatedIdentities")); + pool.setAllowClassicFlow(request.path("AllowClassicFlow").asBoolean(false)); + pool.setSupportedLoginProviders(stringMap(request.get("SupportedLoginProviders"))); + pool.setDeveloperProviderName(text(request, "DeveloperProviderName")); + pool.setOpenIdConnectProviderArns(stringList(request.get("OpenIdConnectProviderARNs"))); + pool.setSamlProviderArns(stringList(request.get("SamlProviderARNs"))); + pool.setIdentityPoolTags(stringMap(request.get("IdentityPoolTags"))); + + List providers = new ArrayList<>(); + JsonNode providersNode = request.get("CognitoIdentityProviders"); + if (providersNode != null && providersNode.isArray()) { + for (JsonNode node : providersNode) { + CognitoIdentityProvider provider = new CognitoIdentityProvider(); + provider.setProviderName(text(node, "ProviderName")); + provider.setClientId(text(node, "ClientId")); + provider.setServerSideTokenCheck(node.path("ServerSideTokenCheck").asBoolean(false)); + providers.add(provider); + } + } + pool.setCognitoIdentityProviders(providers); + return pool; + } + + private ObjectNode identityPoolNode(IdentityPool pool) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("IdentityPoolId", pool.getIdentityPoolId()); + node.put("IdentityPoolName", pool.getIdentityPoolName()); + node.put("AllowUnauthenticatedIdentities", pool.isAllowUnauthenticatedIdentities()); + node.put("AllowClassicFlow", pool.isAllowClassicFlow()); + node.set("SupportedLoginProviders", objectMapper.valueToTree(pool.getSupportedLoginProviders())); + if (pool.getDeveloperProviderName() != null) { + node.put("DeveloperProviderName", pool.getDeveloperProviderName()); + } + node.set("OpenIdConnectProviderARNs", objectMapper.valueToTree(pool.getOpenIdConnectProviderArns())); + node.set("SamlProviderARNs", objectMapper.valueToTree(pool.getSamlProviderArns())); + node.set("IdentityPoolTags", objectMapper.valueToTree(pool.getIdentityPoolTags())); + + ArrayNode providers = node.putArray("CognitoIdentityProviders"); + for (CognitoIdentityProvider provider : pool.getCognitoIdentityProviders()) { + ObjectNode providerNode = providers.addObject(); + providerNode.put("ProviderName", provider.getProviderName()); + providerNode.put("ClientId", provider.getClientId()); + providerNode.put("ServerSideTokenCheck", provider.isServerSideTokenCheck()); + } + return node; + } + + private ObjectNode principalTagAttributeMapNode(String identityPoolId, PrincipalTagAttributeMap attributeMap) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("IdentityPoolId", identityPoolId); + node.put("IdentityProviderName", attributeMap.getIdentityProviderName()); + node.put("UseDefaults", attributeMap.isUseDefaults()); + node.set("PrincipalTags", objectMapper.valueToTree(attributeMap.getPrincipalTags())); + return node; + } + + private String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || value.isNull()) { + return null; + } + return value.asText(); + } + + private Integer integer(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isNumber()) { + return null; + } + return value.asInt(); + } + + private Boolean bool(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || value.isNull()) { + return null; + } + if (!value.isBoolean()) { + throw new AwsException("SerializationException", field + " must be a boolean.", 400); + } + return value.asBoolean(); + } + + private boolean requiredBool(JsonNode node, String field) { + Boolean value = bool(node, field); + if (value == null) { + throw new AwsException("ValidationException", "1 validation error detected: Value null at '" + + Character.toLowerCase(field.charAt(0)) + field.substring(1) + + "' failed to satisfy constraint: Member must not be null", 400); + } + return value; + } + + private Map stringMap(JsonNode node) { + Map values = new LinkedHashMap<>(); + if (node != null && node.isObject()) { + node.fields().forEachRemaining(entry -> values.put(entry.getKey(), entry.getValue().asText())); + } + return values; + } + + private List stringList(JsonNode node) { + List values = new ArrayList<>(); + if (node != null && node.isArray()) { + node.forEach(element -> values.add(element.asText())); + } + return values; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityService.java new file mode 100644 index 0000000000..7c734096a7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityService.java @@ -0,0 +1,309 @@ +package io.github.hectorvent.floci.services.cognitoidentity; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.cognitoidentity.model.IdentityPool; +import io.github.hectorvent.floci.services.cognitoidentity.model.PrincipalTagAttributeMap; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Amazon Cognito Identity (federated identity pools) management plane. + * + *

Pool ids follow the AWS format {@code :} and pool ARNs the documented + * {@code arn:aws:cognito-identity:::identitypool/} form, so a caller + * that parses either gets the same structure it would from AWS. + */ +@ApplicationScoped +public class CognitoIdentityService { + + private static final Logger LOG = Logger.getLogger(CognitoIdentityService.class); + + private static final Pattern IDENTITY_POOL_NAME = Pattern.compile("[\\w\\s+=,.@-]+"); + private static final Pattern DEVELOPER_PROVIDER_NAME = Pattern.compile("[\\w._-]+"); + private static final Set ROLE_TYPES = Set.of("authenticated", "unauthenticated"); + private static final Set ROLE_MAPPING_TYPES = Set.of("Token", "Rules"); + private static final String ARN_RESOURCE_PREFIX = "identitypool/"; + private static final int MAX_LIST_RESULTS = 60; + + private final StorageBackend pools; + private final RegionResolver regionResolver; + + @Inject + public CognitoIdentityService(StorageFactory storageFactory, RegionResolver regionResolver) { + this.pools = storageFactory.create("cognitoidentity", "cognitoidentity-pools.json", + new TypeReference>() {}); + this.regionResolver = regionResolver; + } + + // ──────────────────────────── Identity pools ──────────────────────────── + + public IdentityPool createIdentityPool(IdentityPool spec, String region) { + validatePoolConfiguration(spec); + + String identityPoolId = region + ":" + UUID.randomUUID(); + spec.setIdentityPoolId(identityPoolId); + spec.setArn(regionResolver.buildArn("cognito-identity", region, ARN_RESOURCE_PREFIX + identityPoolId)); + spec.setAccountId(regionResolver.getAccountId()); + spec.setCreatedAt(Instant.now()); + + pools.put(storageKey(region, identityPoolId), spec); + LOG.infov("Created Cognito identity pool: {0}", identityPoolId); + return spec; + } + + public IdentityPool describeIdentityPool(String identityPoolId, String region) { + requireIdentityPoolId(identityPoolId); + return pools.get(storageKey(region, identityPoolId)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "IdentityPool '" + identityPoolId + "' not found.", 404)); + } + + /** + * {@code UpdateIdentityPool} takes the whole {@code IdentityPool} shape and replaces the + * stored pool with it: a member the caller omits is reset to its default rather than + * carried over. The roles, role mappings and principal-tag maps are set by their own + * operations and are not part of the shape, so they survive the replace. + */ + public IdentityPool updateIdentityPool(IdentityPool spec, String region) { + IdentityPool existing = describeIdentityPool(spec.getIdentityPoolId(), region); + validatePoolConfiguration(spec); + + spec.setArn(existing.getArn()); + spec.setAccountId(existing.getAccountId()); + spec.setCreatedAt(existing.getCreatedAt()); + spec.setRoles(existing.getRoles()); + spec.setRoleMappings(existing.getRoleMappings()); + spec.setPrincipalTagAttributeMaps(existing.getPrincipalTagAttributeMaps()); + + pools.put(storageKey(region, spec.getIdentityPoolId()), spec); + LOG.infov("Updated Cognito identity pool: {0}", spec.getIdentityPoolId()); + return spec; + } + + public void deleteIdentityPool(String identityPoolId, String region) { + describeIdentityPool(identityPoolId, region); + pools.delete(storageKey(region, identityPoolId)); + LOG.infov("Deleted Cognito identity pool: {0}", identityPoolId); + } + + /** + * Returns one page of pools ordered by pool id. The pagination token is the index of the + * first pool of the next page, which keeps the token stable for the common case of a pool + * set that only grows. + */ + public Page listIdentityPools(Integer maxResults, String nextToken, String region) { + int limit = maxResults == null ? MAX_LIST_RESULTS : maxResults; + if (limit < 1 || limit > MAX_LIST_RESULTS) { + throw new AwsException("InvalidParameterException", + "MaxResults must be between 1 and " + MAX_LIST_RESULTS + ".", 400); + } + int offset = parseToken(nextToken); + + String regionPrefix = region + "::"; + List ordered = pools.scan(key -> key.startsWith(regionPrefix)).stream() + .sorted(Comparator.comparing(IdentityPool::getIdentityPoolId)) + .toList(); + if (offset >= ordered.size()) { + return new Page(List.of(), null); + } + int end = Math.min(offset + limit, ordered.size()); + return new Page(ordered.subList(offset, end), end < ordered.size() ? String.valueOf(end) : null); + } + + // ──────────────────────────── Pool roles ──────────────────────────── + + public IdentityPool setIdentityPoolRoles(String identityPoolId, Map roles, + JsonNode roleMappings, String region) { + IdentityPool pool = describeIdentityPool(identityPoolId, region); + if (roles == null || roles.isEmpty()) { + throw new AwsException("InvalidParameterException", "Roles is required.", 400); + } + for (Map.Entry entry : roles.entrySet()) { + if (!ROLE_TYPES.contains(entry.getKey())) { + throw new AwsException("InvalidParameterException", + "Role key '" + entry.getKey() + "' must be one of authenticated, unauthenticated.", 400); + } + if (entry.getValue() == null || entry.getValue().isBlank()) { + throw new AwsException("InvalidParameterException", + "Role ARN for '" + entry.getKey() + "' must not be empty.", 400); + } + } + validateRoleMappings(roleMappings); + + pool.setRoles(new LinkedHashMap<>(roles)); + pool.setRoleMappings(roleMappings != null && roleMappings.isObject() ? roleMappings : null); + pools.put(storageKey(region, identityPoolId), pool); + return pool; + } + + public IdentityPool getIdentityPoolRoles(String identityPoolId, String region) { + return describeIdentityPool(identityPoolId, region); + } + + // ──────────────────────── Principal tag attribute maps ──────────────────────── + + public PrincipalTagAttributeMap setPrincipalTagAttributeMap(String identityPoolId, String identityProviderName, + Boolean useDefaults, Map principalTags, + String region) { + IdentityPool pool = describeIdentityPool(identityPoolId, region); + if (identityProviderName == null || identityProviderName.isBlank()) { + throw new AwsException("InvalidParameterException", "IdentityProviderName is required.", 400); + } + + PrincipalTagAttributeMap attributeMap = new PrincipalTagAttributeMap(); + attributeMap.setIdentityProviderName(identityProviderName); + attributeMap.setUseDefaults(useDefaults != null && useDefaults); + attributeMap.setPrincipalTags(principalTags != null ? new LinkedHashMap<>(principalTags) : new LinkedHashMap<>()); + + pool.getPrincipalTagAttributeMaps().put(identityProviderName, attributeMap); + pools.put(storageKey(region, identityPoolId), pool); + return attributeMap; + } + + /** + * A provider with no attribute map is not an error in AWS. The read returns the provider + * with an empty map, so an unset provider yields defaults rather than a not-found. + */ + public PrincipalTagAttributeMap getPrincipalTagAttributeMap(String identityPoolId, String identityProviderName, + String region) { + IdentityPool pool = describeIdentityPool(identityPoolId, region); + if (identityProviderName == null || identityProviderName.isBlank()) { + throw new AwsException("InvalidParameterException", "IdentityProviderName is required.", 400); + } + PrincipalTagAttributeMap attributeMap = pool.getPrincipalTagAttributeMaps().get(identityProviderName); + if (attributeMap != null) { + return attributeMap; + } + PrincipalTagAttributeMap empty = new PrincipalTagAttributeMap(); + empty.setIdentityProviderName(identityProviderName); + return empty; + } + + // ──────────────────────────── Tags ──────────────────────────── + + public Map listTagsForResource(String resourceArn, String region) { + return findByArn(resourceArn, region).getIdentityPoolTags(); + } + + public void tagResource(String resourceArn, Map tags, String region) { + if (tags == null || tags.isEmpty()) { + throw new AwsException("InvalidParameterException", "Tags is required.", 400); + } + IdentityPool pool = findByArn(resourceArn, region); + pool.getIdentityPoolTags().putAll(tags); + pools.put(storageKey(pool), pool); + } + + public void untagResource(String resourceArn, List tagKeys, String region) { + if (tagKeys == null || tagKeys.isEmpty()) { + throw new AwsException("InvalidParameterException", "TagKeys is required.", 400); + } + IdentityPool pool = findByArn(resourceArn, region); + tagKeys.forEach(pool.getIdentityPoolTags()::remove); + pools.put(storageKey(pool), pool); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + /** One page of {@code ListIdentityPools} results plus the token for the page after it. */ + public record Page(List identityPools, String nextToken) {} + + private void validatePoolConfiguration(IdentityPool spec) { + String name = spec.getIdentityPoolName(); + if (name == null || name.isBlank() || name.length() > 128 || !IDENTITY_POOL_NAME.matcher(name).matches()) { + throw new AwsException("InvalidParameterException", + "IdentityPoolName must be 1-128 characters matching [\\w\\s+=,.@-]+.", 400); + } + String developerProviderName = spec.getDeveloperProviderName(); + if (developerProviderName != null + && (developerProviderName.length() > 128 + || !DEVELOPER_PROVIDER_NAME.matcher(developerProviderName).matches())) { + throw new AwsException("InvalidParameterException", + "DeveloperProviderName must be 1-128 characters matching [\\w._-]+.", 400); + } + } + + private void validateRoleMappings(JsonNode roleMappings) { + if (roleMappings == null || !roleMappings.isObject()) { + return; + } + roleMappings.fields().forEachRemaining(entry -> { + JsonNode mapping = entry.getValue(); + String type = mapping.path("Type").asText(null); + if (type == null || !ROLE_MAPPING_TYPES.contains(type)) { + throw new AwsException("InvalidParameterException", + "RoleMapping Type for '" + entry.getKey() + "' must be one of Token, Rules.", 400); + } + if ("Rules".equals(type)) { + JsonNode rules = mapping.path("RulesConfiguration").path("Rules"); + if (!rules.isArray() || rules.isEmpty()) { + throw new AwsException("InvalidParameterException", + "RoleMapping '" + entry.getKey() + "' of type Rules requires RulesConfiguration.Rules.", + 400); + } + } + }); + } + + private void requireIdentityPoolId(String identityPoolId) { + if (identityPoolId == null || identityPoolId.isBlank()) { + throw new AwsException("InvalidParameterException", "IdentityPoolId is required.", 400); + } + } + + private IdentityPool findByArn(String resourceArn, String region) { + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(resourceArn); + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidParameterException", "Invalid ResourceArn: " + resourceArn, 400); + } + if (!"cognito-identity".equals(arn.service()) || !arn.resource().startsWith(ARN_RESOURCE_PREFIX)) { + throw new AwsException("InvalidParameterException", "Invalid ResourceArn: " + resourceArn, 400); + } + String identityPoolId = arn.resource().substring(ARN_RESOURCE_PREFIX.length()); + String arnRegion = arn.region().isEmpty() ? region : arn.region(); + return pools.get(storageKey(arnRegion, identityPoolId)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "IdentityPool '" + identityPoolId + "' not found.", 404)); + } + + private int parseToken(String nextToken) { + if (nextToken == null || nextToken.isBlank()) { + return 0; + } + try { + int offset = Integer.parseInt(nextToken); + if (offset < 0) { + throw new NumberFormatException(nextToken); + } + return offset; + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterException", "Invalid NextToken: " + nextToken, 400); + } + } + + private String storageKey(String region, String identityPoolId) { + return region + "::" + identityPoolId; + } + + private String storageKey(IdentityPool pool) { + return storageKey(AwsArnUtils.parse(pool.getArn()).region(), pool.getIdentityPoolId()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/CognitoIdentityProvider.java b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/CognitoIdentityProvider.java new file mode 100644 index 0000000000..3c737c08d2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/CognitoIdentityProvider.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.cognitoidentity.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A Cognito user pool attached to an identity pool + * ({@code IdentityPool.CognitoIdentityProviders} member). + */ +@RegisterForReflection +public class CognitoIdentityProvider { + + private String providerName; + private String clientId; + private boolean serverSideTokenCheck; + + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public boolean isServerSideTokenCheck() { + return serverSideTokenCheck; + } + + public void setServerSideTokenCheck(boolean serverSideTokenCheck) { + this.serverSideTokenCheck = serverSideTokenCheck; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/IdentityPool.java b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/IdentityPool.java new file mode 100644 index 0000000000..4309178fb9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/IdentityPool.java @@ -0,0 +1,169 @@ +package io.github.hectorvent.floci.services.cognitoidentity.model; + +import com.fasterxml.jackson.databind.JsonNode; + +import io.quarkus.runtime.annotations.RegisterForReflection; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A Cognito federated identity pool. + * + *

The pool's own configuration is the {@code IdentityPool} shape of the AWS model. The + * roles, role mappings and principal-tag attribute maps are separate AWS operations + * ({@code SetIdentityPoolRoles}, {@code SetPrincipalTagAttributeMap}) but belong to the same + * pool, so they are persisted alongside it and survive an {@code UpdateIdentityPool} replace. + */ +@RegisterForReflection +public class IdentityPool { + + private String identityPoolId; + private String identityPoolName; + private boolean allowUnauthenticatedIdentities; + private boolean allowClassicFlow; + private Map supportedLoginProviders = new LinkedHashMap<>(); + private String developerProviderName; + private List openIdConnectProviderArns = new ArrayList<>(); + private List cognitoIdentityProviders = new ArrayList<>(); + private List samlProviderArns = new ArrayList<>(); + private Map identityPoolTags = new LinkedHashMap<>(); + + private String arn; + private String accountId; + private Instant createdAt; + + private Map roles = new LinkedHashMap<>(); + private JsonNode roleMappings; + private Map principalTagAttributeMaps = new LinkedHashMap<>(); + + public String getIdentityPoolId() { + return identityPoolId; + } + + public void setIdentityPoolId(String identityPoolId) { + this.identityPoolId = identityPoolId; + } + + public String getIdentityPoolName() { + return identityPoolName; + } + + public void setIdentityPoolName(String identityPoolName) { + this.identityPoolName = identityPoolName; + } + + public boolean isAllowUnauthenticatedIdentities() { + return allowUnauthenticatedIdentities; + } + + public void setAllowUnauthenticatedIdentities(boolean allowUnauthenticatedIdentities) { + this.allowUnauthenticatedIdentities = allowUnauthenticatedIdentities; + } + + public boolean isAllowClassicFlow() { + return allowClassicFlow; + } + + public void setAllowClassicFlow(boolean allowClassicFlow) { + this.allowClassicFlow = allowClassicFlow; + } + + public Map getSupportedLoginProviders() { + return supportedLoginProviders; + } + + public void setSupportedLoginProviders(Map supportedLoginProviders) { + this.supportedLoginProviders = supportedLoginProviders; + } + + public String getDeveloperProviderName() { + return developerProviderName; + } + + public void setDeveloperProviderName(String developerProviderName) { + this.developerProviderName = developerProviderName; + } + + public List getOpenIdConnectProviderArns() { + return openIdConnectProviderArns; + } + + public void setOpenIdConnectProviderArns(List openIdConnectProviderArns) { + this.openIdConnectProviderArns = openIdConnectProviderArns; + } + + public List getCognitoIdentityProviders() { + return cognitoIdentityProviders; + } + + public void setCognitoIdentityProviders(List cognitoIdentityProviders) { + this.cognitoIdentityProviders = cognitoIdentityProviders; + } + + public List getSamlProviderArns() { + return samlProviderArns; + } + + public void setSamlProviderArns(List samlProviderArns) { + this.samlProviderArns = samlProviderArns; + } + + public Map getIdentityPoolTags() { + return identityPoolTags; + } + + public void setIdentityPoolTags(Map identityPoolTags) { + this.identityPoolTags = identityPoolTags; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Map getRoles() { + return roles; + } + + public void setRoles(Map roles) { + this.roles = roles; + } + + public JsonNode getRoleMappings() { + return roleMappings; + } + + public void setRoleMappings(JsonNode roleMappings) { + this.roleMappings = roleMappings; + } + + public Map getPrincipalTagAttributeMaps() { + return principalTagAttributeMaps; + } + + public void setPrincipalTagAttributeMaps(Map principalTagAttributeMaps) { + this.principalTagAttributeMaps = principalTagAttributeMaps; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/PrincipalTagAttributeMap.java b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/PrincipalTagAttributeMap.java new file mode 100644 index 0000000000..a611492fdf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognitoidentity/model/PrincipalTagAttributeMap.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.cognitoidentity.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Mapping between principal tags and user attributes for one identity provider attached to + * an identity pool ({@code SetPrincipalTagAttributeMap} / {@code GetPrincipalTagAttributeMap}). + */ +@RegisterForReflection +public class PrincipalTagAttributeMap { + + private String identityProviderName; + private boolean useDefaults; + private Map principalTags = new LinkedHashMap<>(); + + public String getIdentityProviderName() { + return identityProviderName; + } + + public void setIdentityProviderName(String identityProviderName) { + this.identityProviderName = identityProviderName; + } + + public boolean isUseDefaults() { + return useDefaults; + } + + public void setUseDefaults(boolean useDefaults) { + this.useDefaults = useDefaults; + } + + public Map getPrincipalTags() { + return principalTags; + } + + public void setPrincipalTags(Map principalTags) { + this.principalTags = principalTags; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 87e4a9e062..320f5cebae 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -610,6 +610,8 @@ floci: enabled: true connect: enabled: true + cognitoidentity: + enabled: true aps: enabled: true lakeformation: diff --git a/src/test/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityIntegrationTest.java new file mode 100644 index 0000000000..7672945b50 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityIntegrationTest.java @@ -0,0 +1,467 @@ +package io.github.hectorvent.floci.services.cognitoidentity; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +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 java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoIdentityIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String TARGET = "AWSCognitoIdentityService"; + private static final String USER_POOL_PROVIDER = "cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123"; + private static final String EU_WEST_1_AUTHORIZATION = + "AWS4-HMAC-SHA256 Credential=test/20260101/eu-west-1/cognito-identity/aws4_request"; + + private static String identityPoolId; + private static String identityPoolArn; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static io.restassured.specification.RequestSpecification action(String name) { + return given() + .header("X-Amz-Target", TARGET + "." + name) + .contentType(CONTENT_TYPE); + } + + @Test + @Order(1) + void createIdentityPool() { + identityPoolId = action("CreateIdentityPool") + .body(""" + { + "IdentityPoolName": "floci integration pool", + "AllowUnauthenticatedIdentities": true, + "AllowClassicFlow": true, + "DeveloperProviderName": "login.floci.test", + "SupportedLoginProviders": {"graph.facebook.com": "1234567890"}, + "OpenIdConnectProviderARNs": ["arn:aws:iam::000000000000:oidc-provider/example.com"], + "SamlProviderARNs": ["arn:aws:iam::000000000000:saml-provider/example"], + "CognitoIdentityProviders": [ + {"ProviderName": "%s", "ClientId": "client-abc", "ServerSideTokenCheck": true} + ], + "IdentityPoolTags": {"team": "identity"} + } + """.formatted(USER_POOL_PROVIDER)) + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", matchesPattern("us-east-1:[0-9a-f-]{36}")) + .body("IdentityPoolName", equalTo("floci integration pool")) + .body("AllowUnauthenticatedIdentities", equalTo(true)) + .body("AllowClassicFlow", equalTo(true)) + .body("DeveloperProviderName", equalTo("login.floci.test")) + .body("SupportedLoginProviders.'graph.facebook.com'", equalTo("1234567890")) + .body("OpenIdConnectProviderARNs[0]", equalTo("arn:aws:iam::000000000000:oidc-provider/example.com")) + .body("SamlProviderARNs[0]", equalTo("arn:aws:iam::000000000000:saml-provider/example")) + .body("CognitoIdentityProviders[0].ProviderName", equalTo(USER_POOL_PROVIDER)) + .body("CognitoIdentityProviders[0].ClientId", equalTo("client-abc")) + .body("CognitoIdentityProviders[0].ServerSideTokenCheck", equalTo(true)) + .body("IdentityPoolTags.team", equalTo("identity")) + .extract().path("IdentityPoolId"); + + identityPoolArn = "arn:aws:cognito-identity:us-east-1:000000000000:identitypool/" + identityPoolId; + } + + @Test + @Order(2) + void describeIdentityPool() { + action("DescribeIdentityPool") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", equalTo(identityPoolId)) + .body("IdentityPoolName", equalTo("floci integration pool")) + .body("AllowUnauthenticatedIdentities", equalTo(true)) + .body("CognitoIdentityProviders[0].ClientId", equalTo("client-abc")) + .body("IdentityPoolTags.team", equalTo("identity")); + } + + @Test + @Order(3) + void describeMissingIdentityPoolReturnsResourceNotFound() { + action("DescribeIdentityPool") + .body("{\"IdentityPoolId\": \"us-east-1:00000000-0000-0000-0000-000000000000\"}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(4) + void createIdentityPoolRejectsInvalidName() { + action("CreateIdentityPool") + .body("{\"IdentityPoolName\": \"bad/name\", \"AllowUnauthenticatedIdentities\": false}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + @Order(5) + void listIdentityPools() { + action("ListIdentityPools") + .body("{\"MaxResults\": 60}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPools.IdentityPoolId", hasItem(identityPoolId)) + .body("IdentityPools.IdentityPoolName", hasItem("floci integration pool")); + } + + @Test + @Order(6) + void listIdentityPoolsRejectsOutOfRangeMaxResults() { + action("ListIdentityPools") + .body("{\"MaxResults\": 500}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + @Order(7) + void getIdentityPoolRolesBeforeSetReturnsEmptyMaps() { + action("GetIdentityPoolRoles") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", equalTo(identityPoolId)) + .body("Roles", not(nullValue())) + .body("Roles.keySet()", emptyIterable()) + .body("RoleMappings", not(nullValue())); + } + + @Test + @Order(8) + void setAndGetIdentityPoolRoles() { + action("SetIdentityPoolRoles") + .body(""" + { + "IdentityPoolId": "%s", + "Roles": { + "authenticated": "arn:aws:iam::000000000000:role/authenticated", + "unauthenticated": "arn:aws:iam::000000000000:role/unauthenticated" + }, + "RoleMappings": { + "%s:client-abc": { + "Type": "Rules", + "AmbiguousRoleResolution": "Deny", + "RulesConfiguration": { + "Rules": [ + {"Claim": "isAdmin", "MatchType": "Equals", "Value": "true", + "RoleARN": "arn:aws:iam::000000000000:role/admin"} + ] + } + } + } + } + """.formatted(identityPoolId, USER_POOL_PROVIDER)) + .when() + .post("/") + .then() + .statusCode(200); + + Map roleMappings = action("GetIdentityPoolRoles") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", equalTo(identityPoolId)) + .body("Roles.authenticated", equalTo("arn:aws:iam::000000000000:role/authenticated")) + .body("Roles.unauthenticated", equalTo("arn:aws:iam::000000000000:role/unauthenticated")) + .extract().path("RoleMappings"); + + @SuppressWarnings("unchecked") + Map mapping = (Map) roleMappings.get(USER_POOL_PROVIDER + ":client-abc"); + assertNotNull(mapping, "RoleMappings must round-trip the provider key sent on SetIdentityPoolRoles"); + assertEquals("Rules", mapping.get("Type")); + assertEquals("Deny", mapping.get("AmbiguousRoleResolution")); + } + + @Test + @Order(9) + void setIdentityPoolRolesRejectsUnknownRoleKey() { + action("SetIdentityPoolRoles") + .body(""" + {"IdentityPoolId": "%s", "Roles": {"admin": "arn:aws:iam::000000000000:role/admin"}} + """.formatted(identityPoolId)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + @Order(10) + void tagRoundTrip() { + action("TagResource") + .body(""" + {"ResourceArn": "%s", "Tags": {"env": "test"}} + """.formatted(identityPoolArn)) + .when() + .post("/") + .then() + .statusCode(200); + + action("ListTagsForResource") + .body("{\"ResourceArn\": \"" + identityPoolArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags.team", equalTo("identity")) + .body("Tags.env", equalTo("test")); + + action("DescribeIdentityPool") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolTags.env", equalTo("test")); + + action("UntagResource") + .body(""" + {"ResourceArn": "%s", "TagKeys": ["env"]} + """.formatted(identityPoolArn)) + .when() + .post("/") + .then() + .statusCode(200); + + action("ListTagsForResource") + .body("{\"ResourceArn\": \"" + identityPoolArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags", hasKey("team")) + .body("Tags", not(hasKey("env"))); + } + + @Test + @Order(11) + void listTagsForUnknownPoolReturnsResourceNotFound() { + action("ListTagsForResource") + .body(""" + {"ResourceArn": "arn:aws:cognito-identity:us-east-1:000000000000:identitypool/us-east-1:00000000-0000-0000-0000-000000000000"} + """) + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(12) + void principalTagAttributeMapRoundTrip() { + action("SetPrincipalTagAttributeMap") + .body(""" + {"IdentityPoolId": "%s", "IdentityProviderName": "%s", + "UseDefaults": false, "PrincipalTags": {"department": "custom:department"}} + """.formatted(identityPoolId, USER_POOL_PROVIDER)) + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", equalTo(identityPoolId)) + .body("IdentityProviderName", equalTo(USER_POOL_PROVIDER)) + .body("UseDefaults", equalTo(false)) + .body("PrincipalTags.department", equalTo("custom:department")); + + action("GetPrincipalTagAttributeMap") + .body(""" + {"IdentityPoolId": "%s", "IdentityProviderName": "%s"} + """.formatted(identityPoolId, USER_POOL_PROVIDER)) + .when() + .post("/") + .then() + .statusCode(200) + .body("UseDefaults", equalTo(false)) + .body("PrincipalTags.department", equalTo("custom:department")); + } + + @Test + @Order(13) + void updateIdentityPoolReplacesTheWholePool() { + action("UpdateIdentityPool") + .body(""" + { + "IdentityPoolId": "%s", + "IdentityPoolName": "floci integration pool renamed", + "AllowUnauthenticatedIdentities": false + } + """.formatted(identityPoolId)) + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", equalTo(identityPoolId)) + .body("IdentityPoolName", equalTo("floci integration pool renamed")) + .body("AllowUnauthenticatedIdentities", equalTo(false)) + .body("AllowClassicFlow", equalTo(false)) + .body("CognitoIdentityProviders", emptyIterable()) + .body("SupportedLoginProviders.keySet()", emptyIterable()) + .body("IdentityPoolTags.keySet()", emptyIterable()); + + action("GetIdentityPoolRoles") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Roles.authenticated", equalTo("arn:aws:iam::000000000000:role/authenticated")); + } + + @Test + @Order(14) + void unimplementedOperationReturnsUnknownOperation() { + action("GetCredentialsForIdentity") + .body("{\"IdentityId\": \"us-east-1:00000000-0000-0000-0000-000000000000\"}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + @Order(15) + void deleteIdentityPool() { + action("DeleteIdentityPool") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + + action("DescribeIdentityPool") + .body("{\"IdentityPoolId\": \"" + identityPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + @Order(16) + void createIdentityPoolRequiresAllowUnauthenticatedIdentities() { + action("CreateIdentityPool") + .body("{\"IdentityPoolName\": \"missing member\"}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value null at 'allowUnauthenticatedIdentities'" + + " failed to satisfy constraint: Member must not be null")); + } + + @Test + @Order(17) + void tagResourceWithCrossRegionArnWritesBackToThePoolRegion() { + String euPoolId = action("CreateIdentityPool") + .header("Authorization", EU_WEST_1_AUTHORIZATION) + .body("{\"IdentityPoolName\": \"eu pool\", \"AllowUnauthenticatedIdentities\": false}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolId", matchesPattern("eu-west-1:[0-9a-f-]{36}")) + .extract().path("IdentityPoolId"); + String euPoolArn = "arn:aws:cognito-identity:eu-west-1:000000000000:identitypool/" + euPoolId; + + action("TagResource") + .body(""" + {"ResourceArn": "%s", "Tags": {"env": "eu"}} + """.formatted(euPoolArn)) + .when() + .post("/") + .then() + .statusCode(200); + + action("DescribeIdentityPool") + .header("Authorization", EU_WEST_1_AUTHORIZATION) + .body("{\"IdentityPoolId\": \"" + euPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPoolTags.env", equalTo("eu")); + + action("DescribeIdentityPool") + .body("{\"IdentityPoolId\": \"" + euPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + + action("ListIdentityPools") + .body("{\"MaxResults\": 60}") + .when() + .post("/") + .then() + .statusCode(200) + .body("IdentityPools.IdentityPoolId", not(hasItem(euPoolId))); + + action("DeleteIdentityPool") + .header("Authorization", EU_WEST_1_AUTHORIZATION) + .body("{\"IdentityPoolId\": \"" + euPoolId + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(18) + void createIdentityPoolRejectsNonBooleanAllowUnauthenticatedIdentities() { + action("CreateIdentityPool") + .body("{\"IdentityPoolName\": \"wrong type\", \"AllowUnauthenticatedIdentities\": \"true\"}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("AllowUnauthenticatedIdentities must be a boolean.")); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 4c471c6423..f3daf8d7a4 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -375,6 +375,8 @@ floci: enabled: true connect: enabled: true + cognitoidentity: + enabled: true aps: enabled: true lakeformation: diff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yaml index 0e8b847d08..0b1bdfcc12 100644 --- a/tools/docs/service_matrix.yaml +++ b/tools/docs/service_matrix.yaml @@ -33,6 +33,7 @@ aliases: monitoring: cloudwatch # CloudWatch Metrics facet, at cloudwatch.md#metrics secretsmanager: secrets-manager codeguru-reviewer: codegurureviewer # SigV4 signing name is hyphenated; the doc slug is not + cognito-identity: cognitoidentity # SigV4 signing name is hyphenated; the doc slug is not servicecatalog: service-catalog cognito-idp: cognito # Cognito's SigV4 signing name states: step-functions # Step Functions' SigV4 signing name diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index a6bdb971f7..e20a0e6102 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -166,6 +166,10 @@ services: # SubnetIds / VpcSecurityGroupIds / TagKeys are labels of an inner member-name # switch (memberKeyRegex), not actions — same shape as the rds exclusions above. exclude_actions: [SubnetIds, VpcSecurityGroupIds, TagKeys] + - service: cognitoidentity + doc: docs/services/cognitoidentity.md + sources: + - { path: src/main/java/io/github/hectorvent/floci/services/cognitoidentity/CognitoIdentityJsonHandler.java, mode: switch } - service: route53 doc: docs/services/route53.md sources: