diff --git a/docs/services/iam.md b/docs/services/iam.md index c16f67cf0e..8fa04905eb 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3733,8 +3733,9 @@ floci populates: queues, SNS for its topics, Kinesis Data Streams for its streams and consumers, EventBridge Pipes for its pipes, Aurora DSQL for its clusters, EKS for its clusters, node groups, Fargate profiles, add-ons, Pod Identity associations and access entries, Resource Groups for its groups, CloudWatch Logs for its log groups, - destinations, delivery sources, delivery destinations and deliveries, and Pricing Calculator for its workload - estimates. Tag keys differing only in case are one condition key holding every value. + destinations, delivery sources, delivery destinations and deliveries, Pricing Calculator for its workload + estimates, and Amazon Managed Service for Prometheus for its workspaces and rule groups namespaces. 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 80d9deec9b..5c47f68c70 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -65,7 +65,8 @@ import java.util.Optional; * for the tags of a cluster; EKS, for the tags of a cluster, a node group, a Fargate profile, an add-on, a Pod Identity * association or an access entry; Resource Groups, for the tags of a group; CloudWatch Logs, for a delivery, the * delivery destinations of a delivery source and the tags of a log group, a destination, a delivery source, a - * delivery destination or a delivery; Pricing Calculator, for the tags of a workload estimate); looked up lazily by + * delivery destination or a delivery; Pricing Calculator, for the tags of a workload estimate; Amazon Managed Service + * for Prometheus, for the tags of a workspace or a rule groups namespace); 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/aps/ApsService.java b/src/main/java/io/floci/aws/services/aps/ApsService.java index cd539cca72..e619b8058f 100644 --- a/src/main/java/io/floci/aws/services/aps/ApsService.java +++ b/src/main/java/io/floci/aws/services/aps/ApsService.java @@ -7,7 +7,9 @@ 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.TagHandler; +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.aps.model.PrometheusWorkspace; @@ -17,14 +19,18 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.time.Instant; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; +import java.util.function.Consumer; import java.util.regex.Pattern; @ApplicationScoped -public class ApsService implements TagHandler { +public class ApsService implements TagHandler, StoredResourceArns { private static final Logger LOG = Logger.getLogger(ApsService.class); // AMP's ListWorkspacesRequest declares maxResults with a default of 100 and a maximum of 1000. @@ -33,6 +39,8 @@ public class ApsService implements TagHandler { private static final int MAX_NAMESPACE_NAME_LENGTH = 128; private static final Pattern NAMESPACE_NAME = Pattern.compile(".*[0-9A-Za-z][-.0-9A-Z_a-z]*.*"); private static final Pattern CLIENT_TOKEN = Pattern.compile("[!-~]{1,64}"); + private static final String WORKSPACE_PREFIX = "workspace/"; + private static final String NAMESPACE_PREFIX = "rulegroupsnamespace/"; private final StorageBackend storage; private final StorageBackend namespaceStorage; @@ -87,9 +95,7 @@ public class ApsService implements TagHandler { "https://" + AwsEndpoints.host("aps-workspaces", region) + "/workspaces/" + workspaceId + "/"); workspace.setCreatedAt(Instant.now()); workspace.setKmsKeyArn(kmsKeyArn); - if (tags != null) { - workspace.getTags().putAll(tags); - } + workspace.setTags(tags); PrometheusWorkspace response = clientToken != null ? copyWorkspace(workspace) : workspace; if (clientToken != null) { @@ -136,7 +142,7 @@ public class ApsService implements TagHandler { DEFAULT_PAGE, MAX_PAGE, "ValidationException"); } - public void deleteWorkspace(String region, String workspaceId) { + public synchronized void deleteWorkspace(String region, String workspaceId) { describeWorkspace(region, workspaceId); String namespacePrefix = namespaceKeyPrefix(region, workspaceId); for (RuleGroupsNamespace namespace : namespaceStorage.scan(k -> k.startsWith(namespacePrefix))) { @@ -146,14 +152,14 @@ public class ApsService implements TagHandler { LOG.infov("Deleted AMP workspace: {0} in {1}", workspaceId, region); } - public void updateWorkspaceAlias(String region, String workspaceId, String alias) { + public synchronized void updateWorkspaceAlias(String region, String workspaceId, String alias) { PrometheusWorkspace workspace = describeWorkspace(region, workspaceId); workspace.setAlias(stripAlias(alias)); storage.put(key(region, workspaceId), workspace); } - public RuleGroupsNamespace createRuleGroupsNamespace(String region, String workspaceId, String name, - String encodedData, Map tags) { + public synchronized RuleGroupsNamespace createRuleGroupsNamespace(String region, String workspaceId, String name, + String encodedData, Map tags) { describeWorkspace(region, workspaceId); requireNamespaceName(name); requireNamespaceData(encodedData); @@ -172,9 +178,7 @@ public class ApsService implements TagHandler { Instant now = Instant.now(); namespace.setCreatedAt(now); namespace.setModifiedAt(now); - if (tags != null) { - namespace.getTags().putAll(tags); - } + namespace.setTags(tags); namespaceStorage.put(namespaceKey(region, workspaceId, name), namespace); LOG.infov("Created AMP rule groups namespace: {0} in workspace {1}", name, workspaceId); @@ -201,8 +205,8 @@ public class ApsService implements TagHandler { DEFAULT_PAGE, MAX_PAGE, "ValidationException"); } - public RuleGroupsNamespace putRuleGroupsNamespace(String region, String workspaceId, String name, - String encodedData) { + public synchronized RuleGroupsNamespace putRuleGroupsNamespace(String region, String workspaceId, String name, + String encodedData) { requireNamespaceData(encodedData); RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, workspaceId, name); namespace.setEncodedData(encodedData); @@ -211,7 +215,7 @@ public class ApsService implements TagHandler { return namespace; } - public void deleteRuleGroupsNamespace(String region, String workspaceId, String name) { + public synchronized void deleteRuleGroupsNamespace(String region, String workspaceId, String name) { describeRuleGroupsNamespace(region, workspaceId, name); namespaceStorage.delete(namespaceKey(region, workspaceId, name)); LOG.infov("Deleted AMP rule groups namespace: {0} in workspace {1}", name, workspaceId); @@ -241,7 +245,7 @@ public class ApsService implements TagHandler { } @Override - public void tagResource(String region, String arn, Map tags) { + public synchronized void tagResource(String region, String arn, Map tags) { // Per AMP's TagResource: keys must not begin with the reserved "aws:" prefix // (case-insensitive, matching the sibling checks in FisService and BatchService). for (String tagKey : tags.keySet()) { @@ -251,18 +255,25 @@ public class ApsService implements TagHandler { } } Taggable taggable = taggableByArn(region, arn); - taggable.tags().putAll(tags); - taggable.persist().run(); + Map tagged = new HashMap<>(taggable.tags()); + tagged.putAll(tags); + taggable.store().accept(tagged); } @Override - public void untagResource(String region, String arn, List tagKeys) { + public synchronized void untagResource(String region, String arn, List tagKeys) { Taggable taggable = taggableByArn(region, arn); - tagKeys.forEach(taggable.tags()::remove); - taggable.persist().run(); + Map untagged = new HashMap<>(taggable.tags()); + tagKeys.forEach(untagged::remove); + taggable.store().accept(untagged); } - private record Taggable(Map tags, Runnable persist) { + /** + * A resource's tags and how to store a new set of them. A tag change stores a whole new map in the resource's + * volatile field, never changing a stored one, so a reader of the tags ({@link #storedTags}), which takes no lock, + * sees one whole set; it does so under the service's lock, so two changes cannot lose each other's tags. + */ + private record Taggable(Map tags, Consumer> store) { } private Taggable taggableByArn(String region, String arn) { @@ -277,27 +288,91 @@ public class ApsService implements TagHandler { throw new AwsException("ValidationException", "The resource ARN does not belong to this AMP account and region: " + arn, 400); } - String resource = parsed.resource(); - String workspacePrefix = "workspace/"; - if (resource.startsWith(workspacePrefix) && resource.length() > workspacePrefix.length()) { - PrometheusWorkspace workspace = - describeWorkspace(region, resource.substring(workspacePrefix.length())); - return new Taggable(workspace.getTags(), - () -> storage.put(key(region, workspace.getWorkspaceId()), workspace)); + List ids = resourceIds(parsed.resource()); + if (ids.size() == 1) { + PrometheusWorkspace workspace = describeWorkspace(region, ids.get(0)); + return new Taggable(workspace.getTags(), tags -> { + workspace.setTags(tags); + storage.put(key(region, workspace.getWorkspaceId()), workspace); + }); } - String namespacePrefix = "rulegroupsnamespace/"; - if (resource.startsWith(namespacePrefix)) { - String[] parts = resource.substring(namespacePrefix.length()).split("/", 2); - if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) { - RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, parts[0], parts[1]); - return new Taggable(namespace.getTags(), - () -> namespaceStorage.put(namespaceKey(region, parts[0], parts[1]), namespace)); - } + if (ids.size() == 2) { + RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, ids.get(0), ids.get(1)); + return new Taggable(namespace.getTags(), tags -> { + namespace.setTags(tags); + namespaceStorage.put(namespaceKey(region, ids.get(0), ids.get(1)), namespace); + }); } throw new AwsException("ValidationException", "Tags are only supported on AMP workspaces and rule groups namespaces: " + arn, 400); } + // ── StoredResourceArns: the tags IAM gives a resource-tag condition ── + + @Override + public String namespace() { + return "aps"; + } + + /** + * A request names a workspace by the id AMP minted and a namespace by its workspace and name, which the table + * fills into the ARN itself, so there is nothing to find by name. + */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + /** + * The tags of the workspace or the rule groups namespace whose ARN is {@code arn}, read in place under its key in + * the Region the ARN names, in the request's account, where the handlers read: an ARN of another account names + * none. A tag change stores a whole new map in a volatile field, so the read, which takes no lock, is of one + * whole set. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "aps")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + if (!parsed.accountId().equals(regionResolver.getAccountId())) { + return Map.of(); + } + List ids = resourceIds(parsed.resource()); + if (ids.size() == 1) { + return AccountAwareStorageBackend.readInAccount(storage, parsed.accountId(), + key(parsed.region(), ids.get(0))) + .filter(workspace -> arn.equals(workspace.getArn())) + .>map(workspace -> new LinkedHashMap<>(workspace.getTags())) + .orElse(Map.of()); + } + if (ids.size() != 2) { + return Map.of(); + } + return AccountAwareStorageBackend.readInAccount(namespaceStorage, parsed.accountId(), + namespaceKey(parsed.region(), ids.get(0), ids.get(1))) + .filter(namespace -> arn.equals(namespace.getArn())) + .>map(namespace -> new LinkedHashMap<>(namespace.getTags())) + .orElse(Map.of()); + } + + /** + * The ids an AMP ARN's resource names: a workspace's id, or a rule groups namespace's workspace id and name; none + * for anything else. Tag calls and IAM's tag lookup read an ARN alike. + */ + private static List resourceIds(String resource) { + if (resource.startsWith(WORKSPACE_PREFIX) && resource.length() > WORKSPACE_PREFIX.length()) { + return List.of(resource.substring(WORKSPACE_PREFIX.length())); + } + if (resource.startsWith(NAMESPACE_PREFIX)) { + String[] parts = resource.substring(NAMESPACE_PREFIX.length()).split("/", 2); + if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) { + return List.of(parts[0], parts[1]); + } + } + return List.of(); + } + // AMP is regional ("You can have one or more workspaces in each Region in your account"), so // the store is partitioned by request region, like CloudWatchLogsService's groupKey. private static String key(String region, String workspaceId) { diff --git a/src/main/java/io/floci/aws/services/aps/model/PrometheusWorkspace.java b/src/main/java/io/floci/aws/services/aps/model/PrometheusWorkspace.java index 3e7dd61646..686628d795 100644 --- a/src/main/java/io/floci/aws/services/aps/model/PrometheusWorkspace.java +++ b/src/main/java/io/floci/aws/services/aps/model/PrometheusWorkspace.java @@ -19,7 +19,7 @@ public class PrometheusWorkspace { private String prometheusEndpoint; private Instant createdAt; private String kmsKeyArn; - private Map tags = new ConcurrentHashMap<>(); + private volatile Map tags = new ConcurrentHashMap<>(); public PrometheusWorkspace() { } diff --git a/src/main/java/io/floci/aws/services/aps/model/RuleGroupsNamespace.java b/src/main/java/io/floci/aws/services/aps/model/RuleGroupsNamespace.java index 0361fb8215..55fe6fe73e 100644 --- a/src/main/java/io/floci/aws/services/aps/model/RuleGroupsNamespace.java +++ b/src/main/java/io/floci/aws/services/aps/model/RuleGroupsNamespace.java @@ -18,7 +18,7 @@ public class RuleGroupsNamespace { private String encodedData; private Instant createdAt; private Instant modifiedAt; - private Map tags = new ConcurrentHashMap<>(); + private volatile Map tags = new ConcurrentHashMap<>(); public RuleGroupsNamespace() { } diff --git a/src/test/java/io/floci/aws/services/aps/ApsIamIntegrationTest.java b/src/test/java/io/floci/aws/services/aps/ApsIamIntegrationTest.java index a666531069..15f0d01687 100644 --- a/src/test/java/io/floci/aws/services/aps/ApsIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/aps/ApsIamIntegrationTest.java @@ -1,14 +1,20 @@ package io.floci.aws.services.aps; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.model.AccessKey; +import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.SignedIamEnforcementProfile; import io.floci.aws.testing.SignedIamUsers; import io.floci.aws.testing.SignedRestRequests; +import io.floci.aws.testing.TestAccounts; import io.floci.aws.testutil.AwsRequestSigner; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.response.Response; +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.net.URI; import java.net.URLEncoder; @@ -32,6 +38,7 @@ import static org.hamcrest.Matchers.nullValue; @TestProfile(SignedIamEnforcementProfile.class) class ApsIamIntegrationTest { + private static final String TEAM_METRICS = "{\"tags\":{\"team\":\"metrics\"}}"; private static final String RULES = Base64.getEncoder() .encodeToString("groups: []\n".getBytes(StandardCharsets.UTF_8)); @@ -40,6 +47,12 @@ class ApsIamIntegrationTest { @TestHTTPResource("/") URI endpoint; + @Inject + IamService iam; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + @Test void aWorkspaceReadIsRefusedWithoutThePermissionAllowedWithItAndRefusedOnceItIsRemoved() throws Exception { String workspaceId = createWorkspace(); @@ -203,6 +216,80 @@ class ApsIamIntegrationTest { response.then().statusCode(400).body("message", equalTo("Invalid resource ARN: " + arn)); } + /** + * An {@code aws:ResourceTag} condition reads the tags AMP holds on the workspace a request names, as tag calls + * leave them: an allow on one team's tag reads that team's workspace, not an untagged one, no longer reads it once + * {@code UntagResource} has removed the tag, and reads the other once {@code TagResource} has added it. + */ + @Test + void aResourceTagConditionReadsTheTagsOfTheWorkspaceARequestNames() throws Exception { + String account = TestAccounts.randomId(); + AwsRequestSigner owner = user(account, "aps-owner", allow("\"aps:*\"", "*")); + AwsRequestSigner caller = user(account, "aps-tags", onTeamMetrics("aps:DescribeWorkspace")); + Workspace tagged = workspace(owner, TEAM_METRICS); + Workspace untagged = workspace(owner, "{}"); + + send(caller, "GET", "/workspaces/" + tagged.id(), null).then().statusCode(200) + .body("workspace.arn", equalTo(tagged.arn())); + denied(send(caller, "GET", "/workspaces/" + untagged.id(), null), "aps:DescribeWorkspace"); + send(owner, "DELETE", "/tags/" + encoded(tagged.arn()) + "?tagKeys=team", null).then().statusCode(200); + denied(send(caller, "GET", "/workspaces/" + tagged.id(), null), "aps:DescribeWorkspace"); + send(owner, "POST", "/tags/" + encoded(untagged.arn()), TEAM_METRICS).then().statusCode(200); + send(caller, "GET", "/workspaces/" + untagged.id(), null).then().statusCode(200) + .body("workspace.arn", equalTo(untagged.arn())); + } + + /** As for a workspace, for the rule groups namespace a request names by its workspace and name. */ + @Test + void aResourceTagConditionReadsTheTagsOfTheRuleGroupsNamespaceARequestNames() throws Exception { + String account = TestAccounts.randomId(); + AwsRequestSigner owner = user(account, "aps-owner", allow("\"aps:*\"", "*")); + AwsRequestSigner caller = user(account, "aps-tags", onTeamMetrics("aps:DescribeRuleGroupsNamespace")); + String namespaces = "/workspaces/" + workspace(owner, "{}").id() + "/rulegroupsnamespaces"; + String arn = send(owner, "POST", namespaces, tagged("metrics")).then().statusCode(202).extract().path("arn"); + send(owner, "POST", namespaces, namespace("untagged")).then().statusCode(202); + + send(caller, "GET", namespaces + "/tagged", null).then().statusCode(200) + .body("ruleGroupsNamespace.arn", equalTo(arn)); + denied(send(caller, "GET", namespaces + "/untagged", null), "aps:DescribeRuleGroupsNamespace"); + send(owner, "DELETE", "/tags/" + encoded(arn) + "?tagKeys=team", null).then().statusCode(200); + denied(send(caller, "GET", namespaces + "/tagged", null), "aps:DescribeRuleGroupsNamespace"); + String untagged = arn.replace("/tagged", "/untagged"); + send(owner, "POST", "/tags/" + encoded(untagged), TEAM_METRICS).then().statusCode(200); + send(caller, "GET", namespaces + "/untagged", null).then().statusCode(200) + .body("ruleGroupsNamespace.arn", equalTo(untagged)); + } + + /** A user of {@code account} with the inline policy {@code policy}, removed after the test, signing for AMP. */ + private AwsRequestSigner user(String account, String name, String policy) { + AccessKey key = SignedIamUsers.createUser(iam, cleanup, account, name, "access", policy); + return AwsRequestSigner.signedAs(key.getAccessKeyId(), key.getSecretAccessKey(), "aps"); + } + + private record Workspace(String id, String arn) { + } + + /** A workspace {@code owner} creates with {@code body}, deleted after the test. */ + private Workspace workspace(AwsRequestSigner owner, String body) throws Exception { + Response created = send(owner, "POST", "/workspaces", body); + created.then().statusCode(202); + Workspace workspace = new Workspace(created.path("workspaceId"), created.path("arn")); + cleanup.register(() -> { + try { + send(owner, "DELETE", "/workspaces/" + workspace.id(), null).then().statusCode(202); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + return workspace; + } + + /** An allow of {@code action} on any resource tagged {@code team} {@code metrics}. */ + private static String onTeamMetrics(String action) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + action + + "\",\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"metrics\"}}}]}"; + } + private static String encoded(String arn) { return URLEncoder.encode(arn, StandardCharsets.UTF_8); } diff --git a/src/test/java/io/floci/aws/services/aps/ApsServiceTest.java b/src/test/java/io/floci/aws/services/aps/ApsServiceTest.java index 25ee77bf27..552f87260b 100644 --- a/src/test/java/io/floci/aws/services/aps/ApsServiceTest.java +++ b/src/test/java/io/floci/aws/services/aps/ApsServiceTest.java @@ -391,4 +391,27 @@ class ApsServiceTest { service.untagResource(US_EAST_1, arn, List.of("env")); assertEquals(Map.of("team", "devops"), service.listTags(US_EAST_1, arn)); } + + /** + * IAM's tag lookup reads the tags of the workspace or the rule groups namespace whose ARN it is given, as tag calls + * leave them; nothing for an ARN of another account or Region, of no such resource, or of another service. + */ + @Test + void storedTagsAreTheTagsOfTheWorkspaceOrTheNamespaceTheArnNames() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, "tagged", Map.of("env", "test"), null); + String namespace = service.createRuleGroupsNamespace(US_EAST_1, workspace.getWorkspaceId(), "alerts", RULES, + Map.of("env", "test")).getArn(); + for (String arn : List.of(workspace.getArn(), namespace)) { + service.tagResource(US_EAST_1, arn, Map.of("team", "metrics")); + service.untagResource(US_EAST_1, arn, List.of("env")); + + assertEquals("aps", service.namespace()); + assertEquals(Map.of("team", "metrics"), service.storedTags(arn)); + assertEquals(Map.of(), service.storedTags(arn.replace(":000000000000:", ":111122223333:"))); + assertEquals(Map.of(), service.storedTags(arn.replace(":" + US_EAST_1 + ":", ":" + EU_WEST_1 + ":"))); + assertEquals(Map.of(), service.storedTags(arn + "0")); + assertEquals(Map.of(), service.storedTags(arn.replace(":aps:", ":ecs:"))); + } + assertEquals(Map.of(), service.storedTags("arn:aws:aps:us-east-1:000000000000:scraper/s-1")); + } } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsCallbackIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsCallbackIamIntegrationTest.java index b0b1131206..2ec5021c7a 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsCallbackIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsCallbackIamIntegrationTest.java @@ -1,7 +1,6 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.ObjectMapper; -import io.floci.aws.core.common.RequestScopes; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.model.AccessKey; import io.floci.aws.services.sqs.SqsService; @@ -241,14 +240,7 @@ class StepFunctionsCallbackIamIntegrationTest { } private AccessKey foreignUser(String name, String policy) { - String account = "111111111111"; - RequestScopes.runAs(account, () -> iam.createUser(name, "/")); - cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteUser(name))); - RequestScopes.runAs(account, () -> iam.putUserPolicy(name, "callback", policy)); - cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteUserPolicy(name, "callback"))); - AccessKey key = RequestScopes.callAs(account, () -> iam.createAccessKey(name)); - cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteAccessKey(name, key.getAccessKeyId()))); - return key; + return SignedIamUsers.createUser(iam, cleanup, "111111111111", name, "callback", policy); } private SfnClient client(String access, String secret) { diff --git a/src/test/java/io/floci/aws/testing/SignedIamUsers.java b/src/test/java/io/floci/aws/testing/SignedIamUsers.java index e217af93e5..ec8f1b49ec 100644 --- a/src/test/java/io/floci/aws/testing/SignedIamUsers.java +++ b/src/test/java/io/floci/aws/testing/SignedIamUsers.java @@ -1,5 +1,8 @@ package io.floci.aws.testing; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.model.AccessKey; import io.floci.aws.testutil.AwsRequestSigner; import io.restassured.response.Response; @@ -19,7 +22,8 @@ import static io.restassured.RestAssured.given; * *

{@link #createUser} makes an IAM user with an access key and an optional inline policy; closing the * returned {@link User} deletes the key, the policy and the user, so a test can hold it in a - * try-with-resources block. + * try-with-resources block. {@link #createUser(IamService, PartitionCleanup, String, String, String, String)} makes + * one in an account of the test's own, which the root {@code test} key, signing for the default account, cannot. */ public final class SignedIamUsers { @@ -78,7 +82,26 @@ public final class SignedIamUsers { } } - /** An IAM user made by {@link #createUser}; {@link #close} removes it with its key and policy. */ + /** + * Creates the user {@code name} of {@code account} through {@code iam}, with one access key and the inline policy + * {@code policyName} holding {@code policyDocument}; {@code cleanup} removes the key, the policy and the user + * after the test. + */ + public static AccessKey createUser(IamService iam, PartitionCleanup cleanup, String account, String name, + String policyName, String policyDocument) { + RequestScopes.runAs(account, () -> iam.createUser(name, "/")); + cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteUser(name))); + RequestScopes.runAs(account, () -> iam.putUserPolicy(name, policyName, policyDocument)); + cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteUserPolicy(name, policyName))); + AccessKey key = RequestScopes.callAs(account, () -> iam.createAccessKey(name)); + cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteAccessKey(name, key.getAccessKeyId()))); + return key; + } + + /** + * An IAM user made by {@link #createUser(URI, String, String, String)}; {@link #close} removes it with its key + * and policy. + */ public record User(URI endpoint, String name, String policyName, String accessKeyId, String secretAccessKey) implements AutoCloseable {