Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

refactor(cloudformation): move IAM leaf types into per-type provisioners (#3913)

Hector Venturafb9deb1e89a5
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index f8dd2d6504..f2afdfb95e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -108,8 +108,6 @@ public class CloudFormationResourceProvisioner {
"AWS::ApiGatewayV2::Route",
"AWS::ApiGatewayV2::Stage",
"AWS::CloudFormation::CustomResource",
- "AWS::IAM::AccessKey",
- "AWS::IAM::InstanceProfile",
"AWS::IAM::ManagedPolicy",
"AWS::IAM::Policy",
"AWS::Lambda::Function",
@@ -217,11 +215,9 @@ public class CloudFormationResourceProvisioner {
case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName);
case "AWS::Lambda::LayerVersion" ->
provisionLambdaLayerVersion(resource, properties, engine, region, stackName);
- case "AWS::IAM::AccessKey" -> provisionIamAccessKey(resource, properties, engine);
case "AWS::IAM::Policy" -> provisionIamInlinePolicy(resource, properties, engine, stackName);
case "AWS::IAM::ManagedPolicy" ->
provisionIamManagedPolicy(resource, properties, engine, accountId, stackName);
- case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId, stackName);
case "AWS::ApiGatewayV2::Api" -> provisionApiGatewayV2Api(resource, properties, engine, region, accountId, stackName);
case "AWS::ApiGatewayV2::Authorizer" -> provisionApiGatewayV2Authorizer(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Route" -> provisionApiGatewayV2Route(resource, properties, engine, region);
@@ -425,7 +421,6 @@ public class CloudFormationResourceProvisioner {
// Nothing to do here when only the physical id (policy name) is known, as on rollback.
case "AWS::IAM::Policy" -> { }
case "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
- case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
// No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus.
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
@@ -1530,22 +1525,6 @@ public class CloudFormationResourceProvisioner {
// ── IAM Instance Profile ──────────────────────────────────────────────────
- private void provisionInstanceProfile(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String accountId, String stackName) {
- String name = resolveOptional(props, "InstanceProfileName", engine);
- if (name == null || name.isBlank()) {
- name = generatePhysicalName(stackName, r.getLogicalId(), 128, false);
- }
- try {
- var profile = iamService.createInstanceProfile(name, "/");
- r.setPhysicalId(name);
- r.getAttributes().put("Arn", profile.getArn());
- } catch (Exception e) {
- r.setPhysicalId(name);
- r.getAttributes().put("Arn", AwsArnUtils.Arn.of("iam", "", accountId, "instance-profile/" + name).toString());
- }
- }
-
// ── Pipes ──────────────────────────────────────────────────────────────────
/**
@@ -1617,15 +1596,6 @@ public class CloudFormationResourceProvisioner {
// ── Helpers ───────────────────────────────────────────────────────────────
- private void provisionIamAccessKey(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
- String userName = resolveOptional(props, "UserName", engine);
- if (userName != null) {
- var key = iamService.createAccessKey(userName);
- r.setPhysicalId(key.getAccessKeyId());
- r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey());
- }
- }
-
// ── ApiGateway (V1) ──────────────────────────────────────────────────────
// ── ApiGatewayV2 (HTTP/WebSocket) ────────────────────────────────────────
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java
new file mode 100644
index 0000000000..3dc82199ef
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java
@@ -0,0 +1,48 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.AccessKey;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::IAM::AccessKey}. {@code Ref} returns the access key
+ * id (the primary identifier), and {@code Fn::GetAtt} exposes the same id plus the one-time
+ * {@code SecretAccessKey}.
+ *
+ * <p>No delete is overridden: removing an access key needs the owning user name, which the
+ * id-only delete path does not carry, so the legacy switch left it a no-op. Storing the user name
+ * and deleting the key is a follow-up.
+ */
+@ApplicationScoped
+public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String TYPE = "AWS::IAM::AccessKey";
+
+ private final IamService iamService;
+
+ @Inject
+ public IamAccessKeyCfnProvisioner(IamService iamService) {
+ this.iamService = iamService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String userName = ctx.resolveOptional(props, "UserName");
+ if (userName != null) {
+ AccessKey key = iamService.createAccessKey(userName);
+ r.setPhysicalId(key.getAccessKeyId());
+ r.getAttributes().put("Id", key.getAccessKeyId());
+ r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey());
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java
new file mode 100644
index 0000000000..2dfe769105
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java
@@ -0,0 +1,64 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::IAM::InstanceProfile}. {@code Ref} returns the
+ * instance profile name (the primary identifier) and {@code Fn::GetAtt Arn} its arn.
+ */
+@ApplicationScoped
+public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(IamInstanceProfileCfnProvisioner.class);
+
+ private static final String TYPE = "AWS::IAM::InstanceProfile";
+
+ private final IamService iamService;
+
+ @Inject
+ public IamInstanceProfileCfnProvisioner(IamService iamService) {
+ this.iamService = iamService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = ctx.resolveOptional(props, "InstanceProfileName");
+ if (name == null || name.isBlank()) {
+ name = ctx.generatePhysicalName(r.getLogicalId(), 128, false);
+ }
+ r.setPhysicalId(name);
+ try {
+ InstanceProfile profile = iamService.createInstanceProfile(name, "/");
+ r.getAttributes().put("Arn", profile.getArn());
+ } catch (RuntimeException e) {
+ // A create collision (the profile already exists) is tolerated as the legacy switch did:
+ // synthesize the arn so Fn::GetAtt Arn still resolves rather than failing the stack.
+ LOG.debugv("createInstanceProfile fell back to a synthesized arn for {0}: {1}",
+ name, e.getMessage());
+ r.getAttributes().put("Arn",
+ AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "instance-profile/" + name).toString());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ // deleteInstanceProfile still throws DeleteConflict when roles are attached, which must
+ // propagate so the stack reports DELETE_FAILED; only the already-gone case is tolerated.
+ CfnDeletes.safeDelete("IAM instance profile", physicalId,
+ () -> iamService.deleteInstanceProfile(physicalId), "NoSuchEntity");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 592b75b7ff..fae6edc5dc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -60,6 +60,8 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapaci
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.IamAccessKeyCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.IamInstanceProfileCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotCfnProvisioner;
@@ -291,6 +293,8 @@ final class CfnProvisionerFixture {
if (iamService != null) {
discovered.add(new IamRoleCfnProvisioner(iamService));
discovered.add(new IamUserCfnProvisioner(iamService));
+ discovered.add(new IamAccessKeyCfnProvisioner(iamService));
+ discovered.add(new IamInstanceProfileCfnProvisioner(iamService));
}
if (eksService != null) {
discovered.add(new EksCfnProvisioner(eksService));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.java
new file mode 100644
index 0000000000..a6295971f3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.java
@@ -0,0 +1,144 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * End-to-end check that CloudFormation provisions the leaf IAM types into IamService for real
+ * rather than stubbing them: {@code AWS::IAM::AccessKey} Ref resolves to a real access key id, and
+ * {@code AWS::IAM::InstanceProfile} Fn::GetAtt Arn resolves to a real instance-profile arn.
+ */
+@QuarkusTest
+class CloudFormationIamLeafIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=111122223333/20260205/us-east-1/cloudformation/aws4_request";
+ private static final String IAM_AUTH =
+ "AWS4-HMAC-SHA256 Credential=111122223333/20260205/us-east-1/iam/aws4_request";
+
+ @Test
+ void createStackProvisionsAccessKeyAndInstanceProfile() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String userName = "leaf-user-" + suffix;
+ String profileName = "leaf-profile-" + suffix;
+ String stackName = "cfn-iam-leaf-" + suffix;
+
+ String template = """
+ {
+ "Resources": {
+ "User": {
+ "Type": "AWS::IAM::User",
+ "Properties": {"UserName": "%s"}
+ },
+ "Key": {
+ "Type": "AWS::IAM::AccessKey",
+ "Properties": {"UserName": {"Ref": "User"}}
+ },
+ "Profile": {
+ "Type": "AWS::IAM::InstanceProfile",
+ "Properties": {"InstanceProfileName": "%s"}
+ }
+ },
+ "Outputs": {
+ "KeyRef": {"Value": {"Ref": "Key"}},
+ "KeyId": {"Value": {"Fn::GetAtt": ["Key", "Id"]}},
+ "ProfileArn": {"Value": {"Fn::GetAtt": ["Profile", "Arn"]}}
+ }
+ }
+ """.formatted(userName, profileName);
+
+ String stackId = createStack(stackName, template);
+ awaitStackStatus(stackId, "CREATE_COMPLETE");
+
+ String stackXml = describeStacks(stackId);
+ String keyRef = outputValue(stackXml, "KeyRef");
+ // Ref and Fn::GetAtt Id resolve to the same real access key id, not the literal "Key.Id".
+ assertEquals(keyRef, outputValue(stackXml, "KeyId"));
+ assertTrue(keyRef != null && !keyRef.isBlank() && !keyRef.contains("Key."), keyRef);
+
+ String profileArn = outputValue(stackXml, "ProfileArn");
+ assertEquals("arn:aws:iam::111122223333:instance-profile/" + profileName, profileArn);
+
+ // The instance profile really exists in IAM (provisioned, not stubbed).
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", "GetInstanceProfile")
+ .formParam("InstanceProfileName", profileName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<InstanceProfileName>" + profileName + "</InstanceProfileName>"));
+
+ deleteStack(stackName);
+ awaitStackStatus(stackId, "DELETE_COMPLETE");
+
+ // The instance profile is gone after the stack delete.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", "GetInstanceProfile")
+ .formParam("InstanceProfileName", profileName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchEntity"));
+ }
+
+ private static String createStack(String stackName, String template) {
+ return cfnQuery("CreateStack", stackName, template)
+ .then()
+ .statusCode(200)
+ .extract()
+ .xmlPath()
+ .getString("CreateStackResponse.CreateStackResult.StackId");
+ }
+
+ private static void deleteStack(String stackName) {
+ cfnQuery("DeleteStack", stackName, null).then().statusCode(200);
+ }
+
+ private static void awaitStackStatus(String stackId, String status) throws InterruptedException {
+ String xml = "";
+ long deadline = System.currentTimeMillis() + 10_000;
+ while (System.currentTimeMillis() < deadline) {
+ xml = describeStacks(stackId);
+ if (xml.contains("<StackStatus>" + status + "</StackStatus>")) {
+ return;
+ }
+ Thread.sleep(50);
+ }
+ fail("stack " + stackId + " never reached " + status + ": " + xml);
+ }
+
+ private static String describeStacks(String stackId) {
+ return cfnQuery("DescribeStacks", stackId, null).then().statusCode(200).extract().asString();
+ }
+
+ private static Response cfnQuery(String action, String stackName, String template) {
+ RequestSpecification req = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", action)
+ .formParam("StackName", stackName);
+ if (template != null) {
+ req.formParam("TemplateBody", template);
+ }
+ return req.when().post("/");
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java
new file mode 100644
index 0000000000..afff2441c2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java
@@ -0,0 +1,78 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.AccessKey;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code AWS::IAM::AccessKey} in isolation: the id backs Ref and Fn::GetAtt, the secret is
+ * published, and an absent UserName creates nothing.
+ */
+class IamAccessKeyCfnProvisionerTest {
+
+ private static final String TYPE = "AWS::IAM::AccessKey";
+
+ private final IamService iam = mock(IamService.class);
+ private final IamAccessKeyCfnProvisioner provisioner = new IamAccessKeyCfnProvisioner(iam);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ void publishesTheIdAndSecret() throws Exception {
+ AccessKey key = new AccessKey();
+ key.setAccessKeyId("AKIA123");
+ key.setSecretAccessKey("secret-xyz");
+ when(iam.createAccessKey("alice")).thenReturn(key);
+
+ StackResource r = resource();
+ provisioner.provision(r, props("{\"UserName\": \"alice\"}"), ctx());
+
+ assertEquals("AKIA123", r.getPhysicalId());
+ assertEquals(Set.of("Id", "SecretAccessKey"), r.getAttributes().keySet());
+ assertEquals("AKIA123", r.getAttributes().get("Id"));
+ assertEquals("secret-xyz", r.getAttributes().get("SecretAccessKey"));
+ verify(iam).createAccessKey("alice");
+ }
+
+ @Test
+ void absentUserNameCreatesNothing() throws Exception {
+ StackResource r = resource();
+ provisioner.provision(r, props("{}"), ctx());
+
+ verifyNoInteractions(iam);
+ }
+
+ private ProvisionContext ctx() {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.asText();
+ });
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
+ }
+
+ private JsonNode props(String json) throws Exception {
+ return mapper.readTree(json);
+ }
+
+ private static StackResource resource() {
+ StackResource r = new StackResource();
+ r.setLogicalId("Key");
+ r.setResourceType(TYPE);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java
new file mode 100644
index 0000000000..635a1e4dbb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java
@@ -0,0 +1,121 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+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.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code AWS::IAM::InstanceProfile} in isolation: Ref is the name, Fn::GetAtt Arn is the arn, the
+ * generated name, the synthesized-arn fallback on a create collision, and the delete tolerance.
+ */
+class IamInstanceProfileCfnProvisionerTest {
+
+ private static final String TYPE = "AWS::IAM::InstanceProfile";
+
+ private final IamService iam = mock(IamService.class);
+ private final IamInstanceProfileCfnProvisioner provisioner = new IamInstanceProfileCfnProvisioner(iam);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ void publishesNameAndArn() throws Exception {
+ InstanceProfile profile = new InstanceProfile();
+ profile.setArn("arn:aws:iam::000000000000:instance-profile/web");
+ when(iam.createInstanceProfile("web", "/")).thenReturn(profile);
+
+ StackResource r = resource();
+ provisioner.provision(r, props("{\"InstanceProfileName\": \"web\"}"), ctx());
+
+ assertEquals("web", r.getPhysicalId());
+ assertEquals(Set.of("Arn"), r.getAttributes().keySet());
+ assertEquals("arn:aws:iam::000000000000:instance-profile/web", r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void absentNameIsGeneratedFromStackAndLogicalId() throws Exception {
+ InstanceProfile profile = new InstanceProfile();
+ profile.setArn("arn:aws:iam::000000000000:instance-profile/generated");
+ when(iam.createInstanceProfile(anyString(), eq("/"))).thenReturn(profile);
+
+ StackResource r = resource();
+ provisioner.provision(r, props("{}"), ctx());
+
+ assertTrue(r.getPhysicalId().matches("my-stack-Profile-[0-9a-f]{12}"), r.getPhysicalId());
+ }
+
+ @Test
+ void aCreateCollisionFallsBackToASynthesizedArn() throws Exception {
+ when(iam.createInstanceProfile("web", "/"))
+ .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
+
+ StackResource r = resource();
+ provisioner.provision(r, props("{\"InstanceProfileName\": \"web\"}"), ctx());
+
+ assertEquals("web", r.getPhysicalId());
+ assertEquals("arn:aws:iam::000000000000:instance-profile/web", r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void deleteRemovesTheProfile() {
+ provisioner.delete(TYPE, "web", "us-east-1");
+
+ org.mockito.Mockito.verify(iam).deleteInstanceProfile("web");
+ }
+
+ @Test
+ void deleteToleratesAProfileAlreadyGone() {
+ doThrow(new AwsException("NoSuchEntity", "gone", 404))
+ .when(iam).deleteInstanceProfile("web");
+
+ assertDoesNotThrow(() -> provisioner.delete(TYPE, "web", "us-east-1"));
+ }
+
+ @Test
+ void deletePropagatesADeleteConflict() {
+ doThrow(new AwsException("DeleteConflict", "roles attached", 409))
+ .when(iam).deleteInstanceProfile("web");
+
+ AwsException failure = assertThrows(AwsException.class,
+ () -> provisioner.delete(TYPE, "web", "us-east-1"));
+ assertEquals("DeleteConflict", failure.getErrorCode());
+ }
+
+ private ProvisionContext ctx() {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.asText();
+ });
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
+ }
+
+ private JsonNode props(String json) throws Exception {
+ return mapper.readTree(json);
+ }
+
+ private static StackResource resource() {
+ StackResource r = new StackResource();
+ r.setLogicalId("Profile");
+ r.setResourceType(TYPE);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index b0c3afad62..efa83c7641 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -86,8 +86,8 @@ AWS::ElasticLoadBalancingV2::TargetGroup ElbV2CfnProvisioner
AWS::Events::EventBus EventsCfnProvisioner
AWS::Events::EventBusPolicy EventsCfnProvisioner
AWS::Events::Rule EventsCfnProvisioner
-AWS::IAM::AccessKey LEGACY_SWITCH
-AWS::IAM::InstanceProfile LEGACY_SWITCH
+AWS::IAM::AccessKey IamAccessKeyCfnProvisioner
+AWS::IAM::InstanceProfile IamInstanceProfileCfnProvisioner
AWS::IAM::ManagedPolicy LEGACY_SWITCH
AWS::IAM::Policy LEGACY_SWITCH
AWS::IAM::Role IamRoleCfnProvisioner