From 1fe555fbc22978827ac303bcce7d53f390698bfc Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:34:12 -0400 Subject: [PATCH] feat(cloudformation): provision EMR security configurations, Studios and session mappings (#9152) A template can now create AWS::EMR::SecurityConfiguration, AWS::EMR::Studio and AWS::EMR::StudioSessionMapping. None was served, so the stack reported CREATE_COMPLETE with nothing behind it. They go through the services the EMR API uses, and the properties are read as model validation reads them, against the registry schemas, now in the vendored property types. - A security configuration's Ref is its name, generated when the template gives none; its JSON is taken as an object or its text. Both properties are create-only, so a change replaces it, and one that keeps a template's own name is refused, as for every custom-named resource. - A Studio's Ref is its id; Fn::GetAtt gives StudioId, Arn and Url, and a template that sets one of them is refused. UpdateStudio applies the Name, Description, SubnetIds and DefaultS3Location the template changes, and the tags change for the keys the stack owns. A change to IdpAuthUrl or IdpRelayStateParameterName is accepted with a warning and not applied, as no Studio API changes them, and a create-only change replaces the Studio. - A session mapping's Ref is StudioId|IdentityType|IdentityName, its primary identifier; SessionPolicyArn updates in place, and another identity replaces it. - A later resource's failure, or a failure of the update itself, puts back what the update changed, but a Studio's added subnets, which UpdateStudio cannot take away. A gone resource fails an update and counts as deleted. Two shared fixes go with them. Model validation now looks for a schema pattern in a value, as the validator CloudFormation runs does, instead of matching the whole value, so a Studio named with spaces passes. And CreateSecurityConfiguration, from the API or a stack, refuses a configuration that is no JSON object, which a cluster naming it could not read. --- docs/services/cloudformation.md | 1 + .../provisioners/CfnPropertyTypes.java | 4 +- .../provisioners/EmrCfnProvisioner.java | 98 +++++ .../provisioners/EmrStudioCfnProvisioner.java | 394 ++++++++++++++++++ .../io/floci/aws/services/emr/EmrService.java | 13 + .../resources/aws/cfn-property-types.json | 169 ++++++++ .../create-only-properties.json | 21 + .../cloudformation/CfnProvisionerFixture.java | 22 + .../EmrStudioCfnIntegrationTest.java | 183 ++++++++ .../provisioners/CfnPropertyTypesTest.java | 21 + .../provisioners/EmrCfnProvisionerTest.java | 123 ++++++ .../EmrStudioCfnProvisionerTest.java | 254 +++++++++++ .../provisioners/ProvisionContexts.java | 19 + .../aws/services/emr/EmrIntegrationTest.java | 8 + .../cloudformation/schema-surface.tsv | 3 + .../supported-resource-types.tsv | 3 + tools/aws/regen_cfn_property_types.py | 1 + tools/docs/cfn_resource_types.yaml | 6 + 18 files changed, 1342 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/EmrStudioCfnIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 8cafb9071a..7814d7607d 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -220,6 +220,7 @@ cross-resource references. | ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` | | EFS | `FileSystem` (metadata only, there is no NFS data plane), `MountTarget` (`SecurityGroups` update in place, every other property replaces), `AccessPoint` (`AccessPointTags` update in place, every other property replaces) | | EKS | `Cluster` (created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack, for `Logging`, for `AccessConfig.AuthenticationMode` (a mode cannot be moved back, so a stack update that does so fails, and a stack rollback restores it) and for `ResourcesVpcConfig` endpoint access and `PublicAccessCidrs`; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion`; a change to the subnets or security groups of `ResourcesVpcConfig` fails the resource, as the emulator's `UpdateClusterConfig` does not change them), `Nodegroup` (created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place) | +| EMR | `SecurityConfiguration` (created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template's own `Name` is refused, as for every custom-named resource), `Studio` (created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits), `StudioSessionMapping` (`Ref` is `StudioId|IdentityType|IdentityName`, the schema's primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping) | | EMR on EKS | `VirtualCluster` (created with `Name`, `ContainerProvider`, `SecurityConfigurationId`, `SessionEnabled` and `Tags`; a template that sets the read-only `Arn` or `Id` is refused; updated in place for `Tags` alone, which end as the template lists them, any other but an `aws:` one removed; a change to any other property replaces the virtual cluster, as the registry marks them create-only, and terminates the old one once the update commits; an update of a virtual cluster that is terminated or gone fails) | | EMR Serverless | `Application` (created with every property, `Name` and `Type` included; updated in place through `UpdateApplication` for the settings a template changes, a dropped setting kept as it is but for `InitialCapacity`, which is cleared, and for `Tags`, which end as the template lists them, any other removed; a change to `Name` or `Type` replaces the application and deletes the old one once the update commits; neither an update nor a delete stops a `STARTED` application, so one it refuses fails the resource, as on AWS) | | RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java index be8083f573..7bc5195d89 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java @@ -494,7 +494,9 @@ final class CfnPropertyTypes { record(new Violation(path, "expected maxLength: " + shape.maxLength() + ", actual: " + length, true), true); } - if (shape.pattern() != null && !Pattern.compile(shape.pattern()).matcher(value).matches()) { + // A schema pattern is not anchored: the validator CloudFormation runs looks for it in the value, as the + // Studio schema's Name pattern [a-zA-Z0-9_-]+ takes "notebooks for etl". + if (shape.pattern() != null && !Pattern.compile(shape.pattern()).matcher(value).find()) { record(new Violation(path, "failed validation constraint for keyword [pattern]", true), true); } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java new file mode 100644 index 0000000000..5156ddbf6a --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java @@ -0,0 +1,98 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.emr.EmrService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * CloudFormation provisioning for Amazon EMR's own types over {@link EmrService}: for now + * {@code AWS::EMR::SecurityConfiguration}, whose {@code Ref} is its name and which has no {@code Fn::GetAtt} + * attributes. + * + *

Both of a security configuration's properties are create-only and its schema has no update handler, so any change + * replaces it: under a new name, generated when the template gives none, and refused, as for every custom-named + * resource, when the template keeps its own name. The {@code SecurityConfiguration} JSON is taken as an object or as + * the text of one, as the schema allows both. + */ +@ApplicationScoped +public class EmrCfnProvisioner implements CfnResourceProvisioner { + + private static final String SECURITY_CONFIGURATION = "AWS::EMR::SecurityConfiguration"; + private static final int NAME_MAX_LENGTH = 255; + + private final EmrService emrService; + + @Inject + public EmrCfnProvisioner(EmrService emrService) { + this.emrService = emrService; + } + + @Override + public Set resourceTypes() { + return Set.of(SECURITY_CONFIGURATION); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + ReplacementCleanup.clear(resource); + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + return ReplacementCleanup.rollback(resource, this::delete); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(SECURITY_CONFIGURATION, props); + String explicitName = template.path("Name").textValue(); + boolean stub = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore); + if (ctx.isUpdate() && !stub && !ctx.changes(SECURITY_CONFIGURATION, props).requiresReplacement()) { + r.setPhysicalId(ctx.priorPhysicalId()); + } else { + if (ctx.isUpdate() && !stub && explicitName != null && explicitName.equals(ctx.priorPhysicalId())) { + throw CfnExceptions.customNamedReplacement(explicitName); + } + String name = explicitName != null ? explicitName + : ctx.generatePhysicalName(r.getLogicalId(), NAME_MAX_LENGTH, false); + JsonNode configuration = template.path("SecurityConfiguration"); + emrService.createSecurityConfiguration(name, + configuration.isTextual() ? configuration.textValue() : configuration.toString(), ctx.region()); + r.setPhysicalId(name); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** Deletes the security configuration, unless the Region lists none of that name, it being gone. */ + @Override + public void delete(String resourceType, String physicalId, String region) { + if (emrService.listSecurityConfigurations(region).stream().anyMatch(sc -> physicalId.equals(sc.getName()))) { + emrService.deleteSecurityConfiguration(physicalId, region); + } + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java new file mode 100644 index 0000000000..8f4d563a05 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java @@ -0,0 +1,394 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.emr.EmrStudioService; +import io.floci.aws.services.emr.EmrStudioService.Identity; +import io.floci.aws.services.emr.model.EmrStudio; +import io.floci.aws.services.emr.model.EmrStudioSessionMapping; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; + +/** + * CloudFormation provisioning for {@code AWS::EMR::Studio} and {@code AWS::EMR::StudioSessionMapping}, through the + * service the EMR Studio API itself uses. + * + *

A Studio's {@code Ref} is its id; {@code Fn::GetAtt} gives {@code StudioId}, {@code Arn} and {@code Url}. The + * properties the registry marks create-only replace the Studio when they change. Of the others, UpdateStudio applies + * {@code Name}, {@code Description}, {@code SubnetIds} and {@code DefaultS3Location} when the template changes them; + * UpdateStudio has no member for {@code IdpAuthUrl} or {@code IdpRelayStateParameterName}, so a change to either is + * accepted with a warning and not applied, and a dropped setting is left as it is. Only the tag keys the stack set are + * its to change or drop, so a tag added outside the stack stays. A rollback puts back the name, description, default + * location and tags the update changed; subnets it added stay, as UpdateStudio cannot take a Studio's subnets away. + * + *

A session mapping's physical id, and so its {@code Ref}, is its primary identifier, {@code StudioId}, + * {@code IdentityType} and {@code IdentityName} joined by {@code |}; those three are create-only, and an update changes + * its {@code SessionPolicyArn} in place. + * + *

No AWS handler for these types is public, so each follows its schema and the API it calls. A template that sets + * a Studio's read-only {@code Arn}, {@code StudioId} or {@code Url}, which the schema guide says a user cannot set, is + * refused in the wording AWS's handler for EMR on EKS's virtual cluster gives its {@code Arn}. + */ +@ApplicationScoped +public class EmrStudioCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(EmrStudioCfnProvisioner.class); + private static final String STUDIO = "AWS::EMR::Studio"; + private static final String MAPPING = "AWS::EMR::StudioSessionMapping"; + /** What an in-place Studio update is about to change, for {@link #rollbackUpdate} to put back. */ + static final String STUDIO_SNAPSHOT_ATTR = "__FlociEmrStudioUpdateSnapshot"; + /** The session policy an in-place mapping update is about to change. */ + static final String MAPPING_SNAPSHOT_ATTR = "__FlociEmrStudioSessionMappingUpdateSnapshot"; + /** The tag keys the template that provisioned the Studio set: the next update drops the ones it omits. */ + static final String TAG_KEYS_ATTR = "__FlociEmrStudioTagKeys"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final List READ_ONLY = List.of("Arn", "StudioId", "Url"); + /** The settings no Studio API changes, accepted with a warning when an update changes them. */ + private static final List NOT_UPDATED = List.of("IdpAuthUrl", "IdpRelayStateParameterName"); + private static final String SEPARATOR = "|"; + + private final EmrStudioService studios; + + @Inject + public EmrStudioCfnProvisioner(EmrStudioService studios) { + this.studios = studios; + } + + @Override + public Set resourceTypes() { + return Set.of(STUDIO, MAPPING); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(STUDIO_SNAPSHOT_ATTR); + resource.getAttributes().remove(MAPPING_SNAPSHOT_ATTR); + return ReplacementCleanup.complete(resource, this::delete); + } + + /** + * An in-place update whose own undo failed leaves its snapshot on the attempted resource, which the engine discards + * for the previous one: carried over, it lets ContinueUpdateRollback try the restore again. + */ + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + CfnRollback.carryFailedUndoSnapshot(previous, attempted, STUDIO_SNAPSHOT_ATTR, MAPPING_SNAPSHOT_ATTR); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(STUDIO_SNAPSHOT_ATTR); + resource.getAttributes().remove(MAPPING_SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement or a stub migration is undone through the cleanup record, and an in-place update from the snapshot + * taken before it, which is spent only once the restore succeeded. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + JsonNode studio = CfnRollback.updateSnapshot(resource, STUDIO_SNAPSHOT_ATTR); + if (studio != null) { + restoreStudio(studio, true, true); + Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, studio); + resource.getAttributes().remove(STUDIO_SNAPSHOT_ATTR); + return true; + } + JsonNode mapping = CfnRollback.updateSnapshot(resource, MAPPING_SNAPSHOT_ATTR); + if (mapping != null) { + restorePolicy(mapping); + resource.getAttributes().remove(MAPPING_SNAPSHOT_ATTR); + return true; + } + return false; + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(STUDIO_SNAPSHOT_ATTR); + r.getAttributes().remove(MAPPING_SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + // A stack from before these types had a provisioner holds the dispatcher's stub, which names nothing. + boolean stub = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore); + switch (r.getResourceType()) { + case STUDIO -> provisionStudio(r, props, ctx, stub); + case MAPPING -> provisionMapping(r, props, ctx, stub); + default -> throw new IllegalStateException("EmrStudioCfnProvisioner cannot provision " + + r.getResourceType()); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + private void provisionStudio(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { + JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(STUDIO, props); + for (String readOnly : READ_ONLY) { + if (template.has(readOnly)) { + throw new AwsException("InvalidRequest", + readOnly + " is a ReadOnly property which cannot be specified in the template", 400); + } + } + Map tags = new LinkedHashMap<>(); + template.path("Tags").forEach(tag -> tags.put(tag.path("Key").asText(), tag.path("Value").asText())); + PropertyChanges changes = ctx.isUpdate() && !stub ? ctx.changes(STUDIO, props) : null; + if (changes != null && !changes.requiresReplacement()) { + updateStudioInPlace(r, ctx, template, changes, tags); + return; + } + EmrStudio requested = new EmrStudio(); + requested.setName(text(template, "Name")); + requested.setDescription(text(template, "Description")); + requested.setAuthMode(text(template, "AuthMode")); + requested.setVpcId(text(template, "VpcId")); + requested.setSubnetIds(strings(template.get("SubnetIds"))); + requested.setServiceRole(text(template, "ServiceRole")); + requested.setUserRole(text(template, "UserRole")); + requested.setWorkspaceSecurityGroupId(text(template, "WorkspaceSecurityGroupId")); + requested.setEngineSecurityGroupId(text(template, "EngineSecurityGroupId")); + requested.setDefaultS3Location(text(template, "DefaultS3Location")); + requested.setIdpAuthUrl(text(template, "IdpAuthUrl")); + requested.setIdpRelayStateParameterName(text(template, "IdpRelayStateParameterName")); + requested.setIdcInstanceArn(text(template, "IdcInstanceArn")); + requested.setIdcUserAssignment(text(template, "IdcUserAssignment")); + requested.setEncryptionKeyArn(text(template, "EncryptionKeyArn")); + JsonNode propagation = template.get("TrustedIdentityPropagationEnabled"); + requested.setTrustedIdentityPropagationEnabled(propagation == null ? null : propagation.booleanValue()); + requested.setTags(tags); + EmrStudio created = studios.createStudio(requested); + publishStudio(r, created); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, tags); + } + + /** + * The update of a Studio the prior physical id names, which fails when it is gone. What it is about to change is + * snapshotted first, so a later resource's failure puts it back, and a failure here puts back what it had changed + * before it propagates. + */ + private void updateStudioInPlace(StackResource r, ProvisionContext ctx, JsonNode template, + PropertyChanges changes, Map tags) { + String id = ctx.priorPhysicalId(); + EmrStudio live = liveStudio(id); + for (String name : NOT_UPDATED) { + if (changed(changes, name)) { + LOG.warnv("EMR Studio {0}: no Studio API changes {1}, so the change is not applied", id, name); + } + } + String name = changed(changes, "Name") ? text(template, "Name") : null; + String description = changed(changes, "Description") ? text(template, "Description") : null; + List subnetIds = changed(changes, "SubnetIds") ? strings(template.get("SubnetIds")) : null; + String location = changed(changes, "DefaultS3Location") ? text(template, "DefaultS3Location") : null; + boolean settings = name != null || description != null || subnetIds != null || location != null; + + Set owned = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("studioId", id); + if (name != null) { + snapshot.put("name", live.getName()); + } + if (description != null) { + // UpdateStudio leaves a null description as it is, so one the Studio did not have is put back empty. + snapshot.put("description", live.getDescription() == null ? "" : live.getDescription()); + } + if (location != null) { + snapshot.put("defaultS3Location", live.getDefaultS3Location()); + } + Map current = live.getTags() == null ? Map.of() : live.getTags(); + Ec2Tags.snapshotOwned(snapshot, owned, tags, current, r.getAttributes().get(TAG_KEYS_ATTR)); + publishStudio(r, live); + r.getAttributes().put(STUDIO_SNAPSHOT_ATTR, snapshot.toString()); + AtomicBoolean settingsChanged = new AtomicBoolean(); + AtomicBoolean tagsTouched = new AtomicBoolean(); + CfnRollback.guarded(r, ctx, false, () -> { }, + () -> restoreStudio(snapshot, settingsChanged.get(), tagsTouched.get()), () -> { + if (settings) { + studios.updateStudio(id, name, description, subnetIds, location, null); + settingsChanged.set(true); + } + tagsTouched.set(true); + reconcileTags(id, Ec2Tags.touched(owned, tags), tags); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, tags); + }); + } + + private void restoreStudio(JsonNode snapshot, boolean settingsChanged, boolean tagsTouched) { + String id = snapshot.path("studioId").asText(); + if (settingsChanged) { + String name = CfnRollback.snapshotText(snapshot, "name"); + String description = CfnRollback.snapshotText(snapshot, "description"); + String location = CfnRollback.snapshotText(snapshot, "defaultS3Location"); + if (name != null || description != null || location != null) { + studios.updateStudio(id, name, description, null, location, null); + } + } + if (tagsTouched) { + List touched = new ArrayList<>(); + snapshot.path("touched").forEach(key -> touched.add(key.asText())); + reconcileTags(id, touched, CfnRollback.snapshotTags(snapshot)); + } + } + + private void reconcileTags(String studioId, Collection managedKeys, Map desired) { + CfnRollback.reconcileTags(managedKeys, desired, dropped -> studios.removeTags(studioId, dropped), + added -> studios.addTags(studioId, added)); + } + + private EmrStudio liveStudio(String id) { + return orNotFound(STUDIO, id, () -> studios.describeStudio(id)); + } + + /** + * What {@code lookup} reads, failing as an update of a gone resource fails when the Studio or mapping does not + * exist, which the Studio service answers with InvalidRequestException. + */ + private static T orNotFound(String type, String id, Supplier lookup) { + try { + return lookup.get(); + } catch (AwsException e) { + if ("InvalidRequestException".equals(e.getErrorCode())) { + throw notFound(type, id); + } + throw e; + } + } + + private static void publishStudio(StackResource r, EmrStudio studio) { + r.setPhysicalId(studio.getStudioId()); + r.getAttributes().put("StudioId", studio.getStudioId()); + r.getAttributes().put("Arn", studio.getStudioArn()); + r.getAttributes().put("Url", studio.getUrl()); + } + + private void provisionMapping(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { + JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(MAPPING, props); + String studioId = text(template, "StudioId"); + String type = text(template, "IdentityType"); + String identityName = text(template, "IdentityName"); + String policy = text(template, "SessionPolicyArn"); + PropertyChanges changes = ctx.isUpdate() && !stub ? ctx.changes(MAPPING, props) : null; + if (changes != null && !changes.requiresReplacement()) { + String id = ctx.priorPhysicalId(); + Identity identity = identity(id); + EmrStudioSessionMapping live = liveMapping(id, identity); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("id", id); + snapshot.put("sessionPolicyArn", live.getSessionPolicyArn()); + r.setPhysicalId(id); + r.getAttributes().put(MAPPING_SNAPSHOT_ATTR, snapshot.toString()); + AtomicBoolean policyChanged = new AtomicBoolean(); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> { + if (policyChanged.get()) { + restorePolicy(snapshot); + } + }, () -> { + if (!policy.equals(live.getSessionPolicyArn())) { + studios.updateSessionMapping(studioOf(id), identity, policy); + policyChanged.set(true); + } + }); + return; + } + studios.createSessionMapping(studioId, new Identity(type, null, identityName), policy); + r.setPhysicalId(studioId + SEPARATOR + type + SEPARATOR + identityName); + } + + private void restorePolicy(JsonNode snapshot) { + String id = snapshot.path("id").asText(); + studios.updateSessionMapping(studioOf(id), identity(id), snapshot.path("sessionPolicyArn").asText()); + } + + private EmrStudioSessionMapping liveMapping(String id, Identity identity) { + return orNotFound(MAPPING, id, () -> studios.getSessionMapping(studioOf(id), identity)); + } + + /** The Studio of a mapping's physical id, {@code StudioId|IdentityType|IdentityName}. */ + private static String studioOf(String physicalId) { + return physicalId.split("\\|", 3)[0]; + } + + /** The identity of a mapping's physical id, named by its type and name. */ + private static Identity identity(String physicalId) { + String[] parts = physicalId.split("\\|", 3); + return new Identity(parts[1], null, parts[2]); + } + + private static AwsException notFound(String type, String id) { + return new AwsException("NotFound", "Resource of type '" + type + "' with identifier '" + id + + "' was not found.", 404); + } + + private static boolean changed(PropertyChanges changes, String name) { + PropertyChanges.Kind kind = changes.kindOf(name); + return kind == PropertyChanges.Kind.ADDED || kind == PropertyChanges.Kind.CHANGED; + } + + private static String text(JsonNode template, String name) { + return template.path(name).textValue(); + } + + private static List strings(JsonNode list) { + if (list == null) { + return null; + } + List values = new ArrayList<>(); + list.forEach(value -> values.add(value.asText())); + return values; + } + + /** + * Deletes the Studio, its session mappings with it, or the one session mapping, unless it is gone: a Studio the + * Region does not hold, or a mapping its Studio does not list. + */ + @Override + public void delete(String resourceType, String physicalId, String region) { + switch (resourceType) { + case STUDIO -> { + if (studios.studioArn(physicalId, region).isPresent()) { + studios.deleteStudio(physicalId); + } + } + case MAPPING -> { + String studioId = studioOf(physicalId); + Identity identity = identity(physicalId); + boolean mapped = studios.studioArn(studioId, region).isPresent() + && studios.describeStudio(studioId).getSessionMappings().stream() + .anyMatch(mapping -> identity.type().equals(mapping.getIdentityType()) + && identity.name().equals(mapping.getIdentityName())); + if (mapped) { + studios.deleteSessionMapping(studioId, identity); + } + } + default -> throw new IllegalStateException("EmrStudioCfnProvisioner cannot delete " + resourceType); + } + } +} 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 c7aeff7eb2..32559a8492 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -1300,6 +1300,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return parameters.toString(); } + private static boolean isJsonObject(String json) { + try { + return SNAPSHOT_MAPPER.readTree(json).isObject(); + } catch (JsonProcessingException notJson) { + return false; + } + } + private static JsonNode rawJson(String json) { if (json == null) { return null; @@ -1781,6 +1789,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (name == null || name.isBlank()) { throw new AwsException("InvalidRequestException", "Name is required.", 400); } + if (json != null && !isJsonObject(json)) { + // A configuration that is no JSON object could not be read when a cluster names it; no source gives AWS's + // refusal, so the wording is Floci's. + throw new AwsException("InvalidRequestException", "SecurityConfiguration must be a JSON object.", 400); + } String key = securityConfigurationKey(region, name); if (secConfigStore.get(key).isPresent()) { throw new AwsException("InvalidRequestException", diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json index ad028c1a3b..8bb9d40bb4 100644 --- a/src/main/resources/aws/cfn-property-types.json +++ b/src/main/resources/aws/cfn-property-types.json @@ -12,6 +12,9 @@ "AWS::EC2::LaunchTemplate": "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition": "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster": "AWS::EKS::Cluster", + "AWS::EMR::SecurityConfiguration": "AWS::EMR::SecurityConfiguration", + "AWS::EMR::Studio": "AWS::EMR::Studio", + "AWS::EMR::StudioSessionMapping": "AWS::EMR::StudioSessionMapping", "AWS::EMRContainers::VirtualCluster": "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application": "AWS::EMRServerless::Application", "AWS::Events::Connection": "AWS::Events::Connection", @@ -1952,6 +1955,172 @@ "Enabled": "Boolean" } }, + "AWS::EMR::SecurityConfiguration": { + "type": "structure", + "members": { + "Name": "String", + "SecurityConfiguration": "Json" + }, + "required": [ + "SecurityConfiguration" + ] + }, + "AWS::EMR::Studio": { + "type": "structure", + "members": { + "Arn": "AWS::EMR::Studio/Arn", + "AuthMode": "String", + "DefaultS3Location": "AWS::EMR::Studio.DefaultS3Location", + "Description": "AWS::EMR::Studio.Description", + "EngineSecurityGroupId": "AWS::EMR::Studio.EngineSecurityGroupId", + "Name": "AWS::EMR::Studio.Name", + "ServiceRole": "AWS::EMR::Studio/Arn", + "StudioId": "AWS::EMR::Studio.StudioId", + "SubnetIds": "AWS::EMR::Studio.SubnetIds", + "Tags": "AWS::EMR::Studio/Tags", + "Url": "AWS::EMR::Studio.Url", + "UserRole": "AWS::EMR::Studio/Arn", + "VpcId": "AWS::EMR::Studio.VpcId", + "WorkspaceSecurityGroupId": "AWS::EMR::Studio.WorkspaceSecurityGroupId", + "IdpAuthUrl": "AWS::EMR::Studio.IdpAuthUrl", + "IdpRelayStateParameterName": "AWS::EMR::Studio.IdpRelayStateParameterName", + "TrustedIdentityPropagationEnabled": "Boolean", + "IdcUserAssignment": "String", + "IdcInstanceArn": "AWS::EMR::Studio.IdcInstanceArn", + "EncryptionKeyArn": "AWS::EMR::Studio/Arn" + }, + "required": [ + "AuthMode", + "EngineSecurityGroupId", + "Name", + "ServiceRole", + "SubnetIds", + "VpcId", + "WorkspaceSecurityGroupId", + "DefaultS3Location" + ] + }, + "AWS::EMR::Studio.DefaultS3Location": { + "type": "string", + "minLength": 6, + "maxLength": 10280, + "pattern": "^s3://.*" + }, + "AWS::EMR::Studio.Description": { + "type": "string", + "minLength": 0, + "maxLength": 256 + }, + "AWS::EMR::Studio.EngineSecurityGroupId": { + "type": "string", + "minLength": 4, + "maxLength": 256, + "pattern": "^sg-[a-zA-Z0-9\\-._]+$" + }, + "AWS::EMR::Studio.IdcInstanceArn": { + "type": "string", + "minLength": 20, + "maxLength": 2048 + }, + "AWS::EMR::Studio.IdpAuthUrl": { + "type": "string", + "maxLength": 4096, + "pattern": "^https://[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])(:[0-9]*)*([?/#].*)?$" + }, + "AWS::EMR::Studio.IdpRelayStateParameterName": { + "type": "string", + "minLength": 0, + "maxLength": 256 + }, + "AWS::EMR::Studio.Name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "[a-zA-Z0-9_-]+" + }, + "AWS::EMR::Studio.StudioId": { + "type": "string", + "minLength": 4, + "maxLength": 256, + "pattern": "^es-[0-9A-Z]+" + }, + "AWS::EMR::Studio.SubnetIds": { + "type": "list", + "member": "AWS::EMR::Studio/SubnetId" + }, + "AWS::EMR::Studio.Url": { + "type": "string", + "maxLength": 4096, + "pattern": "^https://[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])(:[0-9]*)*([?/#].*)?$" + }, + "AWS::EMR::Studio.VpcId": { + "type": "string", + "pattern": "^(vpc-[0-9a-f]{8}|vpc-[0-9a-f]{17})$" + }, + "AWS::EMR::Studio.WorkspaceSecurityGroupId": { + "type": "string", + "pattern": "^sg-[a-zA-Z0-9\\-._]+$" + }, + "AWS::EMR::Studio/Arn": { + "type": "string", + "pattern": "^arn:aws(-(cn|us-gov|iso-f|iso-e))?:[a-z-]+:(([a-z]+-)+[0-9])?:([0-9]{12})?:[^.]+$" + }, + "AWS::EMR::Studio/SubnetId": { + "type": "string", + "pattern": "^(subnet-[a-f0-9]{13})|(subnet-[a-f0-9]{8})\\Z" + }, + "AWS::EMR::Studio/Tag": { + "type": "structure", + "members": { + "Key": "AWS::EMR::Studio/Tag.Key", + "Value": "AWS::EMR::Studio/Tag.Value" + }, + "required": [ + "Value", + "Key" + ] + }, + "AWS::EMR::Studio/Tag.Key": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^(?!aws:)[a-zA-Z+-=._:/]+$" + }, + "AWS::EMR::Studio/Tag.Value": { + "type": "string", + "minLength": 0, + "maxLength": 256, + "pattern": "[a-zA-Z+-=._:/]+$" + }, + "AWS::EMR::Studio/Tags": { + "type": "list", + "member": "AWS::EMR::Studio/Tag" + }, + "AWS::EMR::StudioSessionMapping": { + "type": "structure", + "members": { + "IdentityName": "String", + "IdentityType": "String", + "SessionPolicyArn": "AWS::EMR::StudioSessionMapping/IamPolicyArn", + "StudioId": "AWS::EMR::StudioSessionMapping.StudioId" + }, + "required": [ + "StudioId", + "IdentityName", + "IdentityType", + "SessionPolicyArn" + ] + }, + "AWS::EMR::StudioSessionMapping.StudioId": { + "type": "string", + "minLength": 4, + "maxLength": 256, + "pattern": "^es-[0-9A-Z]+" + }, + "AWS::EMR::StudioSessionMapping/IamPolicyArn": { + "type": "string", + "pattern": "^arn:aws(-(cn|us-gov|iso-f|iso-e))?:iam::([0-9]{12})?:policy\\/[^.]+$" + }, "AWS::EMRContainers::VirtualCluster": { "type": "structure", "members": { diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index 29b60b3e5f..08d32b98a2 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -528,6 +528,27 @@ "AmiType", "Subnets" ], + "AWS::EMR::SecurityConfiguration": [ + "Name", + "SecurityConfiguration" + ], + "AWS::EMR::Studio": [ + "AuthMode", + "EngineSecurityGroupId", + "ServiceRole", + "UserRole", + "VpcId", + "WorkspaceSecurityGroupId", + "TrustedIdentityPropagationEnabled", + "IdcUserAssignment", + "IdcInstanceArn", + "EncryptionKeyArn" + ], + "AWS::EMR::StudioSessionMapping": [ + "StudioId", + "IdentityType", + "IdentityName" + ], "AWS::EMRContainers::VirtualCluster": [ "ContainerProvider", "Name", diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index 7766c1af8f..df5b8e4779 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -76,8 +76,10 @@ import io.floci.aws.services.cloudformation.provisioners.EksCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElastiCacheCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElastiCacheServerlessCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElbV2CfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.EmrCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EmrContainersCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EmrServerlessCfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.EmrStudioCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsArchiveCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsV2CfnProvisioner; @@ -155,6 +157,8 @@ import io.floci.aws.services.elasticache.ElastiCacheMemcachedService; import io.floci.aws.services.elasticache.ElastiCacheServerlessService; import io.floci.aws.services.elasticache.ElastiCacheService; import io.floci.aws.services.elbv2.ElbV2Service; +import io.floci.aws.services.emr.EmrService; +import io.floci.aws.services.emr.EmrStudioService; import io.floci.aws.services.emrcontainers.EmrContainersService; import io.floci.aws.services.emrserverless.EmrServerlessJobRunService; import io.floci.aws.services.emrserverless.EmrServerlessService; @@ -282,6 +286,8 @@ final class CfnProvisionerFixture { private CloudTrailService cloudTrailService; private SchedulerService schedulerService; private CodeDeployService codeDeployService; + private EmrService emrService; + private EmrStudioService emrStudioService; private EmrContainersService emrContainersService; private EmrServerlessService emrServerlessService; private EmrServerlessJobRunService emrServerlessJobRunService; @@ -571,6 +577,12 @@ final class CfnProvisionerFixture { if (codeDeployService != null) { discovered.add(new CodeDeployCfnProvisioner(codeDeployService)); } + if (emrService != null) { + discovered.add(new EmrCfnProvisioner(emrService)); + } + if (emrStudioService != null) { + discovered.add(new EmrStudioCfnProvisioner(emrStudioService)); + } if (emrContainersService != null) { discovered.add(new EmrContainersCfnProvisioner(emrContainersService)); } @@ -807,6 +819,16 @@ final class CfnProvisionerFixture { return this; } + public Builder emr(EmrService v) { + this.emrService = v; + return this; + } + + public Builder emrStudio(EmrStudioService v) { + this.emrStudioService = v; + return this; + } + public Builder emrContainers(EmrContainersService v) { this.emrContainersService = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/EmrStudioCfnIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/EmrStudioCfnIntegrationTest.java new file mode 100644 index 0000000000..05aeb0cbfb --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/EmrStudioCfnIntegrationTest.java @@ -0,0 +1,183 @@ +package io.floci.aws.services.cloudformation; + +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.CfnStackWaits; +import io.floci.aws.testing.CfnTestStack; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.services.cloudformation.model.Stack; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.testing.CfnStackWaits.output; +import static io.floci.aws.testing.EmrRequests.emr; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Provisions {@code AWS::EMR::SecurityConfiguration}, {@code AWS::EMR::Studio} and + * {@code AWS::EMR::StudioSessionMapping} through a stack and reads them back through EMR: each {@code Ref} and the + * Studio's {@code Fn::GetAtt} attributes name them, an update renames the Studio, retags it and gives the mapping a + * new session policy in place, a later resource's failure puts all three back, and deleting the stack deletes them. + */ +@QuarkusTest +class EmrStudioCfnIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String POLICY = "arn:aws:iam::000000000000:policy/EMRStudio_Basic_User_Policy"; + + @RegisterExtension + final CfnTestStack stack = new CfnTestStack("emr-studio-cfn-it"); + + @Inject + Ec2Service ec2; + + @Inject + SsoAdminService ssoAdmin; + + @Inject + IdentityStoreService identityStore; + + @Inject + ObjectMapper objectMapper; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createUpdateRollBackAndDeleteASecurityConfigurationStudioAndSessionMapping() throws Exception { + String vpcId = ec2.describeVpcs(REGION, List.of(), Map.of("is-default", List.of("true"))).get(0).getVpcId(); + List subnetIds = ec2.describeSubnets(REGION, List.of(), Map.of("vpc-id", List.of(vpcId))).stream() + .map(Subnet::getSubnetId).limit(2).toList(); + String securityGroupId = ec2.describeSecurityGroups(REGION, List.of(), List.of(), + Map.of("vpc-id", List.of(vpcId))).get(0).getGroupId(); + String storeId = ssoAdmin.listInstances(ACCOUNT).get(0).identityStoreId(); + String userName = "cfn-" + UUID.randomUUID(); + String userId = identityStore.createUser(objectMapper.readTree(""" + {"IdentityStoreId": "%s", "UserName": "%s", "DisplayName": "Ana"} + """.formatted(storeId, userName))).userId(); + try { + stackLifecycle(vpcId, subnetIds, securityGroupId, userName); + } finally { + identityStore.deleteUser(objectMapper.readTree(""" + {"IdentityStoreId": "%s", "UserId": "%s"} + """.formatted(storeId, userId))); + } + } + + private void stackLifecycle(String vpcId, List subnetIds, String securityGroupId, String userName) { + String securityName = stack.name() + "-security"; + Template template = new Template(securityName, vpcId, subnetIds, securityGroupId, userName); + + Stack created = stack.create(template.render("notebooks", "v1", POLICY, false)); + String studioId = output(created, "StudioRef"); + assertEquals(studioId, output(created, "StudioId")); + assertEquals("arn:aws:elasticmapreduce:us-east-1:000000000000:studio/" + studioId, + output(created, "StudioArn")); + assertEquals(studioId + "|USER|" + userName, output(created, "MappingRef")); + assertEquals(securityName, output(created, "SecurityRef")); + describeStudio(studioId) + .body("Studio.Name", equalTo("notebooks")) + .body("Studio.AuthMode", equalTo("SSO")) + .body("Studio.Url", equalTo(output(created, "StudioUrl"))) + .body("Studio.Tags[0].Value", equalTo("v1")); + mapping(studioId, userName).body("SessionMapping.SessionPolicyArn", equalTo(POLICY)); + emr("DescribeSecurityConfiguration", "{\"Name\": \"" + securityName + "\"}").then().statusCode(200) + .body("Name", equalTo(securityName)); + + Stack updated = stack.update(template.render("renamed", "v2", POLICY + "_V2", false), "UPDATE_COMPLETE"); + assertEquals(studioId, output(updated, "StudioRef")); + describeStudio(studioId).body("Studio.Name", equalTo("renamed")).body("Studio.Tags[0].Value", equalTo("v2")); + mapping(studioId, userName).body("SessionMapping.SessionPolicyArn", equalTo(POLICY + "_V2")); + + stack.update(template.render("again", "v3", POLICY, true), "UPDATE_ROLLBACK_COMPLETE"); + describeStudio(studioId).body("Studio.Name", equalTo("renamed")).body("Studio.Tags[0].Value", equalTo("v2")); + mapping(studioId, userName).body("SessionMapping.SessionPolicyArn", equalTo(POLICY + "_V2")); + + CfnStackWaits.deleteStack(stack.name()); + + emr("DescribeStudio", "{\"StudioId\": \"" + studioId + "\"}").then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + emr("DescribeSecurityConfiguration", "{\"Name\": \"" + securityName + "\"}").then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + } + + private static ValidatableResponse describeStudio(String studioId) { + return emr("DescribeStudio", "{\"StudioId\": \"" + studioId + "\"}").then().statusCode(200); + } + + private static ValidatableResponse mapping(String studioId, String userName) { + return emr("GetStudioSessionMapping", """ + {"StudioId": "%s", "IdentityType": "USER", "IdentityName": "%s"} + """.formatted(studioId, userName)).then().statusCode(200); + } + + private record Template(String securityName, String vpcId, List subnetIds, String securityGroupId, + String userName) { + + String render(String studioName, String stage, String policy, boolean laterFails) { + return """ + { + "Resources": { + "Security": { + "Type": "AWS::EMR::SecurityConfiguration", + "Properties": { + "Name": "%s", + "SecurityConfiguration": {"EncryptionConfiguration": { + "EnableInTransitEncryption": false, "EnableAtRestEncryption": false}} + } + }, + "Studio": { + "Type": "AWS::EMR::Studio", + "Properties": { + "Name": "%s", + "AuthMode": "SSO", + "VpcId": "%s", + "SubnetIds": ["%s", "%s"], + "ServiceRole": "arn:aws:iam::000000000000:role/EMRStudio_Service_Role", + "UserRole": "arn:aws:iam::000000000000:role/EMRStudio_User_Role", + "WorkspaceSecurityGroupId": "%s", + "EngineSecurityGroupId": "%s", + "DefaultS3Location": "s3://studio-bucket/workspaces", + "Tags": [{"Key": "stage", "Value": "%s"}] + } + }, + "Mapping": { + "Type": "AWS::EMR::StudioSessionMapping", + "Properties": { + "StudioId": {"Ref": "Studio"}, + "IdentityType": "USER", + "IdentityName": "%s", + "SessionPolicyArn": "%s" + } + }%s + }, + "Outputs": { + "SecurityRef": {"Value": {"Ref": "Security"}}, + "StudioRef": {"Value": {"Ref": "Studio"}}, + "StudioId": {"Value": {"Fn::GetAtt": ["Studio", "StudioId"]}}, + "StudioArn": {"Value": {"Fn::GetAtt": ["Studio", "Arn"]}}, + "StudioUrl": {"Value": {"Fn::GetAtt": ["Studio", "Url"]}}, + "MappingRef": {"Value": {"Ref": "Mapping"}} + } + } + """.formatted(securityName, studioName, vpcId, subnetIds.get(0), subnetIds.get(1), securityGroupId, + securityGroupId, stage, userName, policy, + laterFails ? CfnStackWaits.failingResourceAfter("Mapping") : ""); + } + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypesTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypesTest.java index 7f1f3eeb0f..2c9821f953 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypesTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypesTest.java @@ -407,6 +407,27 @@ class CfnPropertyTypesTest { .read("AWS::SES::ConfigurationSetEventDestination", properties)); } + /** + * A schema pattern is searched for, as the validator CloudFormation runs does, not matched whole: the Studio + * schema's Name pattern {@code [a-zA-Z0-9_-]+} takes a name with spaces, and refuses one with none of its + * characters. + */ + @Test + void handlerReaderLooksForAPatternInTheValue() { + String studio = """ + {"Name": "%s", "AuthMode": "IAM", "VpcId": "vpc-0123456789abcdef0", "SubnetIds": ["subnet-1"], + "ServiceRole": "arn:aws:iam::000000000000:role/EMRStudio", "WorkspaceSecurityGroupId": "sg-1", + "EngineSecurityGroupId": "sg-2", "DefaultS3Location": "s3://bucket/studio"} + """; + JsonNode spaced = json(studio.formatted("notebooks for etl")); + + assertEquals(spaced, new CfnPropertyTypes.HandlerReader(engine()).read("AWS::EMR::Studio", spaced)); + AwsException failure = assertThrows(AwsException.class, () -> new CfnPropertyTypes.HandlerReader(engine()) + .read("AWS::EMR::Studio", json(studio.formatted("!!!")))); + assertEquals("Model validation failed (#/Name: failed validation constraint for keyword [pattern])", + failure.getMessage()); + } + @ParameterizedTest(name = "{0}") @MethodSource("unknownSesMembers") void handlerReaderRejectsExtraneousMembers(String caseName, String properties, String violation) { diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java new file mode 100644 index 0000000000..7ca2a825b8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java @@ -0,0 +1,123 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.emr.EmrService; +import io.floci.aws.services.emr.model.SecurityConfiguration; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.List; + +import static io.floci.aws.services.cloudformation.provisioners.ProvisionContexts.json; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** {@code AWS::EMR::SecurityConfiguration} in isolation, with {@link EmrService} mocked. */ +class EmrCfnProvisionerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ENCRYPTION = """ + {"EncryptionConfiguration": {"EnableInTransitEncryption": false, "EnableAtRestEncryption": false}}"""; + + private final EmrService emr = mock(EmrService.class); + private final EmrCfnProvisioner provisioner = new EmrCfnProvisioner(emr); + + private static ProvisionContext ctx(String priorPhysicalId, String priorProperties) { + return ProvisionContexts.standalone(priorPhysicalId, priorProperties == null ? null : json(priorProperties)); + } + + private static StackResource resource(String physicalId) { + StackResource r = new StackResource(); + r.setLogicalId("Security"); + r.setResourceType("AWS::EMR::SecurityConfiguration"); + r.setPhysicalId(physicalId); + r.setAttributes(new HashMap<>()); + return r; + } + + + private static String props(String name, String configuration) { + return "{" + (name == null ? "" : "\"Name\": \"" + name + "\", ") + "\"SecurityConfiguration\": " + + configuration + "}"; + } + + @Test + void createsTheSecurityConfigurationFromAnObjectOrItsText() { + StackResource fromObject = resource(null); + StackResource fromText = resource(null); + + provisioner.provision(fromObject, json(props("tls", ENCRYPTION)), ctx(null, null)); + provisioner.provision(fromText, json(props("text", MAPPER.valueToTree(ENCRYPTION).toString())), + ctx(null, null)); + + verify(emr).createSecurityConfiguration("tls", json(ENCRYPTION).toString(), "us-east-1"); + verify(emr).createSecurityConfiguration("text", ENCRYPTION, "us-east-1"); + assertEquals("tls", fromObject.getPhysicalId()); + assertEquals("text", fromText.getPhysicalId()); + } + + @Test + void anUnnamedSecurityConfigurationGetsAGeneratedName() { + StackResource r = resource(null); + + provisioner.provision(r, json(props(null, ENCRYPTION)), ctx(null, null)); + + ArgumentCaptor name = ArgumentCaptor.forClass(String.class); + verify(emr).createSecurityConfiguration(name.capture(), anyString(), eq("us-east-1")); + assertTrue(name.getValue().startsWith("my-stack-Security-"), name.getValue()); + assertEquals(name.getValue(), r.getPhysicalId()); + } + + @Test + void anUpdateThatChangesNothingKeepsIt() { + StackResource r = resource("tls"); + + provisioner.provision(r, json(props("tls", ENCRYPTION)), ctx("tls", props("tls", ENCRYPTION))); + + assertEquals("tls", r.getPhysicalId()); + verifyNoInteractions(emr); + } + + @Test + void aChangeReplacesAnUnnamedOneAndIsRefusedForOneThatKeepsItsName() { + String changed = ENCRYPTION.replace("\"EnableAtRestEncryption\": false", "\"EnableAtRestEncryption\": true"); + StackResource unnamed = resource("my-stack-Security-OLD"); + + provisioner.provision(unnamed, json(props(null, changed)), + ctx("my-stack-Security-OLD", props(null, ENCRYPTION))); + AwsException named = assertThrows(AwsException.class, + () -> provisioner.provision(resource("tls"), json(props("tls", changed)), + ctx("tls", props("tls", ENCRYPTION)))); + + assertTrue(unnamed.getPhysicalId().startsWith("my-stack-Security-"), unnamed.getPhysicalId()); + assertEquals("my-stack-Security-OLD", provisioner.updateCleanupPhysicalId(unnamed)); + assertTrue(named.getMessage().startsWith("CloudFormation cannot update a stack when a custom-named resource"), + named.getMessage()); + } + + @Test + void theDeleteTakesASecurityConfigurationTheRegionDoesNotListAsDeleted() { + SecurityConfiguration tls = new SecurityConfiguration(); + tls.setName("tls"); + when(emr.listSecurityConfigurations("us-east-1")).thenReturn(List.of(tls)); + + provisioner.delete("AWS::EMR::SecurityConfiguration", "tls", "us-east-1"); + provisioner.delete("AWS::EMR::SecurityConfiguration", "gone", "us-east-1"); + + verify(emr).deleteSecurityConfiguration("tls", "us-east-1"); + verify(emr, never()).deleteSecurityConfiguration(eq("gone"), any()); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisionerTest.java new file mode 100644 index 0000000000..9d326e2099 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisionerTest.java @@ -0,0 +1,254 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.emr.EmrStudioService; +import io.floci.aws.services.emr.EmrStudioService.Identity; +import io.floci.aws.services.emr.model.EmrStudio; +import io.floci.aws.services.emr.model.EmrStudioSessionMapping; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static io.floci.aws.services.cloudformation.provisioners.ProvisionContexts.json; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** {@code AWS::EMR::Studio} and {@code AWS::EMR::StudioSessionMapping} in isolation, with the Studio service mocked. */ +class EmrStudioCfnProvisionerTest { + + private static final String STUDIO_ID = "es-0123456789ABCDEFGHIJKLMNO"; + private static final String STUDIO_ARN = "arn:aws:elasticmapreduce:us-east-1:000000000000:studio/" + STUDIO_ID; + private static final String POLICY = "arn:aws:iam::000000000000:policy/EMRStudioSession"; + private static final String MAPPING_ID = STUDIO_ID + "|USER|ana"; + + private final EmrStudioService studios = mock(EmrStudioService.class); + private final EmrStudioCfnProvisioner provisioner = new EmrStudioCfnProvisioner(studios); + + private static ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) { + return ProvisionContexts.standalone(priorPhysicalId, priorProperties); + } + + private static StackResource resource(String type, String physicalId) { + StackResource r = new StackResource(); + r.setLogicalId(type.endsWith("Studio") ? "Studio" : "Mapping"); + r.setResourceType(type); + r.setPhysicalId(physicalId); + r.setAttributes(new HashMap<>()); + return r; + } + + + /** A Studio template using IAM authentication, named {@code name} and tagged {@code stage}. */ + private static ObjectNode studioProps(String name, String stage) { + return (ObjectNode) json(""" + {"Name": "%s", "AuthMode": "IAM", "VpcId": "vpc-0123456789abcdef0", + "SubnetIds": ["subnet-0123456789abcdef0"], "ServiceRole": "arn:aws:iam::000000000000:role/EMRStudio", + "WorkspaceSecurityGroupId": "sg-0123456789abcdef0", "EngineSecurityGroupId": "sg-0123456789abcdef1", + "DefaultS3Location": "s3://studio-bucket/workspaces", "Tags": [{"Key": "stage", "Value": "%s"}]} + """.formatted(name, stage)); + } + + private static EmrStudio studio(String name, Map tags) { + EmrStudio studio = new EmrStudio(); + studio.setStudioId(STUDIO_ID); + studio.setStudioArn(STUDIO_ARN); + studio.setUrl("http://localhost:4566/_aws/emr/studios/" + STUDIO_ID); + studio.setName(name); + studio.setDefaultS3Location("s3://studio-bucket/workspaces"); + studio.setTags(new LinkedHashMap<>(tags)); + return studio; + } + + /** The Studio as the create that made it left the resource, owning the tag key {@code stage}. */ + private static StackResource provisionedStudio() { + StackResource r = resource("AWS::EMR::Studio", STUDIO_ID); + r.getAttributes().put(EmrStudioCfnProvisioner.TAG_KEYS_ATTR, "[\"stage\"]"); + return r; + } + + @Test + void createsTheStudioAndPublishesItsAttributes() { + when(studios.createStudio(any())).thenReturn(studio("notebooks", Map.of("stage", "v1"))); + StackResource r = resource("AWS::EMR::Studio", null); + + provisioner.provision(r, studioProps("notebooks", "v1"), ctx(null, null)); + + ArgumentCaptor created = ArgumentCaptor.forClass(EmrStudio.class); + verify(studios).createStudio(created.capture()); + EmrStudio request = created.getValue(); + assertEquals("notebooks", request.getName()); + assertEquals("IAM", request.getAuthMode()); + assertEquals(List.of("subnet-0123456789abcdef0"), request.getSubnetIds()); + assertEquals("sg-0123456789abcdef1", request.getEngineSecurityGroupId()); + assertEquals(Map.of("stage", "v1"), request.getTags()); + assertEquals(STUDIO_ID, r.getPhysicalId()); + assertEquals(STUDIO_ID, r.getAttributes().get("StudioId")); + assertEquals(STUDIO_ARN, r.getAttributes().get("Arn")); + assertEquals("http://localhost:4566/_aws/emr/studios/" + STUDIO_ID, r.getAttributes().get("Url")); + } + + @Test + void aTemplateThatSetsAReadOnlyPropertyIsRefusedBeforeAnyCall() { + ObjectNode props = studioProps("notebooks", "v1"); + props.put("Url", "https://example.com"); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource("AWS::EMR::Studio", null), props, ctx(null, null))); + + assertEquals("Url is a ReadOnly property which cannot be specified in the template", e.getMessage()); + verifyNoInteractions(studios); + } + + @Test + void anUpdateRenamesTheStudioAndChangesOnlyTheTagKeysTheStackOwns() { + when(studios.describeStudio(STUDIO_ID)) + .thenReturn(studio("notebooks", Map.of("stage", "v1", "owner", "outside"))); + StackResource r = provisionedStudio(); + ObjectNode props = studioProps("renamed", "v2"); + props.put("IdpAuthUrl", "https://idp.example/login"); + + provisioner.provision(r, props, ctx(STUDIO_ID, studioProps("notebooks", "v1"))); + + verify(studios).updateStudio(STUDIO_ID, "renamed", null, null, null, null); + verify(studios).addTags(STUDIO_ID, Map.of("stage", "v2")); + verify(studios, never()).removeTags(any(), any()); + verify(studios, never()).createStudio(any()); + assertEquals(STUDIO_ID, r.getPhysicalId()); + } + + @Test + void aRollbackPutsBackTheNameAndTheTags() { + when(studios.describeStudio(STUDIO_ID)).thenReturn(studio("notebooks", Map.of("stage", "v1"))); + StackResource r = provisionedStudio(); + provisioner.provision(r, studioProps("renamed", "v2"), ctx(STUDIO_ID, studioProps("notebooks", "v1"))); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(studios).updateStudio(STUDIO_ID, "notebooks", null, null, null, null); + verify(studios).addTags(STUDIO_ID, Map.of("stage", "v1")); + assertFalse(r.getAttributes().containsKey(EmrStudioCfnProvisioner.STUDIO_SNAPSHOT_ATTR)); + } + + @Test + void anUpdateTheStudioRefusesChangedNothingSoNothingIsPutBack() { + when(studios.describeStudio(STUDIO_ID)).thenReturn(studio("notebooks", Map.of("stage", "v1"))); + when(studios.updateStudio(eq(STUDIO_ID), any(), any(), any(), any(), any())) + .thenThrow(new AwsException("InvalidRequestException", "refused", 400)); + StackResource r = provisionedStudio(); + + assertThrows(AwsException.class, () -> provisioner.provision(r, studioProps("renamed", "v2"), + ctx(STUDIO_ID, studioProps("notebooks", "v1")))); + + verify(studios, never()).addTags(any(), any()); + assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + } + + @Test + void anUpdateOfAStudioThatIsGoneFails() { + when(studios.describeStudio(STUDIO_ID)) + .thenThrow(new AwsException("InvalidRequestException", "Studio does not exist.", 400)); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(provisionedStudio(), + studioProps("renamed", "v2"), ctx(STUDIO_ID, studioProps("notebooks", "v1")))); + + assertEquals("Resource of type 'AWS::EMR::Studio' with identifier '" + STUDIO_ID + "' was not found.", + e.getMessage()); + } + + @Test + void aSessionMappingIsCreatedUnderItsPrimaryIdentifier() { + StackResource r = resource("AWS::EMR::StudioSessionMapping", null); + + provisioner.provision(r, mappingProps("ana", POLICY), ctx(null, null)); + + verify(studios).createSessionMapping(STUDIO_ID, new Identity("USER", null, "ana"), POLICY); + assertEquals(MAPPING_ID, r.getPhysicalId()); + } + + @Test + void aNewSessionPolicyUpdatesTheMappingInPlaceAndARollbackPutsTheOldOneBack() { + EmrStudioSessionMapping live = new EmrStudioSessionMapping(); + live.setSessionPolicyArn(POLICY); + when(studios.getSessionMapping(STUDIO_ID, new Identity("USER", null, "ana"))).thenReturn(live); + StackResource r = resource("AWS::EMR::StudioSessionMapping", MAPPING_ID); + String newer = POLICY + "V2"; + + provisioner.provision(r, mappingProps("ana", newer), ctx(MAPPING_ID, mappingProps("ana", POLICY))); + provisioner.rollbackUpdate(r); + + verify(studios).updateSessionMapping(STUDIO_ID, new Identity("USER", null, "ana"), newer); + verify(studios).updateSessionMapping(STUDIO_ID, new Identity("USER", null, "ana"), POLICY); + assertEquals(MAPPING_ID, r.getPhysicalId()); + } + + @Test + void anotherIdentityReplacesTheMapping() { + StackResource r = resource("AWS::EMR::StudioSessionMapping", MAPPING_ID); + + provisioner.provision(r, mappingProps("bea", POLICY), ctx(MAPPING_ID, mappingProps("ana", POLICY))); + + verify(studios).createSessionMapping(STUDIO_ID, new Identity("USER", null, "bea"), POLICY); + assertEquals(STUDIO_ID + "|USER|bea", r.getPhysicalId()); + assertEquals(MAPPING_ID, provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void theDeletesTakeAStudioOrMappingThatIsGoneAsDeleted() { + EmrStudio live = studio("notebooks", Map.of()); + EmrStudioSessionMapping mapping = new EmrStudioSessionMapping(); + mapping.setIdentityType("USER"); + mapping.setIdentityName("ana"); + live.setSessionMappings(List.of(mapping)); + when(studios.studioArn(STUDIO_ID, "us-east-1")).thenReturn(Optional.of(STUDIO_ARN)); + when(studios.studioArn("es-GONE", "us-east-1")).thenReturn(Optional.empty()); + when(studios.describeStudio(STUDIO_ID)).thenReturn(live); + + provisioner.delete("AWS::EMR::Studio", STUDIO_ID, "us-east-1"); + provisioner.delete("AWS::EMR::Studio", "es-GONE", "us-east-1"); + provisioner.delete("AWS::EMR::StudioSessionMapping", MAPPING_ID, "us-east-1"); + provisioner.delete("AWS::EMR::StudioSessionMapping", STUDIO_ID + "|USER|bea", "us-east-1"); + + verify(studios).deleteStudio(STUDIO_ID); + verify(studios, never()).deleteStudio("es-GONE"); + verify(studios).deleteSessionMapping(STUDIO_ID, new Identity("USER", null, "ana")); + verify(studios, never()).deleteSessionMapping(STUDIO_ID, new Identity("USER", null, "bea")); + } + + @Test + void aDescriptionTheUpdateAddedIsPutBackEmpty() { + when(studios.describeStudio(STUDIO_ID)).thenReturn(studio("notebooks", Map.of("stage", "v1"))); + StackResource r = provisionedStudio(); + ObjectNode props = studioProps("notebooks", "v1"); + props.put("Description", "for the ETL team"); + + provisioner.provision(r, props, ctx(STUDIO_ID, studioProps("notebooks", "v1"))); + provisioner.rollbackUpdate(r); + + verify(studios).updateStudio(STUDIO_ID, null, "for the ETL team", null, null, null); + verify(studios).updateStudio(STUDIO_ID, null, "", null, null, null); + } + + private static JsonNode mappingProps(String identityName, String policy) { + return json(""" + {"StudioId": "%s", "IdentityType": "USER", "IdentityName": "%s", "SessionPolicyArn": "%s"} + """.formatted(STUDIO_ID, identityName, policy)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java index 4ad4f66142..051671c11a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java @@ -1,5 +1,6 @@ package io.floci.aws.services.cloudformation.provisioners; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; @@ -41,4 +42,22 @@ public final class ProvisionContexts { return new ProvisionContext(passthroughEngine(), region, accountId, stackName, priorPhysicalId, event -> {}, MAPPER.readTree(priorProperties)); } + + /** + * A context over a real standalone engine in us-east-1 for stack {@code my-stack}: a create when + * {@code priorPhysicalId} is null, otherwise an update from {@code priorProperties}, which may be null. + */ + public static ProvisionContext standalone(String priorPhysicalId, JsonNode priorProperties) { + return new ProvisionContext(CloudFormationTemplateEngine.standalone("000000000000", "us-east-1", "my-stack", + MAPPER, null), "us-east-1", "000000000000", "my-stack", priorPhysicalId, event -> {}, priorProperties); + } + + /** {@code text} parsed as JSON, for template properties written into a test. */ + public static JsonNode json(String text) { + try { + return MAPPER.readTree(text); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException(text, e); + } + } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java index f9136f4889..77b54e1ddd 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrIntegrationTest.java @@ -347,6 +347,14 @@ class EmrIntegrationTest { emr("DeleteSecurityConfiguration", "{\"Name\":\"floci-emr-sec\"}") .then().statusCode(200); } + // A configuration that is no JSON object could not be read when a cluster names it. + for (String notAnObject : List.of("not json", "[]")) { + emr("CreateSecurityConfiguration", objectMapper.createObjectNode().put("Name", "floci-emr-sec-bad") + .put("SecurityConfiguration", notAnObject).toString()) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", equalTo("SecurityConfiguration must be a JSON object.")); + } } @Test diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 8c70a94e72..05036ecb6d 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -108,6 +108,9 @@ AWS::EFS::FileSystem Arn,FileSystemId AvailabilityZoneName,BackupPolicy,BypassPo AWS::EFS::MountTarget Id FileSystemId,IpAddress,IpAddressType,Ipv6Address,SecurityGroups,SubnetId AWS::EKS::Cluster Arn,CertificateAuthorityData,ClusterSecurityGroupId,EncryptionConfigKeyArn,Endpoint,Id,OpenIdConnectIssuerUrl AccessConfig,ActiveCertificateAuthorityId,BootstrapSelfManagedAddons,CertificateAuthority,ComputeConfig,ControlPlaneScalingConfig,DeletionProtection,EncryptionConfig,Force,KubeApiServerConfig,KubeControllerManagerConfig,KubeSchedulerConfig,KubernetesNetworkConfig,Logging,Name,OutpostConfig,RemoteNetworkConfig,ResourcesVpcConfig,RoleArn,RollbackConfig,StorageConfig,Tags,UpgradePolicy,Version,ZonalShiftConfig AWS::EKS::Nodegroup Arn,Id AmiType,CapacityType,ClusterName,DiskSize,ForceUpdateEnabled,InstanceTypes,Labels,LaunchTemplate,NodeRepairConfig,NodeRole,NodegroupName,ReleaseVersion,RemoteAccess,ScalingConfig,Subnets,Tags,Taints,UpdateConfig,Version,WarmPoolConfig +AWS::EMR::SecurityConfiguration Name,SecurityConfiguration +AWS::EMR::Studio Arn,StudioId,Url AuthMode,DefaultS3Location,Description,EncryptionKeyArn,EngineSecurityGroupId,IdcInstanceArn,IdcUserAssignment,IdpAuthUrl,IdpRelayStateParameterName,Name,ServiceRole,SubnetIds,Tags,TrustedIdentityPropagationEnabled,UserRole,VpcId,WorkspaceSecurityGroupId +AWS::EMR::StudioSessionMapping IdentityName,IdentityType,SessionPolicyArn,StudioId AWS::EMRContainers::VirtualCluster Arn,Id ContainerProvider,Name,SecurityConfigurationId,SessionEnabled,Tags AWS::EMRServerless::Application ApplicationId,Arn Architecture,AutoStartConfiguration,AutoStopConfiguration,IdentityCenterConfiguration,ImageConfiguration,InitialCapacity,InteractiveConfiguration,MaximumCapacity,MonitoringConfiguration,Name,NetworkConfiguration,ReleaseLabel,RuntimeConfiguration,SchedulerConfiguration,Tags,Type,WorkerTypeSpecifications AWS::ElastiCache::CacheCluster ConfigurationEndpoint,RedisEndpoint AZMode,AutoMinorVersionUpgrade,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterName,Engine,EngineVersion,IpDiscovery,LogDeliveryConfigurations,NetworkType,NotificationTopicArn,NumCacheNodes,Port,PreferredAvailabilityZone,PreferredAvailabilityZones,PreferredMaintenanceWindow,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,Tags,TransitEncryptionEnabled,VpcSecurityGroupIds diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 4b27569c5f..9b4aec46da 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -109,6 +109,9 @@ AWS::EFS::FileSystem EfsCfnProvisioner AWS::EFS::MountTarget EfsCfnProvisioner AWS::EKS::Cluster EksCfnProvisioner AWS::EKS::Nodegroup EksCfnProvisioner +AWS::EMR::SecurityConfiguration EmrCfnProvisioner +AWS::EMR::Studio EmrStudioCfnProvisioner +AWS::EMR::StudioSessionMapping EmrStudioCfnProvisioner AWS::EMRContainers::VirtualCluster EmrContainersCfnProvisioner AWS::EMRServerless::Application EmrServerlessCfnProvisioner AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py index 35e5734e92..93a98c76a7 100644 --- a/tools/aws/regen_cfn_property_types.py +++ b/tools/aws/regen_cfn_property_types.py @@ -52,6 +52,7 @@ FETCH_TIMEOUT_SECONDS = 60 # The resource types whose provisioners read their properties through CfnPropertyTypes. RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster", + "AWS::EMR::SecurityConfiguration", "AWS::EMR::Studio", "AWS::EMR::StudioSessionMapping", "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application", "AWS::Events::Connection", "AWS::Events::Rule", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index d1d4ded9f2..ee5c2107d7 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -27,6 +27,7 @@ order: - AWS::ECS - AWS::EFS - AWS::EKS + - AWS::EMR - AWS::EMRContainers - AWS::EMRServerless - AWS::RDS @@ -99,6 +100,7 @@ type_order: AWS::ECS: [Cluster, TaskDefinition, Service] AWS::EFS: [FileSystem, MountTarget, AccessPoint] AWS::EKS: [Cluster, Nodegroup] + AWS::EMR: [SecurityConfiguration, Studio, StudioSessionMapping] AWS::RDS: [DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup] AWS::ElastiCache: @@ -158,6 +160,7 @@ service_labels: AWS::ECS: ECS AWS::EFS: EFS AWS::EKS: EKS + AWS::EMR: EMR AWS::EMRContainers: EMR on EKS AWS::EMRServerless: EMR Serverless AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2 @@ -232,6 +235,9 @@ notes: AWS::Transfer::User: 'management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user' AWS::EKS::Cluster: 'created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack, for `Logging`, for `AccessConfig.AuthenticationMode` (a mode cannot be moved back, so a stack update that does so fails, and a stack rollback restores it) and for `ResourcesVpcConfig` endpoint access and `PublicAccessCidrs`; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion`; a change to the subnets or security groups of `ResourcesVpcConfig` fails the resource, as the emulator''s `UpdateClusterConfig` does not change them' AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place' + AWS::EMR::SecurityConfiguration: 'created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template''s own `Name` is refused, as for every custom-named resource' + AWS::EMR::Studio: 'created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits' + AWS::EMR::StudioSessionMapping: '`Ref` is `StudioId|IdentityType|IdentityName`, the schema''s primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping' AWS::EMRContainers::VirtualCluster: 'created with `Name`, `ContainerProvider`, `SecurityConfigurationId`, `SessionEnabled` and `Tags`; a template that sets the read-only `Arn` or `Id` is refused; updated in place for `Tags` alone, which end as the template lists them, any other but an `aws:` one removed; a change to any other property replaces the virtual cluster, as the registry marks them create-only, and terminates the old one once the update commits; an update of a virtual cluster that is terminated or gone fails' AWS::EMRServerless::Application: 'created with every property, `Name` and `Type` included; updated in place through `UpdateApplication` for the settings a template changes, a dropped setting kept as it is but for `InitialCapacity`, which is cleared, and for `Tags`, which end as the template lists them, any other removed; a change to `Name` or `Type` replaces the application and deletes the old one once the update commits; neither an update nor a delete stops a `STARTED` application, so one it refuses fails the resource, as on AWS' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete'