diff --git a/docs/services/iam.md b/docs/services/iam.md index 1336c0e2ae..bd77dffdbb 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3203,8 +3203,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, and ACM for its certificates. Tag keys differing only in case are one condition key holding every - value. + instances, ACM for its certificates, and Firehose for its delivery streams. 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 diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 4e986d8ee2..6c261fc898 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -44,9 +44,10 @@ import java.util.Optional; * another account an association runs and the tags of a parameter, a document or an association; CloudFront, for the * 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); looked up lazily by - * {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through {@code Instance} for - * the namespace a request or an ARN is of, so IAM never depends on that service directly.

+ * provider, a task or a container instance; ACM, for the tags of a certificate; Firehose, for the tags of a delivery + * stream); looked up lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through + * {@code Instance} for the namespace a request or an ARN is of, so IAM never depends on that + * service directly.

* *

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 diff --git a/src/main/java/io/floci/aws/services/firehose/FirehoseService.java b/src/main/java/io/floci/aws/services/firehose/FirehoseService.java index b53f5496aa..b682ecb4c9 100644 --- a/src/main/java/io/floci/aws/services/firehose/FirehoseService.java +++ b/src/main/java/io/floci/aws/services/firehose/FirehoseService.java @@ -6,6 +6,7 @@ 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.RequestScopes; +import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; @@ -53,10 +54,12 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; @ApplicationScoped -public class FirehoseService implements ResourceProvider { +public class FirehoseService implements ResourceProvider, StoredResourceArns { private static final Logger LOG = Logger.getLogger(FirehoseService.class); private static final String DEFAULT_BUCKET = "floci-firehose-results"; + /** The resource part of a delivery stream's ARN, before its name. */ + private static final String STREAM_RESOURCE = "deliverystream/"; private static final int DEFAULT_BUFFERING_INTERVAL_SECONDS = 300; private static final int DEFAULT_REDSHIFT_RETRY_SECONDS = 3600; // AWS retries a failed Redshift load every 5 minutes. @@ -131,7 +134,8 @@ public class FirehoseService implements ResourceProvider { private final Map> redshiftPending = new ConcurrentHashMap<>(); // Tracks streams that currently have a drain task queued or running on redshiftDeliveryExecutor. private final Set activeRedshiftDrains = ConcurrentHashMap.newKeySet(); - // Serialises the read, version check, merge and write of a Redshift UpdateDestination per stream. + // Serialises per stream the read, version check, merge and write of a Redshift UpdateDestination, a delete, and + // the read and write of a tag call. private final Map redshiftUpdateLocks = new ConcurrentHashMap<>(); private final Clock clock; private final long tickIntervalSeconds; @@ -426,7 +430,7 @@ public class FirehoseService implements ResourceProvider { s3Config.canonicalizeProcessors(); } String arn = AwsArnUtils.Arn.of("firehose", region, accountId, - "deliverystream/" + name).toString(); + STREAM_RESOURCE + name).toString(); // CreateDeliveryStream's KinesisStreamSourceConfiguration carries only the ARN and // role -- DeliveryStartTimestamp exists only on the Description shape, which AWS // fills in at creation. Stamping it here, at creation time, is what makes the first @@ -816,35 +820,87 @@ public class FirehoseService implements ResourceProvider { return view; } + /** + * Under the lock a delete and a Redshift update hold across their read and write, so a tag call neither writes + * back a stream deleted after it read it nor loses another tag call's change. + */ public void tagDeliveryStream(String name, List tagsToTag) { - DeliveryStreamDescription stream = describeDeliveryStream(name); - Map tagMap = new LinkedHashMap<>(); - for (DeliveryStreamDescription.Tag t : stream.getTags()) { - tagMap.put(t.getKey(), t.getValue()); + String streamKey = scopedKey(name); + synchronized (redshiftUpdateLocks.computeIfAbsent(streamKey, k -> new Object())) { + DeliveryStreamDescription stream = describeDeliveryStream(streamKey, name); + Map tagMap = new LinkedHashMap<>(); + for (DeliveryStreamDescription.Tag t : stream.getTags()) { + tagMap.put(t.getKey(), t.getValue()); + } + for (DeliveryStreamDescription.Tag t : tagsToTag) { + tagMap.put(t.getKey(), t.getValue()); + } + List newTags = new ArrayList<>(); + tagMap.forEach((k, v) -> newTags.add(new DeliveryStreamDescription.Tag(k, v))); + stream.setTags(newTags); + streamPut(streamKey, stream); } - for (DeliveryStreamDescription.Tag t : tagsToTag) { - tagMap.put(t.getKey(), t.getValue()); - } - List newTags = new ArrayList<>(); - tagMap.forEach((k, v) -> newTags.add(new DeliveryStreamDescription.Tag(k, v))); - stream.setTags(newTags); - streamPut(scopedKey(name), stream); LOG.infov("Tagged Firehose delivery stream {0}: {1}", name, tagsToTag); } + /** Under the same lock as {@link #tagDeliveryStream}. */ public void untagDeliveryStream(String name, List tagKeys) { - DeliveryStreamDescription stream = describeDeliveryStream(name); - List newTags = new ArrayList<>(); - for (DeliveryStreamDescription.Tag t : stream.getTags()) { - if (!tagKeys.contains(t.getKey())) { - newTags.add(t); + String streamKey = scopedKey(name); + synchronized (redshiftUpdateLocks.computeIfAbsent(streamKey, k -> new Object())) { + DeliveryStreamDescription stream = describeDeliveryStream(streamKey, name); + List newTags = new ArrayList<>(); + for (DeliveryStreamDescription.Tag t : stream.getTags()) { + if (!tagKeys.contains(t.getKey())) { + newTags.add(t); + } } + stream.setTags(newTags); + streamPut(streamKey, stream); } - stream.setTags(newTags); - streamPut(scopedKey(name), stream); LOG.infov("Untagged Firehose delivery stream {0}: {1}", name, tagKeys); } + @Override + public String namespace() { + return "firehose"; + } + + /** A request names a delivery stream by its name, which its ARN carries whole, so there is nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + /** + * The tags of the delivery stream 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 stream's key in the ARN's Region, or the account's + * key from before the key named the Region, as the handlers find it, and matched on the whole ARN. A tag call + * stores a new list, so the read is of one whole set. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "firehose")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String account = parsed.accountId(); + String region = parsed.region(); + if (!account.equals(regionResolver.getAccountId()) || !parsed.resource().startsWith(STREAM_RESOURCE)) { + return Map.of(); + } + String name = parsed.resource().substring(STREAM_RESOURCE.length()); + Map tags = new LinkedHashMap<>(); + streamStore.getForAccount(account, logicalKeyFromScopedKey(scopedKey(account, region, name))) + .or(() -> streamStore.getForAccount(account, name)) + .filter(stream -> belongsTo(account, region, stream) && arn.equals(stream.getDeliveryStreamARN())) + .ifPresent(stream -> stream.getTags().forEach(tag -> { + if (tag.getKey() != null && tag.getValue() != null) { + tags.put(tag.getKey(), tag.getValue()); + } + })); + return tags; + } + public List listTagsForDeliveryStream(String name, String exclusiveStartTagKey, Integer limit) { DeliveryStreamDescription stream = describeDeliveryStream(name); List tags = stream.getTags(); diff --git a/src/main/java/io/floci/aws/services/firehose/model/DeliveryStreamDescription.java b/src/main/java/io/floci/aws/services/firehose/model/DeliveryStreamDescription.java index cf8b79ebed..c4898ebe6f 100644 --- a/src/main/java/io/floci/aws/services/firehose/model/DeliveryStreamDescription.java +++ b/src/main/java/io/floci/aws/services/firehose/model/DeliveryStreamDescription.java @@ -42,7 +42,7 @@ public class DeliveryStreamDescription { @JsonInclude(JsonInclude.Include.NON_NULL) private Source source; @JsonProperty("Tags") - private List tags = new ArrayList<>(); + private volatile List tags = new ArrayList<>(); // Field-level default so streams persisted before this field existed deserialize to // the AWS-shaped DISABLED configuration instead of null (Jackson only overwrites it diff --git a/src/test/java/io/floci/aws/services/firehose/FirehoseServiceTest.java b/src/test/java/io/floci/aws/services/firehose/FirehoseServiceTest.java index 4cae5a19b8..2d18d3c78f 100644 --- a/src/test/java/io/floci/aws/services/firehose/FirehoseServiceTest.java +++ b/src/test/java/io/floci/aws/services/firehose/FirehoseServiceTest.java @@ -239,6 +239,35 @@ class FirehoseServiceTest { "legacy entries from another region must not be adopted"); } + /** + * IAM's tag lookup reads the tags of the delivery stream whose ARN it is given, as tag calls leave them, and those + * of one stored under the account's key from before the key named the Region, in place, without migrating it; + * nothing for an ARN of another account or Region, or of no stream. + */ + @Test + @SuppressWarnings("unchecked") + void storedTagsAreTheTagsOfTheDeliveryStreamTheArnNames() { + String arn = firehoseService.createDeliveryStream("tagged", null); + firehoseService.tagDeliveryStream("tagged", List.of(new DeliveryStreamDescription.Tag("team", "data"), + new DeliveryStreamDescription.Tag("env", "test"))); + firehoseService.untagDeliveryStream("tagged", List.of("env")); + String legacyArn = "arn:aws:firehose:us-east-1:000000000000:deliverystream/legacy"; + DeliveryStreamDescription legacy = new DeliveryStreamDescription("legacy", legacyArn, null, null); + legacy.setAccountId("000000000000"); + legacy.setTags(List.of(new DeliveryStreamDescription.Tag("tier", "web"))); + AccountAwareStorageBackend streams = + (AccountAwareStorageBackend) backends.get("firehose/streams.json"); + streams.putForAccount("000000000000", "legacy", legacy); + + assertEquals(Map.of("team", "data"), firehoseService.storedTags(arn)); + assertEquals(Map.of("tier", "web"), firehoseService.storedTags(legacyArn)); + assertTrue(streams.getForAccount("000000000000", "legacy").isPresent()); + assertEquals(Map.of(), firehoseService.storedTags(arn.replace(":000000000000:", ":111122223333:"))); + assertEquals(Map.of(), firehoseService.storedTags(arn.replace(":us-east-1:", ":eu-west-1:"))); + assertEquals(Map.of(), firehoseService.storedTags(arn + "0")); + assertEquals(Map.of(), firehoseService.storedTags("arn:aws:s3:::tagged")); + } + @Test @SuppressWarnings("unchecked") void aPersistedRedshiftBackupGetsTheDefaultsOnDescribe() { diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index bc1a724bab..0aefc03476 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -804,6 +804,32 @@ class IamRequestResourceEnforcementIntegrationTest { refusedJson(describeDeliveryStream(user, name + "-other"), "firehose:DescribeDeliveryStream"); } + /** + * An {@code aws:ResourceTag} condition reads the tags Firehose holds on the delivery stream a request names, as a + * tag call leaves them, so an allow on one team's tag lets the caller describe that team's stream and not + * another's. + */ + @Test + void aFirehoseResourceTagConditionReadsTheTagsOfTheDeliveryStream() { + String tagged = deliveryStream("res-tag-stream-" + suffix(), "web"); + String other = deliveryStream("res-tag-stream-" + suffix(), "web"); + adminJson("firehose", "Firehose_20150804.TagDeliveryStream").body("{\"DeliveryStreamName\":\"" + tagged + + "\",\"Tags\":" + teamTag("data") + "}").post("/").then().statusCode(200); + + User user = user("res-stream-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"firehose:DescribeDeliveryStream\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + describeDeliveryStream(user, tagged).statusCode(200); + refusedJson(describeDeliveryStream(user, other), "firehose:DescribeDeliveryStream"); + } + + /** A Firehose delivery stream of the name, tagged with the team, deleted afterwards. */ + private String deliveryStream(String name, String team) { + return created("firehose", "Firehose_20150804.CreateDeliveryStream", "{\"DeliveryStreamName\":\"" + name + + "\",\"Tags\":" + teamTag(team) + "}", "Firehose_20150804.DeleteDeliveryStream", + "{\"DeliveryStreamName\":\"" + name + "\"}", name); + } + /** An identity pool is checked on the ARN its id gives, the one Cognito tags it under. */ @Test void anIdentityPoolIsCheckedOnTheArnItsIdGives() {