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

Move AWS::IAM::AccessKey and AWS::IAM::InstanceProfile out of the CloudFormationResourceProvisioner monolith into IamAccessKeyCfnProvisioner and IamInstanceProfileCfnProvisioner, each over IamService, matching the existing one-type-per-class IAM provisioners (IamRole, IamUser). The monolith keeps iamService, still used by the Policy and ManagedPolicy arms that migrate in a later PR.

Ref is preserved: the access key id for AccessKey, the profile name for InstanceProfile. The move also publishes AccessKey Id as an Fn::GetAtt key the monolith left unresolved, because leaving LEGACY_SWITCH subjects a type to CfnSchemaCoverageTest, which requires every readOnly attribute to be set; SecretAccessKey and InstanceProfile Arn were already set, so no gap rows are needed. InstanceProfile delete tolerates an already-gone profile via CfnDeletes.safeDelete on NoSuchEntity while letting DeleteConflict propagate. AccessKey keeps the legacy no-op delete (removing a key needs the owning user name the id-only path lacks); deleting it properly is a follow-up.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-19 09:58:21 -04:00
1 parent a154470172
commit fb9deb1e89
8 files changed
+461 -32

No files matched your search

@@ -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));
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
}