mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): delete AWS::IAM::User on stack deletion (#3076)
* fix(cloudformation): delete AWS::IAM::User on stack deletion (#2490) * fix(cloudformation): reconcile IAM user updates and verify user identity * fix(cloudformation): log intentionally tolerated errors during IAM user deletion * fix(cloudformation): use context helpers and assert Fn::GetAtt in IAM user provisioner * test(cloudformation): add AWS SDK compatibility test for IAM user * test(cloudformation): log tolerated exception during IAM user test cleanup * test(cloudformation): use Logger for cleanup in IAM user SDK test * test(cloudformation): use JBoss Logging for cleanup in IAM user SDK test * fix(cloudformation): address review feedback on IAM user provisioner --------- Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
This commit is contained in:
1 parent
4ee5a528f3
commit
7b5c6e272d
8 files changed
+1199
-14
No files matched your search
+2
@@ -39,6 +39,7 @@ 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.FirehoseCfnProvisioner;
|
||||
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;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotDomainConfigurationCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCfnProvisioner;
|
||||
@@ -233,6 +234,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (iamService != null) {
|
||||
discovered.add(new IamRoleCfnProvisioner(iamService));
|
||||
discovered.add(new IamUserCfnProvisioner(iamService));
|
||||
}
|
||||
if (ecsService != null) {
|
||||
discovered.add(new EcsCapacityCfnProvisioner(ecsService));
|
||||
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Verifies CloudFormation provisioning and deprovisioning lifecycle for {@code AWS::IAM::User}
|
||||
* (regression test for issue #2490).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationIamUserIntegrationTest {
|
||||
|
||||
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 deleteStackDeletesIamUserAndAllowsRecreation() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String userName = "probe-user-" + suffix;
|
||||
String stackName = "cfn-user-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"ProbeUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "ProbeUser"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["ProbeUser", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(userName);
|
||||
|
||||
String stackId = createStack(stackName, template);
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
String stackXml = describeStacks(stackId);
|
||||
assertEquals(userName, outputValue(stackXml, "UserRef"));
|
||||
String expectedArn = "arn:aws:iam::111122223333:user/" + userName;
|
||||
assertEquals(expectedArn, outputValue(stackXml, "UserArn"));
|
||||
|
||||
// Verify IAM user exists and Arn matches
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<UserName>" + userName + "</UserName>"))
|
||||
.body(containsString("<Arn>" + expectedArn + "</Arn>"));
|
||||
|
||||
// Delete the stack
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
|
||||
// Verify IAM user is gone (NoSuchEntity / 404)
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("NoSuchEntity"));
|
||||
|
||||
// Redeploying with the same explicit UserName succeeds rather than failing with EntityAlreadyExists
|
||||
String newStackName = "cfn-user-stack-recreate-" + suffix;
|
||||
String newStackId = createStack(newStackName, template);
|
||||
awaitStackStatus(newStackId, "CREATE_COMPLETE");
|
||||
|
||||
deleteStack(newStackName);
|
||||
awaitStackStatus(newStackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackDeletesUserWithGeneratedName() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-genuser-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"GenUser": {
|
||||
"Type": "AWS::IAM::User"
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "GenUser"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["GenUser", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String stackId = createStack(stackName, template);
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
String stackXml = describeStacks(stackId);
|
||||
String generatedUserName = outputValue(stackXml, "UserRef");
|
||||
assertNotNull(generatedUserName);
|
||||
assertEquals("arn:aws:iam::111122223333:user/" + generatedUserName, outputValue(stackXml, "UserArn"));
|
||||
|
||||
// Verify generated user exists
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", generatedUserName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<UserName>" + generatedUserName + "</UserName>"))
|
||||
.body(containsString("<Arn>arn:aws:iam::111122223333:user/" + generatedUserName + "</Arn>"));
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
|
||||
// Verify generated user is deleted
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", generatedUserName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("NoSuchEntity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackReconcilesGroupsPoliciesAndPath() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String userName = "update-user-" + suffix;
|
||||
String stackName = "cfn-update-user-stack-" + suffix;
|
||||
|
||||
// Pre-create two groups
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "CreateGroup")
|
||||
.formParam("GroupName", "group-a-" + suffix)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "CreateGroup")
|
||||
.formParam("GroupName", "group-b-" + suffix)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
String template1 = """
|
||||
{
|
||||
"Resources": {
|
||||
"TestUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s",
|
||||
"Path": "/initial/",
|
||||
"Groups": ["group-a-%s", "group-b-%s"],
|
||||
"ManagedPolicyArns": [
|
||||
"arn:aws:iam::aws:policy/ReadOnlyAccess",
|
||||
"arn:aws:iam::aws:policy/PowerUserAccess"
|
||||
],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "keep-policy",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
},
|
||||
{
|
||||
"PolicyName": "drop-policy",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(userName, suffix, suffix);
|
||||
|
||||
String stackId = createStack(stackName, template1);
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
// Verify initial state
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Path>/initial/</Path>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListAttachedUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("ReadOnlyAccess"))
|
||||
.body(containsString("PowerUserAccess"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<member>keep-policy</member>"))
|
||||
.body(containsString("<member>drop-policy</member>"));
|
||||
|
||||
// Update stack: change path to /updated/, drop group-b, drop PowerUserAccess, drop drop-policy
|
||||
String template2 = """
|
||||
{
|
||||
"Resources": {
|
||||
"TestUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s",
|
||||
"Path": "/updated/",
|
||||
"Groups": ["group-a-%s"],
|
||||
"ManagedPolicyArns": [
|
||||
"arn:aws:iam::aws:policy/ReadOnlyAccess"
|
||||
],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "keep-policy",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(userName, suffix);
|
||||
|
||||
updateStack(stackName, template2);
|
||||
awaitStackStatus(stackId, "UPDATE_COMPLETE");
|
||||
|
||||
// Verify updated path
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Path>/updated/</Path>"));
|
||||
|
||||
// Verify managed policy PowerUserAccess was detached
|
||||
String attachedPolicies = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListAttachedUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
assertThat(attachedPolicies, containsString("ReadOnlyAccess"));
|
||||
assertThat(attachedPolicies, org.hamcrest.Matchers.not(containsString("PowerUserAccess")));
|
||||
|
||||
// Verify drop-policy was deleted
|
||||
String inlinePolicies = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
assertThat(inlinePolicies, containsString("<member>keep-policy</member>"));
|
||||
assertThat(inlinePolicies, org.hamcrest.Matchers.not(containsString("<member>drop-policy</member>")));
|
||||
|
||||
// Verify group-b was removed
|
||||
String userGroups = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListGroupsForUser")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
assertThat(userGroups, containsString("group-a-" + suffix));
|
||||
assertThat(userGroups, org.hamcrest.Matchers.not(containsString("group-b-" + suffix)));
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
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 updateStack(String stackName, String template) {
|
||||
cfnQuery("UpdateStack", stackName, template)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteStack(String stackName) {
|
||||
cfnQuery("DeleteStack", stackName)
|
||||
.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).then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
private static Response cfnQuery(String action, String stackName) {
|
||||
return cfnQuery(action, stackName, null);
|
||||
}
|
||||
|
||||
private static Response cfnQuery(String action, String stackName, String template) {
|
||||
var 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);
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
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.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IamUserCfnProvisionerTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
|
||||
private final IamService iam = mock(IamService.class);
|
||||
private final IamUserCfnProvisioner provisioner = new IamUserCfnProvisioner(iam);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
// resolveStringList delegates to the real engine method; for the literal arrays these
|
||||
// tests use it just walks the array and calls resolve(...) per element, stubbed above.
|
||||
when(engine.resolveStringList(any())).thenCallRealMethod();
|
||||
|
||||
when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node != null && node.isTextual() ? node.asText() : node.toString();
|
||||
});
|
||||
|
||||
return new ProvisionContext(engine, "us-east-1", ACCOUNT_ID, "test-stack");
|
||||
}
|
||||
|
||||
private ProvisionContext updateCtx(String priorPhysicalId) {
|
||||
ProvisionContext base = ctx();
|
||||
return new ProvisionContext(base.engine(), base.region(), base.accountId(), base.stackName(), priorPhysicalId);
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("AppUser");
|
||||
r.setResourceType("AWS::IAM::User");
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private JsonNode props(String json) {
|
||||
try {
|
||||
return mapper.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private IamUser stubCreate(String userName, String path) {
|
||||
IamUser user = new IamUser("AIDA" + userName, userName, path,
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":user" + path + userName);
|
||||
when(iam.createUser(eq(userName), eq(path))).thenReturn(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
@Test
|
||||
void declaresIamUserResourceType() {
|
||||
assertEquals(java.util.Set.of("AWS::IAM::User"), provisioner.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionCreatesUserWithExplicitUserNameAndDefaultPath() {
|
||||
stubCreate("custom-user", "/");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "custom-user"
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
assertEquals("custom-user", r.getPhysicalId());
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/custom-user", r.getAttributes().get("Arn"));
|
||||
verify(iam).createUser("custom-user", "/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionCreatesUserWithCustomPath() {
|
||||
stubCreate("custom-user", "/engineering/");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "custom-user",
|
||||
"Path": "/engineering/"
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
assertEquals("custom-user", r.getPhysicalId());
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/engineering/custom-user", r.getAttributes().get("Arn"));
|
||||
verify(iam).createUser("custom-user", "/engineering/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionGeneratesPhysicalNameWhenUserNameIsOmitted() {
|
||||
when(iam.createUser(any(), eq("/"))).thenAnswer(inv -> {
|
||||
String name = inv.getArgument(0);
|
||||
return new IamUser("AIDA" + name, name, "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/" + name);
|
||||
});
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode(), ctx());
|
||||
|
||||
assertNotNull(r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().contains("test-stack"));
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/" + r.getPhysicalId(), r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionAttachesManagedPoliciesAndInlinePoliciesAndGroups() {
|
||||
IamUser user = stubCreate("app-user", "/");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "app-user",
|
||||
"Groups": ["developers", "qa"],
|
||||
"ManagedPolicyArns": [
|
||||
"arn:aws:iam::aws:policy/ReadOnlyAccess",
|
||||
"arn:aws:iam::aws:policy/PowerUserAccess"
|
||||
],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "s3-access",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
verify(iam).addUserToGroup("developers", "app-user");
|
||||
verify(iam).addUserToGroup("qa", "app-user");
|
||||
verify(iam).attachUserPolicy("app-user", "arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
verify(iam).attachUserPolicy("app-user", "arn:aws:iam::aws:policy/PowerUserAccess");
|
||||
verify(iam).putUserPolicy(eq("app-user"), eq("s3-access"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingUserNameRequiresReplacement() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("old-user");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () ->
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "new-user"
|
||||
}
|
||||
"""), updateCtx("old-user")));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("resource replacement"));
|
||||
verify(iam, never()).createUser(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDetachesPoliciesRemovesGroupsAndDeletesUser() {
|
||||
IamUser user = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
user.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
user.getInlinePolicies().put("inline-1", "{}");
|
||||
user.getGroupNames().add("dev-group");
|
||||
when(iam.getUser("my-user")).thenReturn(user);
|
||||
|
||||
AccessKey key = new AccessKey("AKIA123", "secret", "my-user");
|
||||
when(iam.listAccessKeys("my-user")).thenReturn(List.of(key));
|
||||
|
||||
provisioner.delete("AWS::IAM::User", "my-user", "us-east-1");
|
||||
|
||||
verify(iam).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
verify(iam).deleteUserPolicy("my-user", "inline-1");
|
||||
verify(iam).removeUserFromGroup("dev-group", "my-user");
|
||||
verify(iam).deleteAccessKey("my-user", "AKIA123");
|
||||
verify(iam).deleteUser("my-user");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAlreadyDeletedUser() {
|
||||
when(iam.getUser("already-gone"))
|
||||
.thenThrow(new AwsException("NoSuchEntity", "User does not exist", 404));
|
||||
|
||||
provisioner.delete("AWS::IAM::User", "already-gone", "us-east-1");
|
||||
|
||||
verify(iam, never()).deleteUser(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReconcilesRemovedGroupsManagedPoliciesAndInlinePolicies() {
|
||||
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
existing.getGroupNames().add("keep-group");
|
||||
existing.getGroupNames().add("drop-group");
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Keep");
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Drop");
|
||||
existing.getInlinePolicies().put("keep-inline", "{}");
|
||||
existing.getInlinePolicies().put("drop-inline", "{}");
|
||||
|
||||
when(iam.createUser(eq("my-user"), eq("/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getUser("my-user")).thenReturn(existing);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAuser");
|
||||
r.getAttributes().put("__FlociGroups", "keep-group\ndrop-group");
|
||||
r.getAttributes().put("__FlociManagedPolicyArns", "arn:aws:iam::aws:policy/Keep\narn:aws:iam::aws:policy/Drop");
|
||||
r.getAttributes().put("__FlociInlinePolicyNames", "keep-inline\ndrop-inline");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user",
|
||||
"Groups": ["keep-group"],
|
||||
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/Keep"],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "keep-inline",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
"""), updateCtx("my-user"));
|
||||
|
||||
verify(iam).removeUserFromGroup("drop-group", "my-user");
|
||||
verify(iam).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/Drop");
|
||||
verify(iam).deleteUserPolicy("my-user", "drop-inline");
|
||||
verify(iam, never()).removeUserFromGroup("keep-group", "my-user");
|
||||
verify(iam, never()).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/Keep");
|
||||
verify(iam, never()).deleteUserPolicy("my-user", "keep-inline");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReconcilesPathChange() {
|
||||
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
when(iam.createUser(eq("my-user"), eq("/new-path/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getUser("my-user")).thenReturn(existing);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAuser");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user",
|
||||
"Path": "/new-path/"
|
||||
}
|
||||
"""), updateCtx("my-user"));
|
||||
|
||||
verify(iam).updateUser("my-user", null, "/new-path/", "AIDAuser");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRefusesToAdoptReplacementUserWithDifferentUserId() {
|
||||
IamUser replacement = new IamUser("AIDAnew-user", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
when(iam.createUser(eq("my-user"), eq("/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getUser("my-user")).thenReturn(replacement);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAold-user");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () ->
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user"
|
||||
}
|
||||
"""), updateCtx("my-user")));
|
||||
|
||||
assertEquals("EntityAlreadyExists", failure.getErrorCode());
|
||||
verify(iam, never()).addUserToGroup(any(), any());
|
||||
verify(iam, never()).attachUserPolicy(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdateRestoresPriorInlinePolicyAndDetachesNewManagedPolicy() {
|
||||
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
String priorDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[\"prior\"]}";
|
||||
existing.getInlinePolicies().put("first", priorDocument);
|
||||
when(iam.createUser(eq("my-user"), eq("/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getUser("my-user")).thenReturn(existing);
|
||||
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
|
||||
.when(iam).putUserPolicy(eq("my-user"), eq("second"), any());
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAuser");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user",
|
||||
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/NewPolicy"],
|
||||
"Policies": [
|
||||
{"PolicyName": "first", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
|
||||
{"PolicyName": "second", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), updateCtx("my-user")));
|
||||
|
||||
verify(iam).attachUserPolicy("my-user", "arn:aws:iam::aws:policy/NewPolicy");
|
||||
verify(iam).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/NewPolicy");
|
||||
verify(iam).putUserPolicy("my-user", "first", priorDocument);
|
||||
verify(iam, never()).deleteUser("my-user");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user