fix(kinesisanalytics): give resource-tag conditions the tags of the application a request names (#8794)

The generated request resources give Managed Service for Apache Flink's
application type the aws:ResourceTag/ key, but no service answered the
kinesisanalytics namespace's stored tags, so a condition on an
application's tags saw none. KinesisAnalyticsV2Service now answers it:
storedTags reads the application stored under the Region the ARN names
and its name, and in the default Region under the name alone, in the
request's account, where the handlers read, in place, and matched on the
whole ARN; a read that misses both keys while a legacy record moves
looks under the Regional key again. TagResource took no lock and
UntagResource changed the map in place; both now give the application a
new map one call at a time, and the tags field is volatile.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 20:03:10 -04:00
1 parent 4b342dad3f
commit 5110042f6c
6 files changed
+164 -23

No files matched your search

+3 -2
View File
@@ -3315,8 +3315,9 @@ floci populates:
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 identity
pools, OpenSearch for its domains, Signer for its signing profiles, and Access Analyzer for its analyzers. Tag keys
differing only in case are one condition key holding every value.
pools, OpenSearch for its domains, Signer for its signing profiles, Access Analyzer for its analyzers, and Managed
Service for Apache Flink for its applications. 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
@@ -46,9 +46,10 @@ import java.util.Optional;
* 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 or an identity pool; OpenSearch, for the tags of a domain; Signer, for
* the tags of a signing profile; Access Analyzer, for the tags of an analyzer); 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>
* the tags of a signing profile; Access Analyzer, for the tags of an analyzer; Managed Service for Apache Flink, for
* the tags of an application); 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
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
@@ -45,7 +46,7 @@ import java.util.regex.Pattern;
* {@code READY}.
*/
@ApplicationScoped
public class KinesisAnalyticsV2Service {
public class KinesisAnalyticsV2Service implements StoredResourceArns {
private static final Logger LOG = Logger.getLogger(KinesisAnalyticsV2Service.class);
@@ -56,6 +57,9 @@ public class KinesisAnalyticsV2Service {
// on the Tags/TagKeys shapes includes AWS-managed system tags, which floci does not model).
private static final int MAX_USER_TAGS = 50;
/** What an application's ARN resource starts with, its name following. */
private static final String APPLICATION_RESOURCE = "application/";
// CreateApplicationPresignedUrl's SessionExpirationDurationInSeconds valid range (30 min - 12 hr).
private static final long MIN_SESSION_EXPIRATION_SECONDS = 1800;
private static final long MAX_SESSION_EXPIRATION_SECONDS = 43200;
@@ -183,7 +187,7 @@ public class KinesisAnalyticsV2Service {
String accountId = regionResolver.getAccountId();
String arn = AwsArnUtils.Arn.of("kinesisanalytics", region, accountId,
"application/" + applicationName).toString();
APPLICATION_RESOURCE + applicationName).toString();
String mode = (applicationMode == null || applicationMode.isBlank()) ? "STREAMING" : applicationMode;
FlinkApplication app = new FlinkApplication(applicationName, arn, runtimeEnvironment,
@@ -470,7 +474,11 @@ public class KinesisAnalyticsV2Service {
return findByArn(resourceArn).getTags();
}
public Map<String, String> tagResource(String resourceArn, Map<String, String> tags) {
/**
* Gives the application a new map holding its tags and {@code tags}. Tag calls run one at a time, so two of them
* never lose one's tags, and a lookup reads one whole set.
*/
public synchronized Map<String, String> tagResource(String resourceArn, Map<String, String> tags) {
FlinkApplication app = findByArn(resourceArn);
Map<String, String> merged = new LinkedHashMap<>(app.getTags());
if (tags != null) {
@@ -485,15 +493,63 @@ public class KinesisAnalyticsV2Service {
return app.getTags();
}
public Map<String, String> untagResource(String resourceArn, List<String> tagKeys) {
/** Gives the application a new map without {@code tagKeys}, one tag call at a time, as {@link #tagResource}. */
public synchronized Map<String, String> untagResource(String resourceArn, List<String> tagKeys) {
FlinkApplication app = findByArn(resourceArn);
Map<String, String> remaining = new LinkedHashMap<>(app.getTags());
if (tagKeys != null) {
tagKeys.forEach(app.getTags()::remove);
tagKeys.forEach(remaining::remove);
}
app.setTags(remaining);
putApplication(app);
return app.getTags();
}
@Override
public String namespace() {
return "kinesisanalytics";
}
/** A request names an application by its name, which its ARN carries whole: nothing to find. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/**
* The tags of the application 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 application's name, and in
* the default Region under the name alone, where an application stored before applications were kept by Region
* still is, a record stored before storage was account-aware included, and matched on the whole ARN. Moving such
* an application to its Regional key puts it there before deleting the name alone, so a read that misses both
* while it moves looks under the Regional key again. Tag calls give the application a new map, so the read is of
* one whole set.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, "kinesisanalytics")) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String account = regionResolver.getAccountId();
if (!parsed.accountId().equals(account) || !parsed.resource().startsWith(APPLICATION_RESOURCE)) {
return Map.of();
}
String name = parsed.resource().substring(APPLICATION_RESOURCE.length());
String key = applicationKey(parsed.region(), name);
Optional<FlinkApplication> application = storedApplication(account, key, arn);
if (application.isEmpty() && parsed.region().equals(config.defaultRegion())) {
application = storedApplication(account, name, arn).or(() -> storedApplication(account, key, arn));
}
return application.map(app -> new LinkedHashMap<>(app.getTags())).orElseGet(LinkedHashMap::new);
}
/** The application stored under {@code key} in {@code account}, read in place, if its ARN is {@code arn}. */
private Optional<FlinkApplication> storedApplication(String account, String key, String arn) {
return AccountAwareStorageBackend.readInAccount(storage, account, key)
.filter(app -> arn.equals(app.getApplicationArn()));
}
public Snapshot createApplicationSnapshot(String applicationName, String snapshotName) {
return createApplicationSnapshot(applicationName, snapshotName, config.defaultRegion());
}
@@ -648,18 +704,17 @@ public class KinesisAnalyticsV2Service {
throw new AwsException("InvalidArgumentException", "Invalid resource ARN: " + resourceArn, 400);
}
String accountId = regionResolver.getAccountId();
String resourcePrefix = "application/";
if (!"kinesisanalytics".equals(arn.service())
|| !arn.resource().startsWith(resourcePrefix)
|| arn.resource().length() == resourcePrefix.length()
|| arn.resource().substring(resourcePrefix.length()).contains("/")) {
|| !arn.resource().startsWith(APPLICATION_RESOURCE)
|| arn.resource().length() == APPLICATION_RESOURCE.length()
|| arn.resource().substring(APPLICATION_RESOURCE.length()).contains("/")) {
throw new AwsException("InvalidArgumentException", "Invalid resource ARN: " + resourceArn, 400);
}
if (!accountId.equals(arn.accountId())) {
throw new AwsException("ResourceNotFoundException",
"No application found for ARN: " + resourceArn, 400);
}
String applicationName = arn.resource().substring(resourcePrefix.length());
String applicationName = arn.resource().substring(APPLICATION_RESOURCE.length());
String region = arn.region().isEmpty() ? config.defaultRegion() : arn.region();
return getStoredApplication(accountId, region, applicationName)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
@@ -98,7 +98,7 @@ public class FlinkApplication {
// Resource tags. Real AWS never echoes these in ApplicationDetail (CreateApplication /
// DescribeApplication) — only ListTagsForResource returns them — so this is bookkeeping only,
// like containerId/accountId above, not part of the wire response the handler builds.
private Map<String, String> tags = new LinkedHashMap<>();
private volatile Map<String, String> tags = new LinkedHashMap<>();
// ApplicationConfiguration.EnvironmentProperties.PropertyGroups, keyed by PropertyGroupId (the
// key a Flink app looks it up by via KinesisAnalyticsRuntime.getApplicationProperties()). Echoed
@@ -1222,9 +1222,47 @@ class IamRequestResourceEnforcementIntegrationTest {
@Test
void anApplicationIsCheckedOnTheArnItsNameGives() {
String name = "res-app-" + suffix();
String arn = application(name, null);
assertEquals("arn:aws:kinesisanalytics:" + REGION + ":" + ACCOUNT + ":application/" + name, arn);
User user = user("res-application");
user.policy(allowOn("kinesisanalytics:DescribeApplication", arn));
describeApplication(user, name).statusCode(200);
refusedJson(describeApplication(user, name + "-other"), "kinesisanalytics:DescribeApplication");
}
/**
* An {@code aws:ResourceTag} condition reads the tags Managed Service for Apache Flink holds on the application a
* request names, as TagResource leaves them, so an allow on one team's tag lets the caller describe that team's
* application and not another's.
*/
@Test
void aKinesisAnalyticsResourceTagConditionReadsTheTagsOfTheApplication() {
String web = "[{\"Key\":\"team\",\"Value\":\"web\"}]";
String tagged = "res-app-tagged-" + suffix();
String other = "res-app-other-" + suffix();
String taggedArn = application(tagged, web);
application(other, web);
adminJson("kinesisanalytics", "KinesisAnalytics_20180523.TagResource")
.body("{\"ResourceARN\":\"" + taggedArn + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}")
.post("/").then().statusCode(200);
User user = user("res-application-tags");
user.policy("{\"Effect\":\"Allow\",\"Action\":\"kinesisanalytics:DescribeApplication\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}");
describeApplication(user, tagged).statusCode(200);
refusedJson(describeApplication(user, other), "kinesisanalytics:DescribeApplication");
}
/**
* The ARN of the application {@code name} an administrator creates, with the {@code tags} list if any, deleted
* afterwards.
*/
private String application(String name, String tags) {
String arn = adminJson("kinesisanalytics", "KinesisAnalytics_20180523.CreateApplication")
.body("{\"ApplicationName\":\"" + name + "\",\"RuntimeEnvironment\":\"FLINK-1_18\","
+ "\"ServiceExecutionRole\":\"arn:aws:iam::" + ACCOUNT + ":role/flink-role\"}")
+ "\"ServiceExecutionRole\":\"arn:aws:iam::" + ACCOUNT + ":role/flink-role\""
+ (tags == null ? "" : ",\"Tags\":" + tags) + "}")
.post("/").then().statusCode(200).extract().path("ApplicationDetail.ApplicationARN");
cleanup.register(() -> adminJson("kinesisanalytics", "KinesisAnalytics_20180523.DeleteApplication")
.body("{\"ApplicationName\":\"" + name + "\",\"CreateTimestamp\":"
@@ -1232,12 +1270,7 @@ class IamRequestResourceEnforcementIntegrationTest {
.body("{\"ApplicationName\":\"" + name + "\"}").post("/").then().statusCode(200).extract()
.jsonPath(new JsonPathConfig(JsonPathConfig.NumberReturnType.BIG_DECIMAL))
.getString("ApplicationDetail.CreateTimestamp") + "}").post("/"));
assertEquals("arn:aws:kinesisanalytics:" + REGION + ":" + ACCOUNT + ":application/" + name, arn);
User user = user("res-application");
user.policy(allowOn("kinesisanalytics:DescribeApplication", arn));
describeApplication(user, name).statusCode(200);
refusedJson(describeApplication(user, name + "-other"), "kinesisanalytics:DescribeApplication");
return arn;
}
/**
@@ -5,6 +5,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.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.kinesisanalytics.container.FlinkContainerManager;
import io.floci.aws.services.kinesisanalytics.model.ApplicationStatus;
@@ -19,6 +20,7 @@ import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -391,6 +393,55 @@ class KinesisAnalyticsV2ServiceTest {
assertEquals("dev", after.get("env"));
}
/**
* IAM's lookup reads the tags the application the ARN names holds, as the tag calls leave them, and nothing for
* another account's, another Region's or an unknown application; a tag call puts a new map, so one a reader
* already holds stays as it was.
*/
@Test
void storedTagsAreTheTagsOfTheApplicationTheArnNamesAndTaggingPutsANewMap() {
FlinkApplication app = create("demo");
String arn = app.getApplicationArn();
service.tagResource(arn, Map.of("team", "data", "env", "dev"));
Map<String, String> held = app.getTags();
service.untagResource(arn, List.of("env"));
assertEquals(Map.of("team", "data", "env", "dev"), held);
assertEquals("kinesisanalytics", service.namespace());
assertEquals(Map.of("team", "data"), service.storedTags(arn));
assertTrue(service.storedTags(arn.replace("000000000000", "111122223333")).isEmpty());
assertTrue(service.storedTags(arn.replace("us-east-1", "us-west-2")).isEmpty());
assertTrue(service.storedTags(arn.replace("application/demo", "application/nope")).isEmpty());
assertTrue(service.storedTags("arn:aws:kinesis:us-east-1:000000000000:stream/demo").isEmpty());
}
/**
* An application stored under its name alone, before applications were kept by Region, or before storage was
* account-aware, is read where the handlers find it, in place: the lookup migrates nothing.
*/
@Test
void storedTagsReadALegacyRecordInPlaceWithoutMigratingIt() {
InMemoryStorage<String, FlinkApplication> raw = new InMemoryStorage<>();
KinesisAnalyticsV2Service legacyState =
mockModeService(new AccountAwareStorageBackend<>(raw, null, "000000000000"));
FlinkApplication byName = legacyApplication("by-name");
byName.setTags(Map.of("team", "data"));
raw.put("000000000000/by-name", byName);
FlinkApplication bare = legacyApplication("bare");
bare.setTags(Map.of("team", "ops"));
raw.put("bare", bare);
FlinkApplication unscoped = legacyApplication("unscoped");
unscoped.setTags(Map.of("team", "web"));
raw.put("us-east-1/unscoped", unscoped);
assertEquals(Map.of("team", "data"), legacyState.storedTags(byName.getApplicationArn()));
assertEquals(Map.of("team", "ops"), legacyState.storedTags(bare.getApplicationArn()));
assertEquals(Map.of("team", "web"), legacyState.storedTags(unscoped.getApplicationArn()));
assertTrue(legacyState.storedTags(byName.getApplicationArn().replace("us-east-1", "us-west-2")).isEmpty());
assertEquals(Set.of("000000000000/by-name", "bare", "us-east-1/unscoped"), raw.keys());
}
@Test
void tagResourceRejectsUnknownArn() {
assertThrows(AwsException.class, () -> service.tagResource(