fix(cognito-identity): give resource-tag conditions the tags of the identity pool a request names (#8765)

The generated request resources give Cognito identity pools'
identitypool type the aws:ResourceTag/ key, but no service answered the
cognito-identity namespace's stored tags, so a condition on an identity
pool's tags saw none. CognitoIdentityService now answers it: storedTags
reads the pool stored under the Region the ARN names and its id, in the
request's account, where the tag handlers read, in place, and matched on
the whole ARN. TagResource and UntagResource changed the pool's map in
place with no lock; they now give it a new map one call at a time, and
the tags field is volatile. UpdateIdentityPool, which sets the tags
too, replaces the pool under the same lock.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 14:48:33 -04:00
1 parent f64dea0ba5
commit 45aeeb0652
6 files changed
+165 -21

No files matched your search

+2 -2
View File
@@ -3307,8 +3307,8 @@ floci populates:
permission sets, applications and trusted token issuers, OAM for its sinks and links, RAM for its resource shares,
Payment Cryptography for its keys, Resource Explorer for its indexes and views, Application Auto Scaling for its
scalable targets, ECS for its clusters, task definitions, services, capacity providers, tasks and container
instances, ACM for its certificates, Firehose for its delivery streams, Cognito for its user pools, and OpenSearch
for its domains. Tag keys differing only in case are one condition key holding every value.
instances, ACM for its certificates, Firehose for its delivery streams, Cognito for its user pools and identity
pools, and OpenSearch for its domains. Tag keys differing only in case are one condition key holding every value.
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
@@ -45,9 +45,10 @@ import java.util.Optional;
* key value store a name names and the tags of any resource it tags; ECS, for the revision a task definition
* reference resolves to, its default cluster and the tags of a cluster, a task definition, a service, a capacity
* provider, a task or a container instance; ACM, for the tags of a certificate; Firehose, for the tags of a delivery
* stream; Cognito, for the tags of a user pool; OpenSearch, for the tags of a domain); looked up lazily by
* {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for
* the namespace a request or an ARN is of, so IAM never depends on that service directly.</p>
* stream; Cognito, for the tags of a user pool or an identity pool; OpenSearch, for the tags of a domain); looked up
* lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through
* {@code Instance<StoredResourceArns>} for the namespace a request or an ARN is of, so IAM never depends on that
* service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.cognitoidentity.model.IdentityPool;
@@ -18,6 +20,7 @@ import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
@@ -30,7 +33,7 @@ import java.util.regex.Pattern;
* that parses either gets the same structure it would from AWS.
*/
@ApplicationScoped
public class CognitoIdentityService {
public class CognitoIdentityService implements StoredResourceArns {
private static final Logger LOG = Logger.getLogger(CognitoIdentityService.class);
@@ -78,9 +81,11 @@ public class CognitoIdentityService {
* {@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.
* operations and are not part of the shape, so they survive the replace. The shape carries
* the tags, so the replace runs one at a time with the tag calls, which never write back a
* pool it replaced.
*/
public IdentityPool updateIdentityPool(IdentityPool spec, String region) {
public synchronized IdentityPool updateIdentityPool(IdentityPool spec, String region) {
IdentityPool existing = describeIdentityPool(spec.getIdentityPoolId(), region);
validatePoolConfiguration(spec);
@@ -201,24 +206,67 @@ public class CognitoIdentityService {
return findByArn(resourceArn, region).getIdentityPoolTags();
}
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
/**
* Gives the pool a new map, one tag call at a time, so a reader holds one whole set and no call loses another's.
*/
public synchronized void tagResource(String resourceArn, Map<String, String> 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);
Map<String, String> updated = new LinkedHashMap<>(pool.getIdentityPoolTags());
updated.putAll(tags);
pool.setIdentityPoolTags(updated);
pools.put(storageKey(pool), pool);
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
/** As {@link #tagResource}, a new map one call at a time. */
public synchronized void untagResource(String resourceArn, List<String> 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);
Map<String, String> updated = new LinkedHashMap<>(pool.getIdentityPoolTags());
tagKeys.forEach(updated::remove);
pool.setIdentityPoolTags(updated);
pools.put(storageKey(pool), pool);
}
@Override
public String namespace() {
return "cognito-identity";
}
/** A request names an identity pool by the id Cognito minted, which its ARN ends in: nothing to find. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/**
* The tags of the identity pool whose ARN is {@code arn}, in the request's account, where the handlers read: an ARN
* of another account names none. Read in place under the Region the ARN names and the pool's id, as the tag
* handlers read it, a pool stored before storage was account-aware included, and matched on the whole ARN. Tag
* calls give the pool a new map, so the read is of one whole set.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, "cognito-identity")) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
if (!parsed.accountId().equals(regionResolver.getAccountId())
|| !parsed.resource().startsWith(ARN_RESOURCE_PREFIX)) {
return Map.of();
}
Map<String, String> tags = AccountAwareStorageBackend.readInAccount(pools, parsed.accountId(),
storageKey(parsed.region(), parsed.resource().substring(ARN_RESOURCE_PREFIX.length())))
.filter(pool -> arn.equals(pool.getArn()))
.map(IdentityPool::getIdentityPoolTags)
.orElse(Map.of());
return new LinkedHashMap<>(tags);
}
// ──────────────────────────── Helpers ────────────────────────────
/** One page of {@code ListIdentityPools} results plus the token for the page after it. */
@@ -29,7 +29,7 @@ public class IdentityPool {
private List<String> openIdConnectProviderArns = new ArrayList<>();
private List<CognitoIdentityProvider> cognitoIdentityProviders = new ArrayList<>();
private List<String> samlProviderArns = new ArrayList<>();
private Map<String, String> identityPoolTags = new LinkedHashMap<>();
private volatile Map<String, String> identityPoolTags = new LinkedHashMap<>();
private String arn;
private String accountId;
@@ -0,0 +1,62 @@
package io.floci.aws.services.cognitoidentity;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.cognitoidentity.model.IdentityPool;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CognitoIdentityServiceTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private final InMemoryStorage<String, IdentityPool> raw = new InMemoryStorage<>();
private final CognitoIdentityService service = new CognitoIdentityService(
new InMemoryStorageFactory(ACCOUNT).withStore("cognitoidentity-pools.json",
new AccountAwareStorageBackend<>(raw, null, ACCOUNT)),
new RegionResolver(REGION, ACCOUNT));
/**
* IAM's tag lookup reads the tags of the identity pool whose ARN it is given, as tag calls leave them, a tag call
* giving the pool a new map rather than changing the one a reader holds, and those of a pool stored before storage
* was account-aware, in place, without migrating it; nothing for an ARN of another account or Region, or of no
* pool.
*/
@Test
void storedTagsAreTheTagsOfTheIdentityPoolTheArnNamesAndTaggingPutsANewMap() {
IdentityPool spec = new IdentityPool();
spec.setIdentityPoolName("tagged");
spec.setIdentityPoolTags(new LinkedHashMap<>(Map.of("env", "dev")));
String arn = service.createIdentityPool(spec, REGION).getArn();
Map<String, String> held = service.listTagsForResource(arn, REGION);
service.tagResource(arn, Map.of("team", "data"), REGION);
service.untagResource(arn, List.of("env"), REGION);
String legacyId = REGION + ":0b6b2c1e-1f6e-4d7a-9a51-3c1f7f0e2d4a";
String legacyArn = "arn:aws:cognito-identity:" + REGION + ":" + ACCOUNT + ":identitypool/" + legacyId;
IdentityPool legacy = new IdentityPool();
legacy.setIdentityPoolId(legacyId);
legacy.setIdentityPoolName("legacy");
legacy.setArn(legacyArn);
legacy.setIdentityPoolTags(Map.of("tier", "web"));
raw.put(REGION + "::" + legacyId, legacy);
assertEquals(Map.of("env", "dev"), held);
assertEquals(Map.of("team", "data"), service.storedTags(arn));
assertEquals(Map.of("tier", "web"), service.storedTags(legacyArn));
assertTrue(raw.get(REGION + "::" + legacyId).isPresent());
assertEquals(Map.of(), service.storedTags(arn.replace(":" + ACCOUNT + ":", ":111122223333:")));
assertEquals(Map.of(), service.storedTags(arn.replace(":" + REGION + ":" + ACCOUNT, ":eu-west-1:" + ACCOUNT)));
assertEquals(Map.of(), service.storedTags(arn + "0"));
assertEquals(Map.of(), service.storedTags("arn:aws:cognito-idp:" + REGION + ":" + ACCOUNT + ":userpool/x"));
}
}
@@ -859,14 +859,9 @@ class IamRequestResourceEnforcementIntegrationTest {
/** An identity pool is checked on the ARN its id gives, the one Cognito tags it under. */
@Test
void anIdentityPoolIsCheckedOnTheArnItsIdGives() {
String id = adminJson("cognito-identity", "AWSCognitoIdentityService.CreateIdentityPool")
.body("{\"IdentityPoolName\":\"res pool " + suffix() + "\",\"AllowUnauthenticatedIdentities\":false}")
.post("/").then().statusCode(200).extract().path("IdentityPoolId");
cleanup.register(() -> adminJson("cognito-identity", "AWSCognitoIdentityService.DeleteIdentityPool")
.body("{\"IdentityPoolId\":\"" + id + "\"}").post("/"));
String arn = "arn:aws:cognito-identity:" + REGION + ":" + ACCOUNT + ":identitypool/" + id;
adminJson("cognito-identity", "AWSCognitoIdentityService.TagResource")
.body("{\"ResourceArn\":\"" + arn + "\",\"Tags\":{\"a\":\"b\"}}").post("/").then().statusCode(200);
String id = identityPool(null);
String arn = identityPoolArn(id);
tagIdentityPool(arn, "{\"a\":\"b\"}");
User user = user("res-identity-pool");
user.policy(allowOn("cognito-identity:DescribeIdentityPool", arn));
@@ -874,6 +869,44 @@ class IamRequestResourceEnforcementIntegrationTest {
refusedJson(describeIdentityPool(user, REGION + ":" + UUID.randomUUID()), "cognito-identity:DescribeIdentityPool");
}
/**
* An {@code aws:ResourceTag} condition reads the tags Cognito holds on the identity pool a request names, as
* TagResource leaves them, so an allow on one team's tag lets the caller describe that team's pool and not
* another's.
*/
@Test
void aCognitoIdentityResourceTagConditionReadsTheTagsOfTheIdentityPool() {
String tagged = identityPool("{\"team\":\"web\"}");
String other = identityPool("{\"team\":\"web\"}");
tagIdentityPool(identityPoolArn(tagged), "{\"team\":\"data\"}");
User user = user("res-identity-pool-tags");
user.policy("{\"Effect\":\"Allow\",\"Action\":\"cognito-identity:DescribeIdentityPool\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}");
describeIdentityPool(user, tagged).statusCode(200);
refusedJson(describeIdentityPool(user, other), "cognito-identity:DescribeIdentityPool");
}
/** The id of an identity pool an administrator creates, with the {@code tags} object if any, deleted afterwards. */
private String identityPool(String tags) {
String id = adminJson("cognito-identity", "AWSCognitoIdentityService.CreateIdentityPool")
.body("{\"IdentityPoolName\":\"res pool " + suffix() + "\",\"AllowUnauthenticatedIdentities\":false"
+ (tags == null ? "" : ",\"IdentityPoolTags\":" + tags) + "}")
.post("/").then().statusCode(200).extract().path("IdentityPoolId");
cleanup.register(() -> adminJson("cognito-identity", "AWSCognitoIdentityService.DeleteIdentityPool")
.body("{\"IdentityPoolId\":\"" + id + "\"}").post("/"));
return id;
}
private static String identityPoolArn(String id) {
return "arn:aws:cognito-identity:" + REGION + ":" + ACCOUNT + ":identitypool/" + id;
}
private static void tagIdentityPool(String arn, String tags) {
adminJson("cognito-identity", "AWSCognitoIdentityService.TagResource")
.body("{\"ResourceArn\":\"" + arn + "\",\"Tags\":" + tags + "}").post("/").then().statusCode(200);
}
@Test
void aCloudMapNamespaceAndServiceAreCheckedOnTheArnsTheirIdsGive() {
String namespaceId = cloudMapNamespace("res-ns-" + suffix());