From bd6c5810c3d579e00814134aa5e71823cb286f9e Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:21:18 -0400 Subject: [PATCH] feat(emr): keep EMR Studios and their session mappings (#8701) EMR's Studio operations, CreateStudio, DescribeStudio, ListStudios, UpdateStudio and DeleteStudio, and its Studio session mappings, Create, Get, List, Update and DeleteStudioSessionMapping, were not served. Floci now keeps Studios, checked against its own EC2 and IAM Identity Center: a Studio's VPC, at most 5 subnets and its two security groups must exist, the subnets and groups in the VPC; an SSO Studio needs a UserRole and an IAM one may not have one, and the IdP members are for IAM Studios only; an SSO Studio needs the account's IAM Identity Center instance, or the one it names. UpdateStudio keeps every earlier subnet. A session mapping is for an SSO Studio, names its user or group by id or by name but not both, and that identity must be in the instance's identity store, and is found again by the id or name it was made with. Studios and mappings list in the order they were made, by a sequence no deletion frees. AddTags and RemoveTags take a Studio's id, and IAM's resource-tag conditions read a Studio's tags. Floci serves no Studio: its URL is on Floci's own address. Identity Store gains typed lookups of a user by name and a group by id or display name, and EMR's random id helper is shared. --- docs/services/emr.md | 45 +- docs/services/index.md | 2 +- .../io/floci/aws/services/emr/EmrHandler.java | 201 ++++++- .../io/floci/aws/services/emr/EmrService.java | 38 +- .../aws/services/emr/EmrStudioService.java | 521 ++++++++++++++++++ .../aws/services/emr/model/EmrStudio.java | 103 ++++ .../emr/model/EmrStudioSessionMapping.java | 36 ++ .../identitystore/IdentityStoreService.java | 24 + .../emr/EmrServiceContainerStepsTest.java | 6 +- .../emr/EmrStudioIntegrationTest.java | 282 ++++++++++ .../services/emr/EmrStudioServiceTest.java | 80 +++ .../stepfunctions/AslExecutorEmrSyncTest.java | 4 +- 12 files changed, 1323 insertions(+), 19 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/emr/EmrStudioService.java create mode 100644 src/main/java/io/floci/aws/services/emr/model/EmrStudio.java create mode 100644 src/main/java/io/floci/aws/services/emr/model/EmrStudioSessionMapping.java create mode 100644 src/test/java/io/floci/aws/services/emr/EmrStudioIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/emr/EmrStudioServiceTest.java diff --git a/docs/services/emr.md b/docs/services/emr.md index 6d45b05cfe..22fb954f67 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -4,7 +4,7 @@ **Endpoint:** `http://localhost:4566/` **Target prefix:** `X-Amz-Target: ElasticMapReduce.*` -Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job flows), instance groups and fleets, steps, Spark Connect sessions, security configurations, and tags are tracked in Floci's storage backend so the AWS CLI and SDK clients can drive the full cluster lifecycle locally. EMR does not launch real Hadoop/Spark clusters. Clusters transition through their lifecycle states as a state machine. In the `docker` runner mode Spark steps, commands and scripts run for real, each in a container of its own, after the cluster's bootstrap actions (see [Running steps](#running-steps)). +Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job flows), instance groups and fleets, steps, Spark Connect sessions, EMR Studios and their session mappings, security configurations, and tags are tracked in Floci's storage backend so the AWS CLI and SDK clients can drive the full cluster lifecycle locally. EMR does not launch real Hadoop/Spark clusters. Clusters transition through their lifecycle states as a state machine. In the `docker` runner mode Spark steps, commands and scripts run for real, each in a container of its own, after the cluster's bootstrap actions (see [Running steps](#running-steps)). ## Supported Actions @@ -29,6 +29,16 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job | `ListSessions` | Lists a cluster's sessions, newest first, filterable by state | | `TerminateSession` | Terminates a session that has not ended | | `GetSessionEndpoint` | Returns a session's endpoint and an authentication token valid for an hour | +| `CreateStudio` | Creates an EMR Studio in a VPC of Floci's EC2; see [Studios](#studios) | +| `DescribeStudio` | Returns a Studio's configuration | +| `ListStudios` | Lists the Region's Studios | +| `UpdateStudio` | Changes a Studio's name, description, subnets, default S3 location or encryption key | +| `DeleteStudio` | Deletes a Studio and its session mappings | +| `CreateStudioSessionMapping` | Maps an IAM Identity Center user or group to a Studio, with a session policy | +| `GetStudioSessionMapping` | Returns a user's or group's session mapping | +| `ListStudioSessionMappings` | Lists the session mappings of a Studio, or of every Studio | +| `UpdateStudioSessionMapping` | Changes a mapped user's or group's session policy | +| `DeleteStudioSessionMapping` | Removes a user or group from a Studio | | `AddInstanceGroups` | Adds instance groups to a running cluster | | `ListInstanceGroups` | Lists the instance groups of a cluster | | `AddInstanceFleet` | Adds an instance fleet to a cluster | @@ -223,6 +233,39 @@ starts no Spark Connect server for it, in either runner mode, so nothing answers * A session's `EngineConfigurations`, `MonitoringConfiguration` and `Tags` are kept as given and reported by `GetSession`; none of them configures anything, and no session logs are written. +## Studios + +An EMR Studio is kept with the network and identities it names, each checked against Floci's own EC2 and IAM Identity +Center, but Floci serves no Studio: its `Url` is on Floci's own address (`/_aws/emr/studios/`), where +nothing answers. + +* **CreateStudio** refuses a request without one of the model's required members, or with an `AuthMode` or + `IdcUserAssignment` it does not name, with `ValidationException`, and a member of the wrong JSON type with + `SerializationException`. Then, each with `InvalidRequestException` in Floci's own wording, as AWS's is not recorded: + more than 5 subnets ("A Studio can have a maximum of 5 subnets"), none, a VPC, subnet or security group Floci's EC2 + does not have, a subnet or security group outside the VPC ("The subnets must belong to the VPC specified by VpcId", + each security group "must be in the same VPC"), an `SSO` Studio without a `UserRole` ("When you use IAM Identity + Center authentication, you must specify a --user-role"), an `IAM` one with one ("Only specify a UserRole when you + use IAM Identity Center authentication"), an `SSO` one with `IdpAuthUrl` or `IdpRelayStateParameterName`, which are + for "when you use IAM authentication", and an `SSO` one when the account has no IAM Identity Center instance, or + not the one `IdcInstanceArn` names. An `SSO` Studio's `TrustedIdentityPropagationEnabled` is `false` unless given, + as "The default value is false". The Studio's id is `es-` and 25 letters and digits. A subnet named twice is kept + once. +* **Tags**: `AddTags` and `RemoveTags` take a Studio's id as their `ResourceId`, which is "a cluster identifier or an + Amazon EMR Studio ID", and IAM's `aws:ResourceTag` conditions read a Studio's tags. +* **UpdateStudio** changes what it is given. Its `SubnetIds` "can include new subnet IDs, but must also include all of + the subnet IDs previously associated with the Studio", at most 5, in the Studio's VPC; anything else is refused. +* **DeleteStudio** removes the Studio and its session mappings. **ListStudios** lists the Region's Studios in the order + they were made, 50 to a page, after a `Marker`; no source gives AWS's order or page size. +* **Session mappings** are for an `SSO` Studio, as "Use CreateStudioSessionMapping to assign users to a Studio when you + use IAM Identity Center authentication"; one on an `IAM` Studio is refused. A call names its user or group by + "Either IdentityName or IdentityId ... but not both", and the identity must be in the identity store of the + Studio's IAM Identity Center instance, a user by its `UserName` and a group by its `DisplayName`; a mapping reports + both. A user or group mapped twice, or not mapped, is refused, each with `InvalidRequestException` in Floci's own + wording. Getting, updating and removing a mapping finds it by the id or the name it was made with, so one whose + user or group has since been deleted can still be removed. The `SessionPolicyArn` is kept as given. `ListStudioSessionMappings` lists a Studio's mappings, or every + Studio's when it names none, filtered by `IdentityType`, in the order they were made, 50 to a page. + ## Running steps With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMR_RUNNER_MODE=docker`), a step runs. Floci starts diff --git a/docs/services/index.md b/docs/services/index.md index 93fdc086cd..2ef5846096 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -84,7 +84,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 65 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 58 | -| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 45 | +| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 55 | | [EMR on EKS](emr-containers.md) | `/virtualclusters/*`, `/jobtemplates/*`, `/securityconfigurations/*`, `/tags/*` | REST JSON | 25 | | [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 | | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java index ffd2574184..77d421f2ad 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -21,6 +21,8 @@ import io.floci.aws.services.emr.model.EmrInstanceFleet; import io.floci.aws.services.emr.model.EmrInstanceGroup; import io.floci.aws.services.emr.model.EmrSession; import io.floci.aws.services.emr.model.EmrStep; +import io.floci.aws.services.emr.model.EmrStudio; +import io.floci.aws.services.emr.model.EmrStudioSessionMapping; import io.floci.aws.services.emr.model.SecurityConfiguration; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -50,11 +52,13 @@ public class EmrHandler { static final int INSTANCES_PER_PAGE = 2000; private final EmrService service; + private final EmrStudioService studios; private final ObjectMapper objectMapper; @Inject - public EmrHandler(EmrService service, ObjectMapper objectMapper) { + public EmrHandler(EmrService service, EmrStudioService studios, ObjectMapper objectMapper) { this.service = service; + this.studios = studios; this.objectMapper = objectMapper; } @@ -80,6 +84,16 @@ public class EmrHandler { case "ListSessions" -> handleListSessions(request); case "TerminateSession" -> handleTerminateSession(request); case "GetSessionEndpoint" -> handleGetSessionEndpoint(request); + case "CreateStudio" -> handleCreateStudio(request); + case "DescribeStudio" -> handleDescribeStudio(request); + case "ListStudios" -> handleListStudios(request); + case "UpdateStudio" -> handleUpdateStudio(request); + case "DeleteStudio" -> handleDeleteStudio(request); + case "CreateStudioSessionMapping" -> handleCreateStudioSessionMapping(request); + case "GetStudioSessionMapping" -> handleGetStudioSessionMapping(request); + case "ListStudioSessionMappings" -> handleListStudioSessionMappings(request); + case "UpdateStudioSessionMapping" -> handleUpdateStudioSessionMapping(request); + case "DeleteStudioSessionMapping" -> handleDeleteStudioSessionMapping(request); case "AddInstanceGroups" -> handleAddInstanceGroups(request); case "ListInstanceGroups" -> handleListInstanceGroups(request); case "AddInstanceFleet" -> handleAddInstanceFleet(request); @@ -529,6 +543,176 @@ public class EmrHandler { return new AwsException("SerializationException", message, 400); } + // ──────────────────────────── Studios ──────────────────────────── + + private Response handleCreateStudio(JsonNode request) { + EmrStudio studio = new EmrStudio(); + studio.setName(string(request, "Name")); + studio.setDescription(string(request, "Description")); + studio.setAuthMode(string(request, "AuthMode")); + studio.setVpcId(string(request, "VpcId")); + studio.setSubnetIds(strings(request.path("SubnetIds"), "SubnetIds")); + studio.setServiceRole(string(request, "ServiceRole")); + studio.setUserRole(string(request, "UserRole")); + studio.setWorkspaceSecurityGroupId(string(request, "WorkspaceSecurityGroupId")); + studio.setEngineSecurityGroupId(string(request, "EngineSecurityGroupId")); + studio.setDefaultS3Location(string(request, "DefaultS3Location")); + studio.setIdpAuthUrl(string(request, "IdpAuthUrl")); + studio.setIdpRelayStateParameterName(string(request, "IdpRelayStateParameterName")); + studio.setTags(tagList(request.path("Tags"), "Tags")); + studio.setTrustedIdentityPropagationEnabled(bool(request, "TrustedIdentityPropagationEnabled")); + studio.setIdcUserAssignment(string(request, "IdcUserAssignment")); + studio.setIdcInstanceArn(string(request, "IdcInstanceArn")); + studio.setEncryptionKeyArn(string(request, "EncryptionKeyArn")); + EmrStudio created = studios.createStudio(studio); + ObjectNode response = objectMapper.createObjectNode(); + response.put("StudioId", created.getStudioId()); + response.put("Url", created.getUrl()); + return Response.ok(response).build(); + } + + private Response handleDescribeStudio(JsonNode request) { + ObjectNode response = objectMapper.createObjectNode(); + response.set("Studio", studioNode(studios.describeStudio(string(request, "StudioId")))); + return Response.ok(response).build(); + } + + private Response handleListStudios(JsonNode request) { + PaginatedResult page = studios.listStudios(string(request, "Marker")); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode summaries = response.putArray("Studios"); + for (EmrStudio studio : page.items()) { + ObjectNode summary = summaries.addObject(); + summary.put("StudioId", studio.getStudioId()); + summary.put("Name", studio.getName()); + summary.put("VpcId", studio.getVpcId()); + if (studio.getDescription() != null) { + summary.put("Description", studio.getDescription()); + } + summary.put("Url", studio.getUrl()); + summary.put("AuthMode", studio.getAuthMode()); + putEpoch(summary, "CreationTime", studio.getCreationTime()); + } + if (page.nextToken() != null) { + response.put("Marker", page.nextToken()); + } + return Response.ok(response).build(); + } + + private Response handleUpdateStudio(JsonNode request) { + studios.updateStudio(string(request, "StudioId"), string(request, "Name"), string(request, "Description"), + strings(request.path("SubnetIds"), "SubnetIds"), string(request, "DefaultS3Location"), + string(request, "EncryptionKeyArn")); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleDeleteStudio(JsonNode request) { + studios.deleteStudio(string(request, "StudioId")); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleCreateStudioSessionMapping(JsonNode request) { + studios.createSessionMapping(string(request, "StudioId"), identity(request), + string(request, "SessionPolicyArn")); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleGetStudioSessionMapping(JsonNode request) { + String studioId = string(request, "StudioId"); + EmrStudioSessionMapping mapping = studios.getSessionMapping(studioId, identity(request)); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode detail = sessionMappingNode(studioId, mapping); + putEpoch(detail, "LastModifiedTime", mapping.getLastModifiedTime()); + response.set("SessionMapping", detail); + return Response.ok(response).build(); + } + + private Response handleListStudioSessionMappings(JsonNode request) { + PaginatedResult page = studios.listSessionMappings( + string(request, "StudioId"), string(request, "IdentityType"), string(request, "Marker")); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode mappings = response.putArray("SessionMappings"); + page.items().forEach(item -> mappings.add(sessionMappingNode(item.studioId(), item.mapping()))); + if (page.nextToken() != null) { + response.put("Marker", page.nextToken()); + } + return Response.ok(response).build(); + } + + private Response handleUpdateStudioSessionMapping(JsonNode request) { + studios.updateSessionMapping(string(request, "StudioId"), identity(request), + string(request, "SessionPolicyArn")); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleDeleteStudioSessionMapping(JsonNode request) { + studios.deleteSessionMapping(string(request, "StudioId"), identity(request)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private static EmrStudioService.Identity identity(JsonNode request) { + return new EmrStudioService.Identity(string(request, "IdentityType"), string(request, "IdentityId"), + string(request, "IdentityName")); + } + + private ObjectNode studioNode(EmrStudio studio) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("StudioId", studio.getStudioId()); + node.put("StudioArn", studio.getStudioArn()); + node.put("Name", studio.getName()); + putIfSet(node, "Description", studio.getDescription()); + node.put("AuthMode", studio.getAuthMode()); + node.put("VpcId", studio.getVpcId()); + ArrayNode subnets = node.putArray("SubnetIds"); + studio.getSubnetIds().forEach(subnets::add); + node.put("ServiceRole", studio.getServiceRole()); + putIfSet(node, "UserRole", studio.getUserRole()); + node.put("WorkspaceSecurityGroupId", studio.getWorkspaceSecurityGroupId()); + node.put("EngineSecurityGroupId", studio.getEngineSecurityGroupId()); + node.put("Url", studio.getUrl()); + putEpoch(node, "CreationTime", studio.getCreationTime()); + node.put("DefaultS3Location", studio.getDefaultS3Location()); + putIfSet(node, "IdpAuthUrl", studio.getIdpAuthUrl()); + putIfSet(node, "IdpRelayStateParameterName", studio.getIdpRelayStateParameterName()); + node.set("Tags", tagArray(studio.getTags())); + putIfSet(node, "IdcInstanceArn", studio.getIdcInstanceArn()); + if (studio.getTrustedIdentityPropagationEnabled() != null) { + node.put("TrustedIdentityPropagationEnabled", studio.getTrustedIdentityPropagationEnabled()); + } + putIfSet(node, "IdcUserAssignment", studio.getIdcUserAssignment()); + putIfSet(node, "EncryptionKeyArn", studio.getEncryptionKeyArn()); + return node; + } + + // A SessionMappingSummary; GetStudioSessionMapping's detail adds its LastModifiedTime. + private ObjectNode sessionMappingNode(String studioId, EmrStudioSessionMapping mapping) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("StudioId", studioId); + node.put("IdentityId", mapping.getIdentityId()); + putIfSet(node, "IdentityName", mapping.getIdentityName()); + node.put("IdentityType", mapping.getIdentityType()); + node.put("SessionPolicyArn", mapping.getSessionPolicyArn()); + putEpoch(node, "CreationTime", mapping.getCreationTime()); + return node; + } + + private static void putIfSet(ObjectNode node, String field, String value) { + if (value != null) { + node.put(field, value); + } + } + + private static Boolean bool(JsonNode request, String member) { + JsonNode value = request.path(member); + if (value.isMissingNode() || value.isNull()) { + return null; + } + if (!value.isBoolean()) { + throw malformed(member + " must be a boolean"); + } + return value.asBoolean(); + } + // ──────────────────────────── Instance groups / fleets ──────────────────────────── private Response handleAddInstanceGroups(JsonNode request) { @@ -838,13 +1022,24 @@ public class EmrHandler { // ──────────────────────────── Tags ──────────────────────────── + // A tag call's ResourceId is "a cluster identifier or an Amazon EMR Studio ID". private Response handleAddTags(JsonNode request) { - service.addTags(text(request, "ResourceId"), parseTags(request.path("Tags"))); + String resourceId = text(request, "ResourceId"); + if (EmrStudioService.isStudioId(resourceId)) { + studios.addTags(resourceId, parseTags(request.path("Tags"))); + return Response.ok(objectMapper.createObjectNode()).build(); + } + service.addTags(resourceId, parseTags(request.path("Tags"))); return Response.ok(objectMapper.createObjectNode()).build(); } private Response handleRemoveTags(JsonNode request) { - service.removeTags(text(request, "ResourceId"), stringList(request.path("TagKeys"))); + String resourceId = text(request, "ResourceId"); + if (EmrStudioService.isStudioId(resourceId)) { + studios.removeTags(resourceId, stringList(request.path("TagKeys"))); + return Response.ok(objectMapper.createObjectNode()).build(); + } + service.removeTags(resourceId, stringList(request.path("TagKeys"))); return Response.ok(objectMapper.createObjectNode()).build(); } diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index 8ff49aa46b..7189f613bd 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -45,6 +45,7 @@ import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; +import jakarta.inject.Provider; import org.jboss.logging.Logger; import java.security.SecureRandom; @@ -107,7 +108,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // gives it to AddInstanceGroups and AddInstanceFleet too, for one shutting down. private static final String JOB_FLOW_SHUT_DOWN = "A job flow that is shutting down, terminated, or finished may not be modified."; - private static final ObjectMapper SNAPSHOT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule()); + // Copies a stored resource for a call to answer from; the Studios' service copies its own with it too. + static final ObjectMapper SNAPSHOT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule()); private static final String RUNNER_DOCKER = "docker"; // The service a step's driver belongs to, which names it and labels it. private static final String SERVICE = "emr"; @@ -265,6 +267,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } } + // The Studios, whose ARNs and tags this service answers for too, as IAM asks one service per namespace; looked up + // as they are needed, and absent in a test that builds this service itself. + @Inject + Provider studios; + @Inject public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner, @@ -929,11 +936,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return switch (member) { case "InstanceGroups[].InstanceGroupId" -> call(() -> clusterWithGroup(region, value).map(EmrCluster::getClusterArn).stream().toList()); - // A tag call's ResourceId is a cluster's id, or a Studio's, which Floci does not serve: the cluster the - // tag handlers find by it (findCluster), one recorded with no Region included. - case "ResourceId" -> call(() -> clusterStore.get(value) - .filter(cluster -> cluster.getRegion() == null || cluster.getRegion().equals(region)) - .map(EmrCluster::getClusterArn).stream().toList()); + // A tag call's ResourceId is a cluster's id, or a Studio's: the Studio, or the cluster the tag handlers + // find by it (findCluster), one recorded with no Region included. + case "ResourceId" -> EmrStudioService.isStudioId(value) + ? studioService().map(service -> service.studioArn(value, region)).stream() + .flatMap(Optional::stream).toList() + : call(() -> clusterStore.get(value) + .filter(cluster -> cluster.getRegion() == null || cluster.getRegion().equals(region)) + .map(EmrCluster::getClusterArn).stream().toList()); default -> List.of(); }; } @@ -1213,9 +1223,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * The tags held on the cluster stored under {@code arn}, in the account it names, read in place: the cluster of - * that id in the ARN's Region, or one recorded with no Region, as the tag handlers find it; empty for an ARN - * naming nothing stored or naming anything but a cluster. + * The tags held on the cluster or Studio stored under {@code arn}, in the account it names, read in place: the + * cluster of that id in the ARN's Region, or one recorded with no Region, as the tag handlers find it, or the + * Studio of that id in the ARN's Region; empty for an ARN naming nothing stored or naming anything else. */ @Override public Map storedTags(String arn) { @@ -1224,6 +1234,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); String resource = parsed.resource(); + if (resource.startsWith(EmrStudioService.STUDIO_RESOURCE)) { + return studioService().map(service -> service.storedTags(arn)).orElse(Map.of()); + } if (!resource.startsWith(CLUSTER_RESOURCE) || resource.indexOf('/', CLUSTER_RESOURCE.length()) >= 0 || !arn.equals(AwsArnUtils.Arn.of("elasticmapreduce", parsed.region(), parsed.accountId(), resource) .toString())) { @@ -1242,6 +1255,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return held; } + private Optional studioService() { + return studios != null ? Optional.of(studios.get()) : Optional.empty(); + } + // ──────────────────────────── Helpers ──────────────────────────── // ──────────────────────────── Scaling and termination policies ──────────────────────────── @@ -3032,7 +3049,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return clock.instant().truncatedTo(ChronoUnit.MILLIS); } - private String randomId(int length) { + /** {@code length} random upper-case letters and digits, as EMR's resource ids carry after their prefix. */ + static String randomId(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append(UPPER_ALNUM.charAt(RANDOM.nextInt(UPPER_ALNUM.length()))); diff --git a/src/main/java/io/floci/aws/services/emr/EmrStudioService.java b/src/main/java/io/floci/aws/services/emr/EmrStudioService.java new file mode 100644 index 0000000000..34d28bac8c --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/EmrStudioService.java @@ -0,0 +1,521 @@ +package io.floci.aws.services.emr; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsArnUtils; +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.SmithyValidationErrors; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.SecurityGroup; +import io.floci.aws.services.ec2.model.Subnet; +import io.floci.aws.services.emr.model.EmrStudio; +import io.floci.aws.services.emr.model.EmrStudioSessionMapping; +import io.floci.aws.services.identitystore.IdentityStoreService; +import io.floci.aws.services.ssoadmin.SsoAdminService; +import io.floci.aws.services.ssoadmin.model.SsoInstance; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * EMR Studios and their session mappings (Amazon EMR Management Guide, "EMR Studio"). A Studio is kept with the VPC, + * subnets and security groups it names, each of which must be in Floci's EC2, and a Studio that authenticates with IAM + * Identity Center maps that instance's users and groups to it, each found in its identity store. Floci serves no + * Studio: its URL is on Floci's own address, where nothing answers. + */ +@ApplicationScoped +public class EmrStudioService { + + static final String AUTH_SSO = "SSO"; + static final String AUTH_IAM = "IAM"; + static final List AUTH_MODES = List.of(AUTH_SSO, AUTH_IAM); + static final List IDENTITY_TYPES = List.of("USER", "GROUP"); + static final List USER_ASSIGNMENTS = List.of("REQUIRED", "OPTIONAL"); + // "A Studio can have a maximum of 5 subnets." + static final int MAX_SUBNETS = 5; + // A Studio's ARN's resource, before its id. + static final String STUDIO_RESOURCE = "studio/"; + // Where a Studio's URL points; nothing answers there, as Floci serves no Studio. + static final String URL_PATH = "/_aws/emr/studios/"; + // A page of ListStudios or ListStudioSessionMappings: no source gives AWS's size; EMR's other Marker lists give 50. + static final int PAGE_SIZE = 50; + private static final int MAX_NAME_LENGTH = 256; + private static final int ID_LENGTH = 25; + + private final AccountAwareStorageBackend store; + private final RegionResolver regionResolver; + private final Ec2Service ec2; + private final SsoAdminService ssoAdmin; + private final IdentityStoreService identityStore; + private final Clock clock; + private final String baseUrl; + // The last sequence issued, so that none is issued twice in this process. + private long lastSequence; + + @Inject + public EmrStudioService(StorageFactory storageFactory, RegionResolver regionResolver, Ec2Service ec2, + SsoAdminService ssoAdmin, IdentityStoreService identityStore, EmulatorConfig config) { + this(storageFactory.create("emr", "emr-studios.json", new TypeReference>() {}), + regionResolver, ec2, ssoAdmin, identityStore, Clock.systemUTC(), config.effectiveBaseUrl()); + } + + EmrStudioService(AccountAwareStorageBackend store, RegionResolver regionResolver, Ec2Service ec2, + SsoAdminService ssoAdmin, IdentityStoreService identityStore, Clock clock, String baseUrl) { + this.store = store; + this.regionResolver = regionResolver; + this.ec2 = ec2; + this.ssoAdmin = ssoAdmin; + this.identityStore = identityStore; + this.clock = clock; + String base = baseUrl == null ? "" : baseUrl; + this.baseUrl = base.endsWith("/") ? base.substring(0, base.length() - 1) : base; + } + + /** + * Creates a Studio. The model's required members and enums are checked first, with the ValidationException AWS's + * validation layer answers. Then the API reference's and the guide's rules, each refused with + * InvalidRequestException, the one error the model declares, in Floci's own wording: "A Studio can have a maximum + * of 5 subnets"; "The subnets must belong to the VPC specified by VpcId", and each security group "must be in the + * same VPC"; "When you use IAM Identity Center authentication, you must specify a --user-role", and "Only specify + * a UserRole when you use IAM Identity Center authentication"; the IdP members, for "when you use IAM + * authentication", only with it. + */ + public synchronized EmrStudio createStudio(EmrStudio requested) { + List violations = new ArrayList<>(); + requireMember(violations, "name", requested.getName()); + requireMember(violations, "authMode", requested.getAuthMode()); + requireMember(violations, "vpcId", requested.getVpcId()); + if (requested.getSubnetIds() == null) { + violations.add(SmithyValidationErrors.notNull("subnetIds")); + } + requireMember(violations, "serviceRole", requested.getServiceRole()); + requireMember(violations, "workspaceSecurityGroupId", requested.getWorkspaceSecurityGroupId()); + requireMember(violations, "engineSecurityGroupId", requested.getEngineSecurityGroupId()); + requireMember(violations, "defaultS3Location", requested.getDefaultS3Location()); + checkEnum(violations, "authMode", requested.getAuthMode(), AUTH_MODES); + checkEnum(violations, "idcUserAssignment", requested.getIdcUserAssignment(), USER_ASSIGNMENTS); + checkLength(violations, "name", requested.getName()); + checkLength(violations, "description", requested.getDescription()); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + boolean sso = AUTH_SSO.equals(requested.getAuthMode()); + if (sso && requested.getUserRole() == null) { + throw EmrService.invalid("A Studio that uses IAM Identity Center authentication needs a UserRole."); + } + if (!sso && requested.getUserRole() != null) { + throw EmrService.invalid("A UserRole is only for a Studio that uses IAM Identity Center authentication."); + } + if (sso && (requested.getIdpAuthUrl() != null || requested.getIdpRelayStateParameterName() != null)) { + throw EmrService.invalid("IdpAuthUrl and IdpRelayStateParameterName are only for a Studio that uses IAM" + + " authentication."); + } + String region = regionResolver.getRegion(); + checkNetwork(region, requested.getVpcId(), requested.getSubnetIds(), null); + checkSecurityGroup(region, requested.getVpcId(), requested.getWorkspaceSecurityGroupId()); + checkSecurityGroup(region, requested.getVpcId(), requested.getEngineSecurityGroupId()); + if (sso) { + identityStoreOf(requested.getIdcInstanceArn()); + } + + EmrStudio studio = copy(requested); + String id = "es-" + EmrService.randomId(ID_LENGTH); + studio.setStudioId(id); + studio.setStudioArn(regionResolver.buildArn("elasticmapreduce", region, STUDIO_RESOURCE + id)); + studio.setUrl(baseUrl + URL_PATH + id); + studio.setCreationTime(now()); + studio.setRegion(region); + studio.setSequence(nextSequence()); + studio.setSubnetIds(new ArrayList<>(new LinkedHashSet<>(requested.getSubnetIds()))); + if (sso && studio.getTrustedIdentityPropagationEnabled() == null) { + // "The default value is false." + studio.setTrustedIdentityPropagationEnabled(false); + } + studio.setSessionMappings(new ArrayList<>()); + store.put(id, studio); + return copy(studio); + } + + public synchronized EmrStudio describeStudio(String studioId) { + return copy(requireStudio(studioId)); + } + + /** + * The Region's Studios in the order they were made, a page at a time after the request's Marker. No source gives + * AWS's order. + */ + public synchronized PaginatedResult listStudios(String marker) { + List studios = store.scan(key -> true).stream() + .filter(studio -> regionResolver.getRegion().equals(studio.getRegion())) + .toList(); + PaginatedResult page = Pagination.paginate(studios, + studio -> String.format("%020d", studio.getSequence()), PAGE_SIZE, marker, "ListStudios", + token -> EmrService.invalid("Invalid Marker.")); + return new PaginatedResult<>(page.items().stream().map(EmrStudioService::copy).toList(), page.nextToken()); + } + + /** + * Updates a Studio's name, description, subnets, default S3 location and encryption key, as given. Its subnets + * "can include new subnet IDs, but must also include all of the subnet IDs previously associated with the + * Studio", at most 5, in its VPC. + */ + public synchronized EmrStudio updateStudio(String studioId, String name, String description, + List subnetIds, String defaultS3Location, + String encryptionKeyArn) { + List violations = new ArrayList<>(); + checkLength(violations, "name", name); + checkLength(violations, "description", description); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + EmrStudio studio = requireStudio(studioId); + if (subnetIds != null) { + checkNetwork(studio.getRegion(), studio.getVpcId(), subnetIds, studio.getSubnetIds()); + studio.setSubnetIds(new ArrayList<>(new LinkedHashSet<>(subnetIds))); + } + if (name != null) { + studio.setName(name); + } + if (description != null) { + studio.setDescription(description); + } + if (defaultS3Location != null) { + studio.setDefaultS3Location(defaultS3Location); + } + if (encryptionKeyArn != null) { + studio.setEncryptionKeyArn(encryptionKeyArn); + } + store.put(studioId, studio); + return copy(studio); + } + + /** + * Adds tags to a Studio, a tag call's {@code ResourceId} being "a cluster identifier or an Amazon EMR Studio ID". + */ + public synchronized void addTags(String studioId, Map tags) { + EmrStudio studio = requireStudio(studioId); + Map updated = new LinkedHashMap<>(studio.getTags()); + updated.putAll(tags); + studio.setTags(updated); + store.put(studioId, studio); + } + + public synchronized void removeTags(String studioId, List keys) { + EmrStudio studio = requireStudio(studioId); + Map updated = new LinkedHashMap<>(studio.getTags()); + keys.forEach(updated::remove); + studio.setTags(updated); + store.put(studioId, studio); + } + + /** Whether a tag call's {@code ResourceId} names a Studio rather than a cluster. */ + static boolean isStudioId(String resourceId) { + return resourceId != null && resourceId.startsWith("es-"); + } + + /** The ARN of the Studio of that id in the Region, for IAM; empty when there is none. */ + public synchronized Optional studioArn(String studioId, String region) { + return store.get(studioId).filter(studio -> region.equals(studio.getRegion())).map(EmrStudio::getStudioArn); + } + + /** The tags held on the Studio stored under {@code arn}, in the account and Region it names, for IAM. */ + public Map storedTags(String arn) { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + if (!resource.startsWith(STUDIO_RESOURCE) || resource.indexOf('/', STUDIO_RESOURCE.length()) >= 0) { + return Map.of(); + } + Map held = new LinkedHashMap<>(); + String studioId = resource.substring(STUDIO_RESOURCE.length()); + AccountAwareStorageBackend.readInAccount(store, parsed.accountId(), studioId) + .filter(studio -> parsed.region().equals(studio.getRegion()) && arn.equals(studio.getStudioArn())) + .map(EmrStudio::getTags) + .ifPresent(tags -> tags.forEach((key, value) -> { + if (key != null && value != null) { + held.put(key, value); + } + })); + return held; + } + + /** Removes a Studio "from the Studio metadata store", its session mappings with it. */ + public synchronized void deleteStudio(String studioId) { + requireStudio(studioId); + store.delete(studioId); + } + + // ──────────────────────────── Session mappings ──────────────────────────── + + /** + * Maps a user or group of the Studio's IAM Identity Center instance to it, with a session policy, as "Use + * CreateStudioSessionMapping to assign users to a Studio when you use IAM Identity Center authentication". The + * identity is named by "Either IdentityName or IdentityId ... but not both", and must be in the instance's + * identity store, the user by its UserName and the group by its DisplayName. One already mapped is refused. + * Each refusal is InvalidRequestException in Floci's own wording. + */ + public synchronized EmrStudioSessionMapping createSessionMapping(String studioId, Identity identity, + String sessionPolicyArn) { + requireMappingMembers(identity, sessionPolicyArn, true); + EmrStudio studio = requireStudio(studioId); + if (!AUTH_SSO.equals(studio.getAuthMode())) { + throw EmrService.invalid("Studio " + studioId + " uses IAM authentication; session mappings are for a" + + " Studio that uses IAM Identity Center authentication."); + } + Identity resolved = resolve(studio, identity); + if (mappingOf(studio, resolved).isPresent()) { + throw EmrService.invalid("The " + resolved.type().toLowerCase() + " " + resolved.id() + + " is already mapped to Studio " + studioId + "."); + } + Instant now = now(); + EmrStudioSessionMapping mapping = new EmrStudioSessionMapping(); + mapping.setIdentityId(resolved.id()); + mapping.setIdentityName(resolved.name()); + mapping.setIdentityType(resolved.type()); + mapping.setSessionPolicyArn(sessionPolicyArn); + mapping.setCreationTime(now); + mapping.setLastModifiedTime(now); + mapping.setSequence(nextSequence()); + studio.getSessionMappings().add(mapping); + store.put(studioId, studio); + return copy(mapping); + } + + /** + * A mapping, found by the id or the name it was made with, without asking the identity store again: one whose + * user or group has since gone can still be read, updated and removed. + */ + public synchronized EmrStudioSessionMapping getSessionMapping(String studioId, Identity identity) { + requireMappingMembers(identity, null, false); + EmrStudio studio = requireStudio(studioId); + return copy(requireMapping(studio, identity)); + } + + public synchronized EmrStudioSessionMapping updateSessionMapping(String studioId, Identity identity, + String sessionPolicyArn) { + requireMappingMembers(identity, sessionPolicyArn, true); + EmrStudio studio = requireStudio(studioId); + EmrStudioSessionMapping mapping = requireMapping(studio, identity); + mapping.setSessionPolicyArn(sessionPolicyArn); + mapping.setLastModifiedTime(now()); + store.put(studioId, studio); + return copy(mapping); + } + + public synchronized void deleteSessionMapping(String studioId, Identity identity) { + requireMappingMembers(identity, null, false); + EmrStudio studio = requireStudio(studioId); + EmrStudioSessionMapping mapping = requireMapping(studio, identity); + studio.getSessionMappings().remove(mapping); + store.put(studioId, studio); + } + + /** + * The session mappings of the Studio, or of every Studio in the Region when the request names none, filtered by + * {@code identityType}, by Studio in the order they were made and then each Studio's in the order they were made, + * a page at a time after the request's Marker. No source gives AWS's order. + */ + public synchronized PaginatedResult listSessionMappings(String studioId, String identityType, + String marker) { + List violations = new ArrayList<>(); + checkEnum(violations, "identityType", identityType, IDENTITY_TYPES); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + List studios = studioId != null ? List.of(requireStudio(studioId)) + : store.scan(key -> true).stream() + .filter(studio -> regionResolver.getRegion().equals(studio.getRegion())) + .sorted(Comparator.comparingLong(EmrStudio::getSequence)) + .toList(); + List mappings = new ArrayList<>(); + for (EmrStudio studio : studios) { + for (EmrStudioSessionMapping mapping : studio.getSessionMappings()) { + if (identityType == null || identityType.equals(mapping.getIdentityType())) { + mappings.add(new StudioMapping(studio.getStudioId(), studio.getSequence(), mapping)); + } + } + } + String namespace = String.join("|", "ListStudioSessionMappings", String.valueOf(studioId), + String.valueOf(identityType)); + PaginatedResult page = Pagination.paginate(mappings, StudioMapping::cursor, PAGE_SIZE, marker, + namespace, token -> EmrService.invalid("Invalid Marker.")); + return new PaginatedResult<>(page.items().stream() + .map(item -> new StudioMapping(item.studioId(), item.studioSequence(), copy(item.mapping()))) + .toList(), page.nextToken()); + } + + /** A session mapping, with the Studio it maps to and that Studio's place among the account's. */ + public record StudioMapping(String studioId, long studioSequence, EmrStudioSessionMapping mapping) { + // Sorts as the listing does: by Studio, then by mapping, each in the order they were made. + String cursor() { + return String.format("%020d%020d", studioSequence, mapping.getSequence()); + } + } + + /** The identity a session mapping call names: its type, and its id or its name. */ + public record Identity(String type, String id, String name) { + } + + private void requireMappingMembers(Identity identity, String sessionPolicyArn, boolean policyRequired) { + List violations = new ArrayList<>(); + if (identity.type() == null) { + violations.add(SmithyValidationErrors.notNull("identityType")); + } + if (policyRequired && sessionPolicyArn == null) { + violations.add(SmithyValidationErrors.notNull("sessionPolicyArn")); + } + checkEnum(violations, "identityType", identity.type(), IDENTITY_TYPES); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + if ((identity.id() == null) == (identity.name() == null)) { + throw EmrService.invalid("Either IdentityName or IdentityId must be specified, but not both."); + } + } + + // The identity, with its id and its name, as the Studio's identity store holds it. + private Identity resolve(EmrStudio studio, Identity identity) { + String storeId = identityStoreOf(studio.getIdcInstanceArn()); + boolean user = "USER".equals(identity.type()); + Optional found; + if (user) { + found = (identity.id() != null ? identityStore.findUser(storeId, identity.id()) + : identityStore.findUserByName(storeId, identity.name())) + .map(u -> new Identity(identity.type(), u.userId(), u.userName())); + } else { + found = (identity.id() != null ? identityStore.findGroup(storeId, identity.id()) + : identityStore.findGroupByDisplayName(storeId, identity.name())) + .map(g -> new Identity(identity.type(), g.groupId(), g.displayName())); + } + return found.orElseThrow(() -> EmrService.invalid("The " + (user ? "user " : "group ") + + (identity.id() != null ? identity.id() : identity.name()) + + " is not in the Studio's IAM Identity Center identity store.")); + } + + // The identity store of the Studio's IAM Identity Center instance: the one it names, or else the account's. + private String identityStoreOf(String idcInstanceArn) { + List instances = ssoAdmin.listInstances(regionResolver.getAccountId()); + return instances.stream() + .filter(instance -> idcInstanceArn == null || idcInstanceArn.equals(instance.instanceArn())) + .map(SsoInstance::identityStoreId) + .findFirst() + .orElseThrow(() -> EmrService.invalid(idcInstanceArn == null + ? "The account has no IAM Identity Center instance." + : "IAM Identity Center instance " + idcInstanceArn + " does not exist.")); + } + + private static Optional mappingOf(EmrStudio studio, Identity identity) { + return studio.getSessionMappings().stream() + .filter(mapping -> identity.type().equals(mapping.getIdentityType()) + && identity.id().equals(mapping.getIdentityId())) + .findFirst(); + } + + // The mapping of the identity a call names, by the id or the name it was mapped with. + private static EmrStudioSessionMapping requireMapping(EmrStudio studio, Identity identity) { + return studio.getSessionMappings().stream() + .filter(mapping -> identity.type().equals(mapping.getIdentityType())) + .filter(mapping -> identity.id() != null ? identity.id().equals(mapping.getIdentityId()) + : identity.name().equals(mapping.getIdentityName())) + .findFirst() + .orElseThrow(() -> EmrService.invalid("The " + identity.type().toLowerCase() + " " + + (identity.id() != null ? identity.id() : identity.name()) + " is not mapped to Studio " + + studio.getStudioId() + ".")); + } + + /** + * A sequence above every one issued before, in this process or an earlier one, so that the number of a deleted + * Studio or mapping is never issued again and a listing's marker never skips a newer one: the microseconds of + * now, or one more than the last. + */ + private long nextSequence() { + lastSequence = Math.max(clock.instant().toEpochMilli() * 1000, lastSequence + 1); + return lastSequence; + } + + // The subnets, at most 5 and each in the VPC, which must exist; on an update, a superset of the current ones. + private void checkNetwork(String region, String vpcId, List subnetIds, List current) { + if (subnetIds.isEmpty()) { + throw EmrService.invalid("A Studio needs at least one subnet."); + } + if (new LinkedHashSet<>(subnetIds).size() > MAX_SUBNETS) { + throw EmrService.invalid("A Studio can have a maximum of " + MAX_SUBNETS + " subnets."); + } + if (current != null && !subnetIds.containsAll(current)) { + throw EmrService.invalid("The subnets must include all of the subnet IDs previously associated with" + + " the Studio."); + } + if (ec2.describeVpcs(region, List.of(vpcId), Map.of()).isEmpty()) { + throw EmrService.invalid("VPC " + vpcId + " does not exist."); + } + List subnets = ec2.describeSubnets(region, List.copyOf(new LinkedHashSet<>(subnetIds)), Map.of()); + for (String subnetId : subnetIds) { + Subnet subnet = subnets.stream().filter(s -> subnetId.equals(s.getSubnetId())).findFirst() + .orElseThrow(() -> EmrService.invalid("Subnet " + subnetId + " does not exist.")); + if (!vpcId.equals(subnet.getVpcId())) { + throw EmrService.invalid("Subnet " + subnetId + " is not in VPC " + vpcId + "."); + } + } + } + + private void checkSecurityGroup(String region, String vpcId, String groupId) { + SecurityGroup group = ec2.describeSecurityGroups(region, List.of(groupId), List.of(), Map.of()).stream() + .findFirst() + .orElseThrow(() -> EmrService.invalid("Security group " + groupId + " does not exist.")); + if (!vpcId.equals(group.getVpcId())) { + throw EmrService.invalid("Security group " + groupId + " is not in VPC " + vpcId + "."); + } + } + + private EmrStudio requireStudio(String studioId) { + if (studioId == null) { + throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("studioId")); + } + return store.get(studioId) + .filter(studio -> regionResolver.getRegion().equals(studio.getRegion())) + .orElseThrow(() -> EmrService.invalid("Studio " + studioId + " does not exist.")); + } + + private static void requireMember(List violations, String member, String value) { + if (value == null) { + violations.add(SmithyValidationErrors.notNull(member)); + } + } + + private static void checkEnum(List violations, String member, String value, List allowed) { + if (value != null && !allowed.contains(value)) { + violations.add(SmithyValidationErrors.notInEnum(value, member, allowed)); + } + } + + private static void checkLength(List violations, String member, String value) { + if (value != null && value.length() > MAX_NAME_LENGTH) { + violations.add(SmithyValidationErrors.lengthOutOfRange(member, value, 0, MAX_NAME_LENGTH)); + } + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MILLIS); + } + + private static EmrStudio copy(EmrStudio studio) { + return EmrService.SNAPSHOT_MAPPER.convertValue(studio, EmrStudio.class); + } + + private static EmrStudioSessionMapping copy(EmrStudioSessionMapping mapping) { + return EmrService.SNAPSHOT_MAPPER.convertValue(mapping, EmrStudioSessionMapping.class); + } +} diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrStudio.java b/src/main/java/io/floci/aws/services/emr/model/EmrStudio.java new file mode 100644 index 0000000000..69611a4687 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/model/EmrStudio.java @@ -0,0 +1,103 @@ +package io.floci.aws.services.emr.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * An EMR Studio, as DescribeStudio reports it, with the Region it is in and its users' and groups' session mappings, + * oldest first. + */ +@RegisterForReflection +public class EmrStudio { + private String studioId; + private String studioArn; + private String name; + private String description; + private String authMode; + private String vpcId; + private List subnetIds = new ArrayList<>(); + private String serviceRole; + private String userRole; + private String workspaceSecurityGroupId; + private String engineSecurityGroupId; + private String url; + private Instant creationTime; + private String defaultS3Location; + private String idpAuthUrl; + private String idpRelayStateParameterName; + private Map tags = new LinkedHashMap<>(); + private String idcInstanceArn; + private Boolean trustedIdentityPropagationEnabled; + private String idcUserAssignment; + private String encryptionKeyArn; + private String region; + // Its place among the account's Studios, 1 for the first, which orders ListStudios. + private long sequence; + private List sessionMappings = new ArrayList<>(); + + public EmrStudio() {} + + public String getStudioId() { return studioId; } + public void setStudioId(String studioId) { this.studioId = studioId; } + public String getStudioArn() { return studioArn; } + public void setStudioArn(String studioArn) { this.studioArn = studioArn; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public String getAuthMode() { return authMode; } + public void setAuthMode(String authMode) { this.authMode = authMode; } + public String getVpcId() { return vpcId; } + public void setVpcId(String vpcId) { this.vpcId = vpcId; } + public List getSubnetIds() { return subnetIds; } + public void setSubnetIds(List subnetIds) { this.subnetIds = subnetIds; } + public String getServiceRole() { return serviceRole; } + public void setServiceRole(String serviceRole) { this.serviceRole = serviceRole; } + public String getUserRole() { return userRole; } + public void setUserRole(String userRole) { this.userRole = userRole; } + public String getWorkspaceSecurityGroupId() { return workspaceSecurityGroupId; } + public void setWorkspaceSecurityGroupId(String workspaceSecurityGroupId) { + this.workspaceSecurityGroupId = workspaceSecurityGroupId; + } + public String getEngineSecurityGroupId() { return engineSecurityGroupId; } + public void setEngineSecurityGroupId(String engineSecurityGroupId) { + this.engineSecurityGroupId = engineSecurityGroupId; + } + public String getUrl() { return url; } + public void setUrl(String url) { this.url = url; } + public Instant getCreationTime() { return creationTime; } + public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } + public String getDefaultS3Location() { return defaultS3Location; } + public void setDefaultS3Location(String defaultS3Location) { this.defaultS3Location = defaultS3Location; } + public String getIdpAuthUrl() { return idpAuthUrl; } + public void setIdpAuthUrl(String idpAuthUrl) { this.idpAuthUrl = idpAuthUrl; } + public String getIdpRelayStateParameterName() { return idpRelayStateParameterName; } + public void setIdpRelayStateParameterName(String idpRelayStateParameterName) { + this.idpRelayStateParameterName = idpRelayStateParameterName; + } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + public String getIdcInstanceArn() { return idcInstanceArn; } + public void setIdcInstanceArn(String idcInstanceArn) { this.idcInstanceArn = idcInstanceArn; } + public Boolean getTrustedIdentityPropagationEnabled() { return trustedIdentityPropagationEnabled; } + public void setTrustedIdentityPropagationEnabled(Boolean trustedIdentityPropagationEnabled) { + this.trustedIdentityPropagationEnabled = trustedIdentityPropagationEnabled; + } + public String getIdcUserAssignment() { return idcUserAssignment; } + public void setIdcUserAssignment(String idcUserAssignment) { this.idcUserAssignment = idcUserAssignment; } + public String getEncryptionKeyArn() { return encryptionKeyArn; } + public void setEncryptionKeyArn(String encryptionKeyArn) { this.encryptionKeyArn = encryptionKeyArn; } + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + public long getSequence() { return sequence; } + public void setSequence(long sequence) { this.sequence = sequence; } + public List getSessionMappings() { return sessionMappings; } + public void setSessionMappings(List sessionMappings) { + this.sessionMappings = sessionMappings; + } +} diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrStudioSessionMapping.java b/src/main/java/io/floci/aws/services/emr/model/EmrStudioSessionMapping.java new file mode 100644 index 0000000000..7729fc2d65 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/model/EmrStudioSessionMapping.java @@ -0,0 +1,36 @@ +package io.floci.aws.services.emr.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** A user or group of IAM Identity Center mapped to a Studio, with the session policy that refines its permissions. */ +@RegisterForReflection +public class EmrStudioSessionMapping { + + private String identityId; + private String identityName; + private String identityType; + private String sessionPolicyArn; + private Instant creationTime; + private Instant lastModifiedTime; + // Its place among its Studio's mappings, 1 for the first, which orders ListStudioSessionMappings. + private long sequence; + + public EmrStudioSessionMapping() {} + + public String getIdentityId() { return identityId; } + public void setIdentityId(String identityId) { this.identityId = identityId; } + public String getIdentityName() { return identityName; } + public void setIdentityName(String identityName) { this.identityName = identityName; } + public String getIdentityType() { return identityType; } + public void setIdentityType(String identityType) { this.identityType = identityType; } + public String getSessionPolicyArn() { return sessionPolicyArn; } + public void setSessionPolicyArn(String sessionPolicyArn) { this.sessionPolicyArn = sessionPolicyArn; } + public Instant getCreationTime() { return creationTime; } + public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } + public Instant getLastModifiedTime() { return lastModifiedTime; } + public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } + public long getSequence() { return sequence; } + public void setSequence(long sequence) { this.sequence = sequence; } +} diff --git a/src/main/java/io/floci/aws/services/identitystore/IdentityStoreService.java b/src/main/java/io/floci/aws/services/identitystore/IdentityStoreService.java index d9ef747c04..4b79cd8b62 100644 --- a/src/main/java/io/floci/aws/services/identitystore/IdentityStoreService.java +++ b/src/main/java/io/floci/aws/services/identitystore/IdentityStoreService.java @@ -219,6 +219,30 @@ public class IdentityStoreService implements Resettable { return users.getForAccount(GLOBAL_PARTITION, userKey(storeId, userId)); } + /** The user of the identity store {@code storeId} whose {@code UserName} is {@code userName}, if it holds one. */ + public Optional findUserByName(String storeId, String userName) { + if (storeId == null || userName == null) { + return Optional.empty(); + } + return listUsersAll(storeId, userName).stream().findFirst(); + } + + /** The group {@code groupId} of the identity store {@code storeId}, if the store holds one. */ + public Optional findGroup(String storeId, String groupId) { + if (storeId == null || groupId == null) { + return Optional.empty(); + } + return groups.getForAccount(GLOBAL_PARTITION, groupKey(storeId, groupId)); + } + + /** The group of the identity store {@code storeId} whose {@code DisplayName} is {@code displayName}, if any. */ + public Optional findGroupByDisplayName(String storeId, String displayName) { + if (storeId == null || displayName == null) { + return Optional.empty(); + } + return listGroupsAll(storeId, displayName).stream().findFirst(); + } + public synchronized void updateUser(JsonNode request) { String storeId = requireStore(required(request, "IdentityStoreId")); String userId = requireResourceId(required(request, "UserId"), "UserId"); diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index 01c84393a0..628435f9ff 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -1112,8 +1112,8 @@ class EmrServiceContainerStepsTest { fixture.runStepThread(); ObjectMapper objectMapper = new ObjectMapper(); - JsonNode answer = (JsonNode) new EmrHandler(service, objectMapper).handle("DescribeStep", - objectMapper.createObjectNode().put("ClusterId", cluster.getId()) + JsonNode answer = (JsonNode) new EmrHandler(service, mock(EmrStudioService.class), objectMapper) + .handle("DescribeStep", objectMapper.createObjectNode().put("ClusterId", cluster.getId()) .put("StepId", cluster.getSteps().get(0).getId()), REGION).getEntity(); JsonNode status = answer.path("Step").path("Status"); @@ -2040,7 +2040,7 @@ class EmrServiceContainerStepsTest { bootstrapping.runStepThread(); String waitingId = bootstrapping.service.runJobFlow(cluster("waiting", true), REGION).getId(); ObjectMapper objectMapper = new ObjectMapper(); - EmrHandler handler = new EmrHandler(bootstrapping.service, objectMapper); + EmrHandler handler = new EmrHandler(bootstrapping.service, mock(EmrStudioService.class), objectMapper); String page = ERROR_CODE_PAGES + "BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE.html"; JsonNode expected = objectMapper.readTree(""" [{"ErrorCode": "BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE", diff --git a/src/test/java/io/floci/aws/services/emr/EmrStudioIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrStudioIntegrationTest.java new file mode 100644 index 0000000000..b52aa98d32 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrStudioIntegrationTest.java @@ -0,0 +1,282 @@ +package io.floci.aws.services.emr; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.Subnet; +import io.floci.aws.services.identitystore.IdentityStoreService; +import io.floci.aws.services.ssoadmin.SsoAdminService; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.testing.EmrRequests.emr; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * EMR Studios and their session mappings over the AWS JSON 1.1 wire protocol, against Floci's own EC2 (the Region's + * default VPC, its subnets and security group) and IAM Identity Center (the account's instance and its identity store). + */ +@QuarkusTest +class EmrStudioIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String POLICY = "arn:aws:iam::000000000000:policy/EMRStudio_Basic_User_Policy"; + + @Inject + Ec2Service ec2; + + @Inject + SsoAdminService ssoAdmin; + + @Inject + IdentityStoreService identityStore; + + @Inject + ObjectMapper objectMapper; + + @Inject + EmrService emrService; + + private String vpcId; + private List subnetIds; + private String securityGroupId; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void network() { + vpcId = ec2.describeVpcs(REGION, List.of(), Map.of("is-default", List.of("true"))).get(0).getVpcId(); + subnetIds = ec2.describeSubnets(REGION, List.of(), Map.of("vpc-id", List.of(vpcId))).stream() + .map(Subnet::getSubnetId).limit(3).toList(); + securityGroupId = ec2.describeSecurityGroups(REGION, List.of(), List.of(), + Map.of("vpc-id", List.of(vpcId))).get(0).getGroupId(); + assertTrue(subnetIds.size() >= 3, "the default VPC's subnets: " + subnetIds); + } + + @Test + void anIdentityCenterStudioIsCreatedDescribedListedUpdatedAndDeleted() { + String studioId = studio("SSO", "\"UserRole\": \"EMRStudio_User_Role\",", subnetIds.subList(0, 2)); + + emr("DescribeStudio", "{\"StudioId\":\"" + studioId + "\"}") + .then().statusCode(200) + .body("Studio.StudioId", equalTo(studioId)) + .body("Studio.StudioArn", equalTo("arn:aws:elasticmapreduce:us-east-1:000000000000:studio/" + + studioId)) + .body("Studio.AuthMode", equalTo("SSO")) + .body("Studio.VpcId", equalTo(vpcId)) + .body("Studio.SubnetIds", equalTo(subnetIds.subList(0, 2))) + .body("Studio.UserRole", equalTo("EMRStudio_User_Role")) + .body("Studio.Url", endsWith("/_aws/emr/studios/" + studioId)) + .body("Studio.TrustedIdentityPropagationEnabled", equalTo(false)) + .body("Studio.CreationTime", notNullValue()) + .body("Studio.Tags[0].Key", equalTo("team")); + emr("ListStudios", "{}") + .then().statusCode(200) + .body("Studios.StudioId", hasItem(studioId)); + + emr("UpdateStudio", "{\"StudioId\":\"" + studioId + "\",\"Name\":\"renamed\",\"SubnetIds\":" + + json(subnetIds) + "}") + .then().statusCode(200); + emr("DescribeStudio", "{\"StudioId\":\"" + studioId + "\"}") + .then().statusCode(200) + .body("Studio.Name", equalTo("renamed")) + .body("Studio.SubnetIds", equalTo(subnetIds)); + // "must also include all of the subnet IDs previously associated with the Studio" + emr("UpdateStudio", "{\"StudioId\":\"" + studioId + "\",\"SubnetIds\":" + json(subnetIds.subList(0, 1)) + + "}") + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + + emr("DeleteStudio", "{\"StudioId\":\"" + studioId + "\"}").then().statusCode(200); + emr("DescribeStudio", "{\"StudioId\":\"" + studioId + "\"}") + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + emr("ListStudios", "{}") + .then().statusCode(200) + .body("Studios.StudioId", not(hasItem(studioId))); + } + + @Test + void aStudiosRepeatedSubnetsAreKeptOnceAndItsTagsChangeThroughTheTagCalls() { + String repeated = subnetIds.get(0); + String studioId = studio("IAM", "", List.of(repeated, repeated, repeated, repeated, repeated, repeated)); + emr("DescribeStudio", "{\"StudioId\":\"" + studioId + "\"}") + .then().statusCode(200) + .body("Studio.SubnetIds", equalTo(List.of(repeated))); + + // A tag call's ResourceId is "a cluster identifier or an Amazon EMR Studio ID". + emr("AddTags", "{\"ResourceId\":\"" + studioId + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"dev\"}]}") + .then().statusCode(200); + emr("RemoveTags", "{\"ResourceId\":\"" + studioId + "\",\"TagKeys\":[\"team\"]}") + .then().statusCode(200); + emr("DescribeStudio", "{\"StudioId\":\"" + studioId + "\"}") + .then().statusCode(200) + .body("Studio.Tags.size()", equalTo(1)) + .body("Studio.Tags[0].Key", equalTo("env")) + .body("Studio.Tags[0].Value", equalTo("dev")); + // What an IAM condition on aws:ResourceTag reads of the Studio, and the ARN a tag call names it by. + String arn = "arn:aws:elasticmapreduce:us-east-1:000000000000:studio/" + studioId; + assertEquals(Map.of("env", "dev"), emrService.storedTags(arn)); + assertEquals(List.of(arn), emrService.through("ResourceId", studioId, REGION)); + emr("DeleteStudio", "{\"StudioId\":\"" + studioId + "\"}").then().statusCode(200); + } + + @Test + void aMappingWhoseUserHasGoneCanStillBeReadAndRemoved() throws Exception { + String storeId = ssoAdmin.listInstances(ACCOUNT).get(0).identityStoreId(); + String userId = identityStore.createUser(objectMapper.readTree(""" + {"IdentityStoreId": "%s", "UserName": "gone-%s", "DisplayName": "Gone"} + """.formatted(storeId, UUID.randomUUID()))).userId(); + String studioId = studio("SSO", "\"UserRole\": \"EMRStudio_User_Role\",", subnetIds.subList(0, 1)); + emr("CreateStudioSessionMapping", mapping(studioId, "USER", userId, null, POLICY)).then().statusCode(200); + + identityStore.deleteUser(objectMapper.readTree(""" + {"IdentityStoreId": "%s", "UserId": "%s"} + """.formatted(storeId, userId))); + + emr("GetStudioSessionMapping", mapping(studioId, "USER", userId, null, null)) + .then().statusCode(200) + .body("SessionMapping.IdentityId", equalTo(userId)); + emr("DeleteStudioSessionMapping", mapping(studioId, "USER", userId, null, null)).then().statusCode(200); + emr("DeleteStudio", "{\"StudioId\":\"" + studioId + "\"}").then().statusCode(200); + } + + @Test + void aStudioIsRefusedForItsNetworkItsAuthModesRolesOrAMalformedRequest() { + String sso = "\"UserRole\": \"EMRStudio_User_Role\","; + refused(create("SSO", sso, List.of("subnet-1", "subnet-2", "subnet-3", "subnet-4", "subnet-5", "subnet-6"), + vpcId, securityGroupId), "InvalidRequestException"); + refused(create("SSO", sso, subnetIds, "vpc-00000000000000000", securityGroupId), "InvalidRequestException"); + refused(create("SSO", sso, List.of("subnet-00000000000000000"), vpcId, securityGroupId), + "InvalidRequestException"); + refused(create("SSO", sso, subnetIds, vpcId, "sg-00000000000000000"), "InvalidRequestException"); + refused(create("SSO", "", subnetIds, vpcId, securityGroupId), "InvalidRequestException"); + refused(create("IAM", sso, subnetIds, vpcId, securityGroupId), "InvalidRequestException"); + refused(create("SSO", sso + "\"IdpAuthUrl\": \"https://idp.example/login\",", subnetIds, vpcId, + securityGroupId), "InvalidRequestException"); + refused(create("OIDC", "", subnetIds, vpcId, securityGroupId), "ValidationException"); + refused("{\"Name\": \"n\"}", "ValidationException"); + refused(create("SSO", sso, subnetIds, vpcId, securityGroupId).replace(json(subnetIds), + "\"" + subnetIds.get(0) + "\""), "SerializationException"); + } + + @Test + void anIdentityCenterStudiosUsersAndGroupsAreMappedFoundUpdatedListedAndRemoved() throws Exception { + String storeId = ssoAdmin.listInstances(ACCOUNT).get(0).identityStoreId(); + String userName = "ana-" + UUID.randomUUID(); + String userId = identityStore.createUser(objectMapper.readTree(""" + {"IdentityStoreId": "%s", "UserName": "%s", "DisplayName": "Ana", + "Name": {"GivenName": "Ana", "FamilyName": "Silva"}} + """.formatted(storeId, userName))).userId(); + String groupName = "analysts-" + UUID.randomUUID(); + String groupId = identityStore.createGroup(objectMapper.readTree(""" + {"IdentityStoreId": "%s", "DisplayName": "%s"} + """.formatted(storeId, groupName))).groupId(); + String studioId = studio("SSO", "\"UserRole\": \"EMRStudio_User_Role\",", subnetIds.subList(0, 1)); + + emr("CreateStudioSessionMapping", mapping(studioId, "USER", null, userName, POLICY)) + .then().statusCode(200); + emr("CreateStudioSessionMapping", mapping(studioId, "GROUP", groupId, null, POLICY)) + .then().statusCode(200); + emr("GetStudioSessionMapping", mapping(studioId, "USER", userId, null, null)) + .then().statusCode(200) + .body("SessionMapping.StudioId", equalTo(studioId)) + .body("SessionMapping.IdentityId", equalTo(userId)) + .body("SessionMapping.IdentityName", equalTo(userName)) + .body("SessionMapping.IdentityType", equalTo("USER")) + .body("SessionMapping.SessionPolicyArn", equalTo(POLICY)) + .body("SessionMapping.LastModifiedTime", notNullValue()); + emr("CreateStudioSessionMapping", mapping(studioId, "USER", userId, null, POLICY)) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + + String advanced = "arn:aws:iam::000000000000:policy/EMRStudio_Advanced_User_Policy"; + emr("UpdateStudioSessionMapping", mapping(studioId, "GROUP", null, groupName, advanced)) + .then().statusCode(200); + emr("ListStudioSessionMappings", "{\"StudioId\":\"" + studioId + "\",\"IdentityType\":\"GROUP\"}") + .then().statusCode(200) + .body("SessionMappings.size()", equalTo(1)) + .body("SessionMappings[0].IdentityId", equalTo(groupId)) + .body("SessionMappings[0].IdentityName", equalTo(groupName)) + .body("SessionMappings[0].SessionPolicyArn", equalTo(advanced)); + emr("ListStudioSessionMappings", "{}") + .then().statusCode(200) + .body("SessionMappings.IdentityId", hasItem(userId)); + + // "Either IdentityName or IdentityId must be specified, but not both." + emr("GetStudioSessionMapping", mapping(studioId, "USER", userId, userName, null)) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + emr("CreateStudioSessionMapping", mapping(studioId, "USER", null, "nobody-" + UUID.randomUUID(), POLICY)) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + + emr("DeleteStudioSessionMapping", mapping(studioId, "USER", userId, null, null)).then().statusCode(200); + emr("GetStudioSessionMapping", mapping(studioId, "USER", userId, null, null)) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + + String iamStudio = studio("IAM", "", subnetIds.subList(0, 1)); + emr("CreateStudioSessionMapping", mapping(iamStudio, "USER", userId, null, POLICY)) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + emr("DeleteStudio", "{\"StudioId\":\"" + studioId + "\"}").then().statusCode(200); + emr("DeleteStudio", "{\"StudioId\":\"" + iamStudio + "\"}").then().statusCode(200); + } + + private String studio(String authMode, String extra, List subnets) { + return emr("CreateStudio", create(authMode, extra, subnets, vpcId, securityGroupId)) + .then().statusCode(200) + .body("StudioId", matchesPattern("es-[A-Z0-9]{25}")) + .extract().path("StudioId"); + } + + private static String create(String authMode, String extra, List subnets, String vpc, String group) { + return """ + {"Name": "studio-%s", "AuthMode": "%s", %s "VpcId": "%s", "SubnetIds": %s, + "ServiceRole": "EMRStudio_Service_Role", "WorkspaceSecurityGroupId": "%s", + "EngineSecurityGroupId": "%s", "DefaultS3Location": "s3://bucket/studio/", + "Tags": [{"Key": "team", "Value": "data"}]} + """.formatted(UUID.randomUUID(), authMode, extra, vpc, json(subnets), group, group); + } + + private static void refused(String body, String type) { + emr("CreateStudio", body).then().statusCode(400).body("__type", equalTo(type)); + } + + private static String mapping(String studioId, String type, String id, String name, String policy) { + StringBuilder body = new StringBuilder("{\"StudioId\":\"" + studioId + "\",\"IdentityType\":\"" + type + "\""); + if (id != null) { + body.append(",\"IdentityId\":\"").append(id).append('"'); + } + if (name != null) { + body.append(",\"IdentityName\":\"").append(name).append('"'); + } + if (policy != null) { + body.append(",\"SessionPolicyArn\":\"").append(policy).append('"'); + } + return body.append('}').toString(); + } + + private static String json(List values) { + return "[" + String.join(",", values.stream().map(value -> "\"" + value + "\"").toList()) + "]"; + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrStudioServiceTest.java b/src/test/java/io/floci/aws/services/emr/EmrStudioServiceTest.java new file mode 100644 index 0000000000..328131d104 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrStudioServiceTest.java @@ -0,0 +1,80 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.SecurityGroup; +import io.floci.aws.services.ec2.model.Subnet; +import io.floci.aws.services.ec2.model.Vpc; +import io.floci.aws.services.emr.model.EmrStudio; +import io.floci.aws.services.identitystore.IdentityStoreService; +import io.floci.aws.services.ssoadmin.SsoAdminService; +import io.floci.aws.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** A Studio's place in its listing, which no deleted Studio's can take, through {@link EmrStudioService}. */ +class EmrStudioServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private final MutableClock clock = new MutableClock(); + private EmrStudioService studios; + + @BeforeEach + void setUp() { + Ec2Service ec2 = mock(Ec2Service.class); + Vpc vpc = new Vpc(); + vpc.setVpcId("vpc-1"); + Subnet subnet = new Subnet(); + subnet.setSubnetId("subnet-1"); + subnet.setVpcId("vpc-1"); + SecurityGroup group = new SecurityGroup(); + group.setGroupId("sg-1"); + group.setVpcId("vpc-1"); + when(ec2.describeVpcs(eq(REGION), anyList(), any())).thenReturn(List.of(vpc)); + when(ec2.describeSubnets(eq(REGION), anyList(), any())).thenReturn(List.of(subnet)); + when(ec2.describeSecurityGroups(eq(REGION), anyList(), anyList(), any())).thenReturn(List.of(group)); + studios = new EmrStudioService(AccountAwareStorageBackend.inMemory(ACCOUNT), + new RegionResolver(REGION, ACCOUNT), ec2, mock(SsoAdminService.class), + mock(IdentityStoreService.class), clock, "http://localhost:4566"); + } + + @Test + void aStudioMadeAfterTheNewestIsDeletedListsAfterEveryEarlierOne() { + String first = studios.createStudio(studio("first")).getStudioId(); + EmrStudio newest = studios.createStudio(studio("newest")); + studios.deleteStudio(newest.getStudioId()); + + EmrStudio replacement = studios.createStudio(studio("replacement")); + + assertTrue(replacement.getSequence() > newest.getSequence(), + replacement.getSequence() + " after " + newest.getSequence()); + assertEquals(List.of(first, replacement.getStudioId()), studios.listStudios(null).items().stream() + .map(EmrStudio::getStudioId).toList()); + } + + private static EmrStudio studio(String name) { + EmrStudio studio = new EmrStudio(); + studio.setName(name); + studio.setAuthMode("IAM"); + studio.setVpcId("vpc-1"); + studio.setSubnetIds(List.of("subnet-1")); + studio.setServiceRole("EMRStudio_Service_Role"); + studio.setWorkspaceSecurityGroupId("sg-1"); + studio.setEngineSecurityGroupId("sg-1"); + studio.setDefaultS3Location("s3://bucket/studio/"); + return studio; + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java index 09c8f97edb..ce11df462a 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.services.emr.EmrHandler; import io.floci.aws.services.emr.EmrService; +import io.floci.aws.services.emr.EmrStudioService; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrStep; import io.floci.aws.services.stepfunctions.model.Execution; @@ -71,7 +72,8 @@ class AslExecutorEmrSyncTest { .objectMapper(objectMapper) .sfnService(instance) .customResourceLiveness(null) - .emrTaskInvoker(new EmrTaskInvoker(new EmrHandler(emrService, objectMapper), objectMapper)) + .emrTaskInvoker(new EmrTaskInvoker( + new EmrHandler(emrService, mock(EmrStudioService.class), objectMapper), objectMapper)) .nanoTime(testNanos::get) .sleeper(testNanos::addAndGet) .build();