diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationDeleteAfterFailedRollbackTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationDeleteAfterFailedRollbackTest.java index a660c305bd..36b93a2a47 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationDeleteAfterFailedRollbackTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationDeleteAfterFailedRollbackTest.java @@ -123,7 +123,7 @@ class CloudFormationDeleteAfterFailedRollbackTest { /** The role and log group; the update changes both and adds a group that collides with outsideGroup. */ private String template(boolean failingUpdate) { - String roleExtra = failingUpdate ? ", \"Description\": \"updated\"" : ""; + String rolePrincipal = !failingUpdate ? "lambda.amazonaws.com" : "events.amazonaws.com"; String groupExtra = failingUpdate ? ", \"RetentionInDays\": 7" : ""; String dup = failingUpdate ? """ , @@ -143,10 +143,10 @@ class CloudFormationDeleteAfterFailedRollbackTest { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", - "Principal": {"Service": "lambda.amazonaws.com"}, + "Principal": {"Service": "%s"}, "Action": "sts:AssumeRole" }] - }%s + } } }, "LogGroup": { @@ -155,7 +155,7 @@ class CloudFormationDeleteAfterFailedRollbackTest { }%s } } - """.formatted(roleName, roleExtra, logGroup, groupExtra, dup); + """.formatted(roleName, rolePrincipal, logGroup, groupExtra, dup); } private String awaitStable() throws InterruptedException { diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 933d4d2e9f..e95fc013da 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -3,6 +3,14 @@ **Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter **Endpoint:** `POST http://localhost:4566/` +## IAM role session duration + +`AWS::IAM::Role` applies `MaxSessionDuration` on creation and update, including +resolved parameters. Its range is 3,600 to 43,200 seconds; omitting the property +uses 3,600 seconds. Updates preserve the role's identity, and failed updates +restore its previous duration. The limit controls new STS sessions without +changing credentials already issued. + ## Supported Actions diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java index 52f0f28507..b36d310d7c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java @@ -1,12 +1,18 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.iam.IamRequestShapes; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.IamRole; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; import org.jboss.logging.Logger; import java.util.ArrayList; @@ -19,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.TreeSet; /** * CloudFormation provisioning for {@code AWS::IAM::Role}, moved out of the @@ -30,6 +37,9 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { private static final Logger LOG = Logger.getLogger(IamRoleCfnProvisioner.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String DURATION_SNAPSHOT_ATTR = "__FlociRoleDurationSnapshot"; + private static final String INLINE_NAMES_ATTR = "__FlociInlinePolicyNames"; private static final String MANAGED_ARNS_ATTR = "__FlociManagedPolicyArns"; @@ -69,6 +79,12 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { path = "/"; } String description = ctx.resolveOptional(props, "Description"); + Integer declaredDuration = ctx.resolveOptionalInt(props, "MaxSessionDuration"); + int maxSessionDuration = declaredDuration != null ? declaredDuration : 3600; + MultivaluedMap durationParams = new MultivaluedHashMap<>(); + durationParams.putSingle("RoleName", resolvedRoleName); + durationParams.putSingle("MaxSessionDuration", Integer.toString(maxSessionDuration)); + IamRequestShapes.check("UpdateRole", durationParams); List managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns"); // Blank means absent: Fn::If with Ref AWS::NoValue resolves to "" (CDK bootstrap does this). String permissionsBoundary = ctx.resolveOrDefault(props, "PermissionsBoundary", null); @@ -84,8 +100,9 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { String priorAssumeRoleId = null; // The adopted role's boundary before this attempt, restored on failure like the trust policy. String priorPermissionsBoundary = null; + int priorMaxSessionDuration = 3600; try { - role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, 3600, Map.of(), + role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, maxSessionDuration, Map.of(), permissionsBoundary); createdRole = true; r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); @@ -117,9 +134,11 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { // write, closing the gap between the check above and this call: a role deleted and // recreated under the same name in between would otherwise silently receive an update // meant for the role this stack actually owns. + snapshotDuration(r, role); priorAssumeRolePolicyDocument = role.getAssumeRolePolicyDocument(); priorAssumeRoleId = existingRoleId; priorPermissionsBoundary = role.getPermissionsBoundaryArn(); + priorMaxSessionDuration = role.getMaxSessionDuration(); iamService.updateAssumeRolePolicy(resolvedRoleName, assumeDoc, existingRoleId); } @@ -145,8 +164,14 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { final String documentToRestore = priorAssumeRolePolicyDocument; final String roleIdToRestore = priorAssumeRoleId; final String boundaryToRestore = priorPermissionsBoundary; + final int durationToRestore = priorMaxSessionDuration; boolean boundaryChangedByThisAttempt = false; + boolean durationChangedByThisAttempt = false; try { + if (!createdRole && maxSessionDuration != durationToRestore) { + iamService.updateRole(resolvedRoleName, null, maxSessionDuration, roleIdToRestore); + durationChangedByThisAttempt = true; + } // createRole() only applies PermissionsBoundary on first create. On adoption, set a // changed boundary, and remove one only if the role has one and the template dropped it. // ID-verified like the trust-policy write, here and in the rollback restore. @@ -271,6 +296,13 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { cleanupSucceeded = false; } } + if (durationChangedByThisAttempt) { + if (!CfnRollback.attemptIamCleanup(failure, + "restore prior session duration on role " + resolvedRoleName, + () -> iamService.updateRole(resolvedRoleName, null, durationToRestore, roleIdToRestore))) { + cleanupSucceeded = false; + } + } if (documentToRestore != null) { // ID-verified, same as the primary write above: if the role was deleted and // recreated under this name in between, this must not write the restored document @@ -298,6 +330,73 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { CfnTrackedSets.write(r, MANAGED_ARNS_ATTR, managedPolicyArns); } + private void snapshotDuration(StackResource resource, IamRole role) { + if (requiresUpdateRecovery(resource)) { + return; + } + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("name", role.getRoleName()); + snapshot.put("id", role.getRoleId()); + snapshot.put("duration", role.getMaxSessionDuration()); + snapshot.set("otherConfiguration", otherConfiguration(role)); + snapshot.set("attributes", MAPPER.valueToTree(resource.getAttributes())); + resource.getAttributes().put(DURATION_SNAPSHOT_ATTR, snapshot.toString()); + } + + private JsonNode otherConfiguration(IamRole role) { + ObjectNode configuration = MAPPER.createObjectNode(); + configuration.put("trust", role.getAssumeRolePolicyDocument()); + configuration.put("boundary", role.getPermissionsBoundaryArn()); + configuration.set("inline", MAPPER.valueToTree(role.getInlinePolicies())); + configuration.set("managed", MAPPER.valueToTree(new TreeSet<>(role.getAttachedPolicyArns()))); + return configuration; + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + String raw = resource.getAttributes().get(DURATION_SNAPSHOT_ATTR); + if (raw == null) { + return false; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Invalid IAM role duration rollback snapshot", e); + } + IamRole role = iamService.updateRole(snapshot.path("name").asText(), null, + snapshot.path("duration").asInt(), snapshot.path("id").asText()); + // Duration rollback must not report success for trust or policy changes it did not undo. + if (!snapshot.path("otherConfiguration").equals(otherConfiguration(role))) { + return false; + } + resource.getAttributes().clear(); + snapshot.path("attributes").properties().forEach(attribute -> + resource.getAttributes().put(attribute.getKey(), attribute.getValue().asText())); + return true; + } + + @Override + public boolean retainsFailedUpdateState(StackResource resource) { + return requiresUpdateRecovery(resource); + } + + @Override + public boolean requiresUpdateRecovery(StackResource resource) { + return resource.getAttributes().containsKey(DURATION_SNAPSHOT_ATTR); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + clearUpdate(resource); + return UpdateCleanupResult.notApplicable(); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(DURATION_SNAPSHOT_ATTR); + } + @Override public void delete(String resourceType, String physicalId, String region) { IamRole role; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java index accf85c1df..c42d6e1b07 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java @@ -33,7 +33,7 @@ import jakarta.ws.rs.core.MultivaluedMap; * outside its shape's rules carries the whole set the shape declares. {@code docs/services/iam.md} * records what moved with them and what did not. */ -final class IamRequestShapes { +public final class IamRequestShapes { private static final QueryConstraintCheck CHECK = QueryConstraintCheck.load( "aws/iam-request-shapes.json", "IAM request shapes", IamValidationErrors.MESSAGES); @@ -42,7 +42,7 @@ final class IamRequestShapes { } /** Throws {@code ValidationError} when the request breaks a constraint the model declares. */ - static void check(String action, MultivaluedMap params) { + public static void check(String action, MultivaluedMap params) { CHECK.check(action, params); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index b929c711a6..854288d582 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -1524,20 +1524,28 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * request carrying both is refused whole, before the description is written. */ public IamRole updateRole(String roleName, String description, int maxSessionDuration) { + return updateRole(roleName, description, maxSessionDuration, null); + } + + /** Applies an update only to the verified role, even if another role has since taken its name. */ + public IamRole updateRole(String roleName, String description, int maxSessionDuration, String expectedRoleId) { validateRoleName(roleName); validateRoleDescription(description); - IamRole role = getRole(roleName); - if (maxSessionDuration > 0) { - requireNotServiceLinked(role, roleName); + synchronized (resourceNameLock) { + IamRole role = getRole(roleName); + requireSameRole(role, roleName, expectedRoleId); + if (maxSessionDuration > 0) { + requireNotServiceLinked(role, roleName); + } + if (description != null) { + role.setDescription(description); + } + if (maxSessionDuration > 0) { + role.setMaxSessionDuration(maxSessionDuration); + } + roles.put(roleName, role); + return role; } - if (description != null) { - role.setDescription(description); - } - if (maxSessionDuration > 0) { - role.setMaxSessionDuration(maxSessionDuration); - } - roles.put(roleName, role); - return role; } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteAfterFailedRollbackIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteAfterFailedRollbackIntegrationTest.java index ddf5fd33cf..7cc1bf3925 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteAfterFailedRollbackIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteAfterFailedRollbackIntegrationTest.java @@ -117,7 +117,7 @@ class CloudFormationDeleteAfterFailedRollbackIntegrationTest { /** The role and log group, changed and joined by a colliding log group when outsideGroup is set. */ private static String template(String roleName, String logGroup, String outsideGroup) { - String roleExtra = outsideGroup == null ? "" : ", \"Description\": \"updated\""; + String rolePrincipal = outsideGroup == null ? "lambda.amazonaws.com" : "events.amazonaws.com"; String groupExtra = outsideGroup == null ? "" : ", \"RetentionInDays\": 7"; String dup = outsideGroup == null ? "" : """ , @@ -137,10 +137,10 @@ class CloudFormationDeleteAfterFailedRollbackIntegrationTest { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", - "Principal": {"Service": "lambda.amazonaws.com"}, + "Principal": {"Service": "%s"}, "Action": "sts:AssumeRole" }] - }%s + } } }, "LogGroup": { @@ -149,7 +149,7 @@ class CloudFormationDeleteAfterFailedRollbackIntegrationTest { }%s } } - """.formatted(roleName, roleExtra, logGroup, groupExtra, dup); + """.formatted(roleName, rolePrincipal, logGroup, groupExtra, dup); } private static Response cfn(String action, String stackName, String templateBody) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamRoleDurationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamRoleDurationIntegrationTest.java new file mode 100644 index 0000000000..88452451b9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamRoleDurationIntegrationTest.java @@ -0,0 +1,193 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.ValidateSignaturesProfile; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.NoSuchEntityException; +import software.amazon.awssdk.services.iam.model.Role; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.model.AssumeRoleResponse; +import software.amazon.awssdk.services.sts.model.StsException; + +import java.net.URI; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +@TestProfile(ValidateSignaturesProfile.class) +class CloudFormationIamRoleDurationIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private final String name = "cfn-duration-" + UUID.randomUUID(); + private final ObjectMapper mapper = new ObjectMapper(); + private final List sessions = new ArrayList<>(); + private CloudFormationClient cfn; + private IamClient iam; + private StsClient sts; + private boolean stackCreated; + + @TestHTTPResource + URI endpoint; + + @Inject + IamService iamService; + + @BeforeEach + void clients() { + cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.EU_WEST_1, endpoint); + iam = AwsTestClients.create(IamClient.builder(), "test", Region.EU_WEST_1, endpoint); + sts = AwsTestClients.create(StsClient.builder(), "test", Region.EU_WEST_1, endpoint); + } + + @AfterEach + void removeThisTestsStackAndSessions() { + try { + sessions.forEach(key -> iamService.unregisterSession(ACCOUNT, key)); + if (stackCreated) { + cfn.deleteStack(request -> request.stackName(name)); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> + assertThrows(NoSuchEntityException.class, + () -> iam.getRole(request -> request.roleName(name)))); + } + } finally { + sts.close(); + iam.close(); + cfn.close(); + } + } + + @Test + void templateDurationAllowsAnEightHourSession() { + create(28800); + assertEquals(28800, role().maxSessionDuration()); + assumeFor(28800); + assertRejected(28801); + } + + @Test + void updatesAndPropertyRemovalRetainRoleIdentityAndChangeNewSessionLimits() { + create(7200); + Role original = role(); + AssumeRoleResponse issued = assumeFor(7200); + Instant expiration = iamService.findSessionExpiration(issued.credentials().accessKeyId()).orElseThrow(); + + cfn.updateStack(request -> request.stackName(name).templateBody(template(43200, false)) + .parameters(parameter -> parameter.parameterKey("Duration").parameterValue("43200")) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + awaitStack("UPDATE_COMPLETE"); + assertEquals(original.roleId(), role().roleId()); + assertEquals(43200, role().maxSessionDuration()); + assumeFor(43200); + + cfn.updateStack(request -> request.stackName(name).templateBody(template(null, false)) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + awaitStack("UPDATE_COMPLETE"); + assertEquals(original.roleId(), role().roleId()); + assertEquals(3600, role().maxSessionDuration()); + assertRejected(3601); + assertEquals(expiration, iamService.findSessionExpiration( + issued.credentials().accessKeyId()).orElseThrow()); + } + + @Test + void failedUpdateRestoresTheOriginalDuration() { + create(7200); + Role original = role(); + cfn.updateStack(request -> request.stackName(name).templateBody(template(14400, true)) + .parameters(parameter -> parameter.parameterKey("Duration").parameterValue("14400")) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + awaitStack("UPDATE_ROLLBACK_COMPLETE"); + assertEquals(original.roleId(), role().roleId()); + assertEquals(7200, role().maxSessionDuration()); + assumeFor(7200); + assertRejected(7201); + } + + @Test + void laterResourceFailureRestoresTheEarlierSuccessfulRoleUpdate() throws Exception { + create(7200); + Role original = role(); + ObjectNode updated = (ObjectNode) mapper.readTree(template(14400, false)); + ObjectNode failure = ((ObjectNode) updated.get("Resources")).putObject("Failure") + .put("Type", "AWS::IAM::Role").put("DependsOn", "Role"); + failure.putObject("Properties").put("RoleName", name + "-invalid") + .put("MaxSessionDuration", 1); + cfn.updateStack(request -> request.stackName(name).templateBody(updated.toString()) + .parameters(parameter -> parameter.parameterKey("Duration").parameterValue("14400")) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + awaitStack("UPDATE_ROLLBACK_COMPLETE"); + assertEquals(original.roleId(), role().roleId()); + assertEquals(7200, role().maxSessionDuration()); + assumeFor(7200); + assertRejected(7201); + assertThrows(NoSuchEntityException.class, () -> iam.getRole(request -> request.roleName(name + "-invalid"))); + } + + private void create(int duration) { + cfn.createStack(request -> request.stackName(name).templateBody(template(duration, false)) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + stackCreated = true; + awaitStack("CREATE_COMPLETE"); + } + + private void awaitStack(String status) { + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> + assertEquals(status, cfn.describeStacks(request -> request.stackName(name)) + .stacks().getFirst().stackStatusAsString())); + } + + private Role role() { + return iam.getRole(request -> request.roleName(name)).role(); + } + + private AssumeRoleResponse assumeFor(int seconds) { + AssumeRoleResponse response = sts.assumeRole(request -> request.roleArn(role().arn()) + .roleSessionName("duration-check").durationSeconds(seconds)); + sessions.add(response.credentials().accessKeyId()); + assertFalse(response.credentials().expiration().isBefore(Instant.now().plusSeconds(seconds - 5))); + return response; + } + + private void assertRejected(int seconds) { + StsException error = assertThrows(StsException.class, () -> sts.assumeRole(request -> + request.roleArn(role().arn()).roleSessionName("rejected").durationSeconds(seconds))); + assertEquals(400, error.statusCode()); + assertEquals("ValidationError", error.awsErrorDetails().errorCode()); + } + + private String template(Integer duration, boolean missingManagedPolicy) { + ObjectNode template = mapper.createObjectNode(); + ObjectNode properties = template.putObject("Resources").putObject("Role") + .put("Type", "AWS::IAM::Role").putObject("Properties"); + properties.put("RoleName", name); + ObjectNode trust = properties.putObject("AssumeRolePolicyDocument").put("Version", "2012-10-17"); + trust.putArray("Statement").addObject().put("Effect", "Allow").put("Action", "sts:AssumeRole") + .putObject("Principal").put("AWS", "arn:aws:iam::" + ACCOUNT + ":root"); + if (duration != null) { + template.putObject("Parameters").putObject("Duration").put("Type", "Number").put("Default", duration); + properties.putObject("MaxSessionDuration").put("Ref", "Duration"); + } + if (missingManagedPolicy) { + properties.putArray("ManagedPolicyArns").add("arn:aws:iam::" + ACCOUNT + ":policy/missing-" + name); + } + return template.toString(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java index d8b066718b..3da2c95015 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java @@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.testutil.IamServiceTestHelper; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; @@ -17,6 +19,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -24,11 +27,14 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; /** @@ -96,6 +102,131 @@ class IamRoleCfnProvisionerTest { return role; } + @ParameterizedTest + @ValueSource(strings = {"0", "3599", "43201", "7200.5", "\"\"", "\"invalid\""}) + void invalidSessionDurationIsRejectedBeforeTouchingIam(String duration) { + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":" + duration + "}"), ctx())); + + assertEquals("ValidationError", failure.getErrorCode()); + verifyNoInteractions(iam); + } + + @ParameterizedTest + @ValueSource(ints = {3599, 43201}) + void durationRangeUsesTheIamQueryValidationMessage(int duration) { + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":" + duration + "}"), ctx())); + + String bound = duration < 3600 ? "greater than or equal to 3600" : "less than or equal to 43200"; + assertEquals("1 validation error detected: Value at 'maxSessionDuration' failed to satisfy constraint: " + + "Member must have value " + bound, failure.getMessage()); + verifyNoInteractions(iam); + } + + @Test + void durationUpdateCannotChangeAnotherRoleThatTookTheSameName() { + IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST); + IamRole original = realIam.createRole("app-role", "/", EMPTY_TRUST, null, 7200, Map.of()); + realIam.deleteRole("app-role"); + IamRole replacement = realIam.createRole("app-role", "/", EMPTY_TRUST, "new owner", 21600, Map.of()); + + AwsException failure = assertThrows(AwsException.class, + () -> realIam.updateRole("app-role", "old owner", 43200, original.getRoleId())); + + assertEquals("EntityAlreadyExists", failure.getErrorCode()); + assertNotEquals(original.getRoleId(), replacement.getRoleId()); + assertEquals(21600, realIam.getRole("app-role").getMaxSessionDuration()); + assertEquals("new owner", realIam.getRole("app-role").getDescription()); + } + + @Test + void rollbackDoesNotChangeAReplacementRoleWithTheSameName() { + IamService realIam = spy(IamServiceTestHelper.iamServiceWithUserPolicy( + "test", "secret", "user", EMPTY_TRUST)); + IamRoleCfnProvisioner realProvisioner = new IamRoleCfnProvisioner(realIam); + StackResource r = resource(); + realProvisioner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":7200}"), ctx()); + String originalId = realIam.getRole("app-role").getRoleId(); + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/missing"; + doAnswer(invocation -> { + realIam.deleteRole("app-role"); + realIam.createRole("app-role", "/", EMPTY_TRUST, "new owner", 21600, Map.of()); + throw new AwsException("NoSuchEntity", "policy missing", 404); + }).when(realIam).attachRolePolicy("app-role", policyArn); + + AwsException failure = assertThrows(AwsException.class, () -> realProvisioner.provision(r, + props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":14400," + + "\"ManagedPolicyArns\":[\"" + policyArn + "\"]}"), ctx())); + + assertEquals("NoSuchEntity", failure.getErrorCode()); + assertTrue(failure.getSuppressed().length > 0, "Refused rollback must remain visible"); + assertNotEquals(originalId, realIam.getRole("app-role").getRoleId()); + assertEquals(21600, realIam.getRole("app-role").getMaxSessionDuration()); + assertEquals("new owner", realIam.getRole("app-role").getDescription()); + } + + @Test + void stackRollbackRestoresDurationFromSerializedResource() throws Exception { + IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST); + IamRoleCfnProvisioner owner = new IamRoleCfnProvisioner(realIam); + StackResource r = resource(); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":7200}"), ctx()); + Map originalAttributes = new HashMap<>(r.getAttributes()); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":14400}"), ctx()); + assertEquals(14400, realIam.getRole("app-role").getMaxSessionDuration()); + ObjectMapper storageMapper = new ObjectMapper().findAndRegisterModules(); + StackResource restored = storageMapper.readValue(storageMapper.writeValueAsString(r), StackResource.class); + assertTrue(owner.rollbackUpdate(restored)); + assertEquals(7200, realIam.getRole("app-role").getMaxSessionDuration()); + assertEquals(originalAttributes, restored.getAttributes()); + assertFalse(owner.requiresUpdateRecovery(restored)); + assertFalse(owner.rollbackUpdate(restored)); + } + + @Test + void stackRollbackRejectsReplacementAndKeepsRecoverySnapshot() { + IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST); + IamRoleCfnProvisioner owner = new IamRoleCfnProvisioner(realIam); + StackResource r = resource(); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":7200}"), ctx()); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":14400}"), ctx()); + realIam.deleteRole("app-role"); + realIam.createRole("app-role", "/", EMPTY_TRUST, null, 21600, Map.of()); + assertThrows(AwsException.class, () -> owner.rollbackUpdate(r)); + assertEquals(21600, realIam.getRole("app-role").getMaxSessionDuration()); + assertTrue(owner.requiresUpdateRecovery(r)); + } + + @Test + void successfulCommitDiscardsOnlyTheCompletedDurationSnapshot() { + IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST); + IamRoleCfnProvisioner owner = new IamRoleCfnProvisioner(realIam); + StackResource r = resource(); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":7200}"), ctx()); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":14400}"), ctx()); + owner.completeUpdate(r); + assertFalse(owner.requiresUpdateRecovery(r)); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":21600}"), ctx()); + assertTrue(owner.rollbackUpdate(r)); + assertEquals(14400, realIam.getRole("app-role").getMaxSessionDuration()); + } + + @Test + void durationRestoreDoesNotClaimOtherPolicyChangesWereRolledBack() { + IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST); + IamRoleCfnProvisioner owner = new IamRoleCfnProvisioner(realIam); + StackResource r = resource(); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":7200}"), ctx()); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"MaxSessionDuration\":14400}"), ctx()); + realIam.putRolePolicy("app-role", "later", EMPTY_TRUST); + assertFalse(owner.rollbackUpdate(r)); + assertEquals(7200, realIam.getRole("app-role").getMaxSessionDuration()); + assertTrue(owner.requiresUpdateRecovery(r)); + realIam.deleteRolePolicy("app-role", "later"); + assertTrue(owner.rollbackUpdate(r)); + } + @Test void inlinePoliciesArePutOnTheRoleWithResolvedDocuments() { stubCreate("app-role"); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index af4758db67..24fbbb8191 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -366,7 +366,6 @@ AWS::IAM::ManagedPolicy Path accepted and ignored AWS::IAM::ManagedPolicy PolicyDocument accepted and ignored AWS::IAM::ManagedPolicy Users accepted and ignored AWS::IAM::Policy PolicyDocument accepted and ignored -AWS::IAM::Role MaxSessionDuration accepted and ignored AWS::IAM::Role Tags accepted and ignored AWS::IAM::User LoginProfile documented as ignored (docs/services/cloudformation.md, IAM) AWS::KMS::Key BypassPolicyLockoutSafetyCheck accepted and ignored