diff --git a/docs/services/iam.md b/docs/services/iam.md index dfa678da20..01fb579aac 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3119,11 +3119,13 @@ floci populates: reads from the Service Reference for every namespace it reads, valued from the tags the type's service holds on that resource (`StoredResourceArns.storedTags`); a service that holds none leaves them absent. Secrets Manager answers for its secrets, S3 Tables for its table buckets and tables, EventBridge Scheduler for - its schedule groups, CloudFormation for its stacks, stack sets and change sets, Lambda for its functions, - their versions and aliases (the function's tags), event source mappings, web functions, their revisions and - endpoints (the web function's tags), MicroVM images and network connectors, and Glue for its schema registries - and schemas and for the jobs, crawlers, triggers, workflows, connections, databases, tables and other resources - it tags. Tag keys differing only in case are one condition key holding every value. + its schedule groups, EventBridge for its event buses and rules, RDS for its resources and DocumentDB's, + CloudFormation for its stacks, stack sets and change sets, Lambda for its functions, their versions and aliases + (the function's tags), event source mappings, web functions, their revisions and endpoints (the web function's + tags), MicroVM images and network connectors, Glue for its schema registries and schemas and for the jobs, + crawlers, triggers, workflows, connections, databases, tables and other resources it tags, and Step Functions for + its state machines, their versions and executions (the state machine's tags) and activities. 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 1867ebc4c6..2d0e7ff4d7 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -30,7 +30,8 @@ import java.util.Optional; * or a change set; S3 Tables, for the table a request names by its table bucket, namespace and name, and the tags of a * table bucket or a table; Lambda, for the layer version a layer version ARN selects, the image of a MicroVM and the * execution of a callback, and the tags of a function, an event source mapping, a web function, a MicroVM image or a - * network connector; Glue, for the tags of a resource it tags); looked up lazily by {@code ResourceArnBuilder} and + * network connector; Glue, for the tags of a resource it tags; Step Functions, for the tags of a state machine, its + * versions and executions, and an activity); 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.

* diff --git a/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java index 3dd0f1eefc..a45f272d72 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java @@ -1510,42 +1510,106 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store throw new AwsException("ResourceNotFound", "Resource not found: " + arn, 400); } - public void tagResource(String arn, Map tags) { + /** + * Puts a new tag map in place of the state machine's or the activity's, never changing one in place, so a reader + * copying it, as {@link #storedTags} does on every request IAM checks, sees one whole set; under the service's lock + * the other state machine writes take, so an update copying the state machine does not lose a tag. + */ + public synchronized void tagResource(String arn, Map tags) { Optional smOpt = stateMachineStore.get(arn); if (smOpt.isPresent()) { StateMachine sm = smOpt.get(); - sm.getTags().putAll(tags); + Map next = new HashMap<>(sm.getTags()); + next.putAll(tags); + sm.setTags(next); stateMachineStore.put(arn, sm); return; } Optional actOpt = activityStore.get(arn); if (actOpt.isPresent()) { Activity activity = actOpt.get(); - activity.getTags().putAll(tags); + Map next = new HashMap<>(activity.getTags()); + next.putAll(tags); + activity.setTags(next); activityStore.put(arn, activity); return; } throw new AwsException("ResourceNotFound", "Resource not found: " + arn, 400); } - public void untagResource(String arn, List tagKeys) { + /** As {@link #tagResource}, without the keys. */ + public synchronized void untagResource(String arn, List tagKeys) { Optional smOpt = stateMachineStore.get(arn); if (smOpt.isPresent()) { StateMachine sm = smOpt.get(); - tagKeys.forEach(sm.getTags()::remove); + Map next = new HashMap<>(sm.getTags()); + tagKeys.forEach(next::remove); + sm.setTags(next); stateMachineStore.put(arn, sm); return; } Optional actOpt = activityStore.get(arn); if (actOpt.isPresent()) { Activity activity = actOpt.get(); - tagKeys.forEach(activity.getTags()::remove); + Map next = new HashMap<>(activity.getTags()); + tagKeys.forEach(next::remove); + activity.setTags(next); activityStore.put(arn, activity); return; } throw new AwsException("ResourceNotFound", "Resource not found: " + arn, 400); } + /** + * The tags of the state machine or the activity stored under {@code arn} in the account and Region it names, read + * in place and matched on the whole ARN; a version and an execution have their state machine's, as all versions + * of a state machine share its tags and its executions inherit them, and an alias has none. Empty for an ARN + * naming nothing stored. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "states")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String account = parsed.accountId(); + String resource = parsed.resource(); + if (resource.startsWith("activity:")) { + return AccountAwareStorageBackend.readInAccount(activityStore, account, arn) + .map(activity -> Map.copyOf(activity.getTags())) + .orElse(Map.of()); + } + if (resource.startsWith("execution:")) { + return AccountAwareStorageBackend.readInAccount(executionStore, account, arn) + .map(execution -> stateMachineTags(account, execution.getStateMachineArn(), null)) + .orElse(Map.of()); + } + String[] stateMachine = resource.split(":", -1); + if (!"stateMachine".equals(stateMachine[0]) || stateMachine.length < 2 || stateMachine.length > 3) { + return Map.of(); + } + if (stateMachine.length == 2) { + return stateMachineTags(account, arn, null); + } + return stateMachine[2].matches("[0-9]+") + ? stateMachineTags(account, arn.substring(0, arn.lastIndexOf(':')), arn) + : Map.of(); + } + + /** The tags of the state machine stored under {@code arn} in the account, when it holds {@code version} if one. */ + private Map stateMachineTags(String account, String arn, String version) { + Optional stored = AccountAwareStorageBackend.readInAccount(stateMachineStore, account, arn); + if (stored.isEmpty() || version != null && !holdsVersion(stored.get(), version)) { + return Map.of(); + } + return Map.copyOf(stored.get().getTags()); + } + + private synchronized boolean holdsVersion(StateMachine stateMachine, String versionArn) { + return stateMachine.getVersions().stream() + .anyMatch(published -> versionArn.equals(published.getStateMachineVersionArn())); + } + public synchronized void replaceStateMachineTags(String arn, Map tags) { StateMachine current = stateMachineStore.get(arn) .orElseThrow(() -> new AwsException( diff --git a/src/main/java/io/floci/aws/services/stepfunctions/model/Activity.java b/src/main/java/io/floci/aws/services/stepfunctions/model/Activity.java index 68aa07b9be..0a5b9ce299 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/model/Activity.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/model/Activity.java @@ -13,7 +13,7 @@ public class Activity { private String activityArn; private String name; private double creationDate; - private Map tags = new HashMap<>(); + private volatile Map tags = new HashMap<>(); public Activity() { this.creationDate = EpochSeconds.fromMillis(System.currentTimeMillis()); diff --git a/src/main/java/io/floci/aws/services/stepfunctions/model/StateMachine.java b/src/main/java/io/floci/aws/services/stepfunctions/model/StateMachine.java index 4404615f6c..28bd2f7a52 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/model/StateMachine.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/model/StateMachine.java @@ -26,7 +26,7 @@ public class StateMachine { private JsonNode loggingConfiguration; private JsonNode tracingConfiguration; private JsonNode encryptionConfiguration; - private Map tags = new HashMap<>(); + private volatile Map tags = new HashMap<>(); private String creationVersionArn; private String creationVersionDescription; private int versionCounter = 0; 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 a7fb86d54d..3bbb3fbae3 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -1860,6 +1860,62 @@ class IamRequestResourceEnforcementIntegrationTest { } /** The user's JSON-protocol request to the target, {@code .}, with the body. */ + /** + * An {@code aws:ResourceTag} condition reads a Step Functions state machine's tags for the state machine, its + * version and its execution, and an activity's own, so an allow on one team's tag lets the caller read that + * team's and not another's. + */ + @Test + void aStepFunctionsResourceTagConditionReadsTheStateMachineTagsAndTheActivityTags() { + String definition = "{\\\"StartAt\\\":\\\"Done\\\",\\\"States\\\":{\\\"Done\\\":{\\\"Type\\\":\\\"Pass\\\"," + + "\\\"End\\\":true}}}"; + String tagged = stateMachine("res-tag-sm-" + suffix(), definition, "data"); + String other = stateMachine("res-tag-sm-" + suffix(), definition, "web"); + String version = sfn("PublishStateMachineVersion", "{\"stateMachineArn\":\"" + tagged + "\"}") + .statusCode(200).extract().path("stateMachineVersionArn"); + String execution = sfn("StartExecution", "{\"stateMachineArn\":\"" + tagged + "\"}") + .statusCode(200).extract().path("executionArn"); + String otherExecution = sfn("StartExecution", "{\"stateMachineArn\":\"" + other + "\"}") + .statusCode(200).extract().path("executionArn"); + String activity = activity("res-tag-act-" + suffix(), "data"); + String otherActivity = activity("res-tag-act-" + suffix(), "web"); + + User user = user("res-sfn-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":[\"states:DescribeStateMachine\",\"states:DescribeExecution\"," + + "\"states:DescribeActivity\"],\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + describe(user, "DescribeStateMachine", "stateMachineArn", tagged).statusCode(200); + describe(user, "DescribeStateMachine", "stateMachineArn", version).statusCode(200); + refusedJson(describe(user, "DescribeStateMachine", "stateMachineArn", other), "states:DescribeStateMachine"); + describe(user, "DescribeExecution", "executionArn", execution).statusCode(200); + refusedJson(describe(user, "DescribeExecution", "executionArn", otherExecution), "states:DescribeExecution"); + describe(user, "DescribeActivity", "activityArn", activity).statusCode(200); + refusedJson(describe(user, "DescribeActivity", "activityArn", otherActivity), "states:DescribeActivity"); + } + + private String stateMachine(String name, String definition, String team) { + String arn = sfn("CreateStateMachine", "{\"name\":\"" + name + "\",\"definition\":\"" + definition + + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/sfn\",\"tags\":[{\"key\":\"team\",\"value\":\"" + + team + "\"}]}").statusCode(200).extract().path("stateMachineArn"); + cleanup.register(() -> sfn("DeleteStateMachine", "{\"stateMachineArn\":\"" + arn + "\"}")); + return arn; + } + + private String activity(String name, String team) { + String arn = sfn("CreateActivity", "{\"name\":\"" + name + "\",\"tags\":[{\"key\":\"team\",\"value\":\"" + + team + "\"}]}").statusCode(200).extract().path("activityArn"); + cleanup.register(() -> sfn("DeleteActivity", "{\"activityArn\":\"" + arn + "\"}")); + return arn; + } + + private static ValidatableResponse sfn(String operation, String body) { + return adminJson("states", "AWSStepFunctions." + operation, "1.0").body(body).post("/").then(); + } + + private static ValidatableResponse describe(User user, String operation, String member, String arn) { + return send(user, "states", "AWSStepFunctions." + operation, "1.0", "{\"" + member + "\":\"" + arn + "\"}"); + } + /** * A Glue table is checked on the account's catalog, its database and itself, the types AWS gives * {@code glue:GetTable}, so a grant on all three allows it, the same grant refuses another table of the database, diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStoredTagsTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStoredTagsTest.java new file mode 100644 index 0000000000..6215a1fb7f --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsStoredTagsTest.java @@ -0,0 +1,90 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.stepfunctions.model.Activity; +import io.floci.aws.services.stepfunctions.model.Execution; +import io.floci.aws.services.stepfunctions.model.MapRun; +import io.floci.aws.services.stepfunctions.model.RoutingConfiguration; +import io.floci.aws.services.stepfunctions.model.StateMachine; +import io.floci.aws.services.stepfunctions.model.StateMachineAlias; +import io.floci.aws.services.stepfunctions.model.StateMachineVersion; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +class StepFunctionsStoredTagsTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String DEFINITION = "{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"End\":true}}}"; + private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/sfn"; + + private AccountAwareStorageBackend executionStore; + private StepFunctionsService service; + + @BeforeEach + void setUp() { + StorageFactory factory = mock(StorageFactory.class); + executionStore = AccountAwareStorageBackend.inMemory(ACCOUNT); + doReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)) + .doReturn(executionStore) + .doReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)) + .doReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)) + .doReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)) + .when(factory).create(anyString(), anyString(), any()); + service = new StepFunctionsService(factory, new RegionResolver(REGION, ACCOUNT), null, new ObjectMapper(), + mock(SfnMockLoader.class), mock(StepFunctionsEventPublisher.class), Clock.systemUTC()); + } + + @Test + void aStateMachinesVersionsAndExecutionsHaveItsTagsAndAnAliasNone() { + String arn = service.createStateMachine("orders", DEFINITION, ROLE, "STANDARD", REGION, + Map.of("team", "data")).getStateMachineArn(); + StateMachineVersion version = service.publishStateMachineVersion(arn, null, null); + service.createStateMachineAlias("live", null, + List.of(new RoutingConfiguration(version.getStateMachineVersionArn(), 100))); + Execution execution = new Execution(); + execution.setExecutionArn("arn:aws:states:" + REGION + ":" + ACCOUNT + ":execution:orders:run-1"); + execution.setStateMachineArn(arn); + executionStore.put(execution.getExecutionArn(), execution); + + assertEquals(Map.of("team", "data"), service.storedTags(arn)); + assertEquals(Map.of("team", "data"), service.storedTags(version.getStateMachineVersionArn())); + assertEquals(Map.of("team", "data"), service.storedTags(execution.getExecutionArn())); + assertEquals(Map.of(), service.storedTags(arn + ":live")); + assertEquals(Map.of(), service.storedTags(arn + ":7")); + assertEquals(Map.of(), service.storedTags(execution.getExecutionArn().replace("run-1", "run-2"))); + assertEquals(Map.of(), service.storedTags(arn.replace(ACCOUNT, "111111111111"))); + assertEquals(Map.of(), service.storedTags(arn.replace(REGION, "us-west-2"))); + + service.tagResource(arn, Map.of("stage", "prod")); + service.untagResource(arn, List.of("team")); + + assertEquals(Map.of("stage", "prod"), service.storedTags(version.getStateMachineVersionArn())); + } + + @Test + void anActivityHasItsOwnTagsAndTaggingPutsANewMapInPlaceOfTheHeldOne() { + String arn = service.createActivity("worker", REGION, Map.of("team", "data")).getActivityArn(); + Map held = service.listTags(arn); + + service.tagResource(arn, Map.of("stage", "prod")); + service.untagResource(arn, List.of("team")); + + assertEquals(Map.of("stage", "prod"), service.storedTags(arn)); + assertEquals(Map.of("team", "data"), held); + assertEquals(Map.of(), service.storedTags(arn.replace("worker", "other"))); + } +}